1.引入第三方包
java
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2.代码如下
java
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MySQLPortForwarding {
public static void main(String[] args) throws Exception{
String sshHost = ""; //服务器ip
String sshUsername = ""; //用户名称
String sshPassword = ""; //用户密码
String remoteHost = "localhost";
int localPort = 3307; // 本地端口
int remotePort = 3306; // 远程MySQL服务器端口
JSch jsch = new JSch();
Session session = jsch.getSession(sshUsername, sshHost, 22);
session.setPassword(sshPassword);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("建立SSH连接...");
session.connect();
/* //这步是做端口转发的,与文章无关,目的:服务器安装的有mysql,然后防火墙没开3306,本地无法直接连接mysql,
// 这一步本地可以用过localhost:3307连接服务器的mysql
int assignedPort = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("本地端口 " + assignedPort + " 被转发到 " + remoteHost + ":" + remotePort);*/
String command = "tail -f " + "/tmp/debug.log";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 实时打印日志内容
}
channel.disconnect();
session.disconnect();
}
}