问题描述
我是 JAVA 新手。 我试图编写一个应用程序,接下来将执行 - 打开到 UNIX 服务器的 ssh 连接,并使用私钥从该服务器连接到另一台服务器。
要连接到第一台服务器,我正在使用如下程序:
public static void main(String args[])
{
String user = "john";
String password = "mypassword";
String host = "192.168.100.23";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Crating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
br.close();
}
catch(Exception e){System.err.print(e);}
}
它工作正常。 但是当我尝试使用相同的代码连接到第二个时,这不起作用,因为应用程序试图创建一个全新的连接而不使用已经创建的连接。
有人知道如何让应用程序使用已创建的连接吗?
谢谢。
1楼
您可以在第一个session
中使用端口转发来做到这一点,然后在转发的本地端口中创建另一个连接到主机的session
。
示例正是这样做的。
公钥认证参考
这是基于这些示例对您的代码的修改:
String user = "john";
String password = "mypassword";
String host = "127.0.0.1";
String host2 = "192.168.100.23";
int port=22;
try{
JSch jsch = new JSch();
Session session1 = jsch.getSession(user, host, port);
session1.setPassword(password);
session1.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session1.connect();
System.out.println("Connection established.");
//Here we do port forwarding to the second host
int assinged_port = session1.setPortForwardingL(0, host2, 22);
System.out.println("portforwarding: "+
"localhost:"+assinged_port+" -> "+host+":"+22);
//And here we connect to the first host to the forwarded port, not 22
Session session2 = jsch.getSession(user, host, assinged_port);
//This is your public key file
jsch.addIdentity("~/.ssh/id_rsa");
session2.setConfig("StrictHostKeyChecking", "no");
session2.connect();
System.out.println("The session has been established to "+
user+"@"+host);
System.out.println("Crating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session2.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
br.close();
}
catch(Exception e){System.err.print(e);}