在远程服务器上执行ssh跳转到另一台服务器,并使用Java和JSch在该服务器上执行更多命令

问题描述 投票:0回答:1

我正在尝试使用JSch库通过SSH在远程计算机上执行多个命令。我快到了,但被困在一个命令中。

我正在使用两台远程计算机,比如说RM1和RM2

可以执行以下步骤,

  1. 能够连接到远程机器RM1。
  2. 能够在RM1上执行单个/多个命令(此https://www.journaldev.com/246/jsch-example-java-ssh-unix-serverhttps://stackoverflow.com/a/5831846/8773024之后)。
  3. 能够连接到远程机器RM1,然后再次连接到另一个远程机器RM2。

无法执行此步骤,1.一旦我将无法执行任何命令后连接到远程机器RM2。

[请让我知道是否有人可以帮助我。

我尝试过此代码:

String host="IP";
String user="username";
String password="password";
String command1="pwd";
String command2="ssh -tt user@ip";
String command3="pwd";

java.util.Properties config = new java.util.Properties(); 
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");        

Channel channel1=session.openChannel("exec");
((ChannelExec)channel1).setCommand(command1;command2;command3);

channel1.setInputStream(null);
((ChannelExec)channel1).setErrStream(System.err);            
InputStream in1=channel1.getInputStream();
channel1.connect();
byte[] tmp=new byte[1024];
while(true){
  while(in1.available()>0){
    int i=in1.read(tmp, 0, 1024);
    if(i<0)break;
    System.out.print(new String(tmp, 0, i));
  }
  if(channel1.isConnected()){
    System.out.println("exit-status: "+channel1.getExitStatus());
    break;
  }
  try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
java command remote-server jsch
1个回答
0
投票

[尝试在连接到RM1的普通SSH终端客户端中执行pwd;ssh -tt user@ip;pwd。它不起作用,因此它也无法在Java中起作用。

要执行“跳转”,您应该使用端口转发(请参阅JSch JumpHosts example),而不是在跳转服务器上执行JumpHosts

© www.soinside.com 2019 - 2024. All rights reserved.