Percy

使用JSch setCommand执行时,带有source选项的Shell ping命令失败

java

我正在测试短ping测试程序。如果我将简单的ping命令设置"ping y.y.y.y -c 5 -s 500 "为setCommand()功能,它将按设计工作。但是,如果我添加另外平的选择,"ping source x.x.x.x host y.y.y.y -c 5 -s 500"我有

ping:未知主机源

回信。如果我从x终端手动执行两个命令,则两个命令都能正常工作。

我需要使程序从不同的源接口IP执行ping操作。使用JSch的两个命令有什么区别setCommand?

  1. ping y.y.y.y -c 5 -s 500 (加工)
  2. ping source x.x.x.x host y.y.y.y -c 5 -s 500 (不工作)

码:

public static void main(String[] arg){
try{
  JSch jsch=new JSch();  

  String host=null;
  if(arg.length>0){
    host=arg[0];
  }
  else{
    host=JOptionPane.showInputDialog("Enter username@hostname",
                                     System.getProperty("user.name")+
                                     "@localhost"); 
  }
  String user=host.substring(0, host.indexOf('@'));
  host=host.substring(host.indexOf('@')+1);

  Session session=jsch.getSession(user, host, 22);

  UserInfo ui=new MyUserInfo();
  session.setUserInfo(ui);
  session.connect();

  // this command works
  // String command = "ping 20.5.1.15 -c " + count + " -s " + size;

  // this command not working
  String command = "ping source 20.5.1.10 host 20.5.1.15 -c " + count + " -s
  " + size;

  Channel channel=session.openChannel("exec");
  ((ChannelExec)channel).setCommand(command);

  channel.setInputStream(null);

  ((ChannelExec)channel).setErrStream(System.err);

  InputStream in=channel.getInputStream();

  channel.connect();

  byte[] tmp=new byte[1024];
  while(true){
    while(in.available()>0){
      int i=in.read(tmp, 0, 1024);
      if(i<0)break;
      System.out.print(new String(tmp, 0, i));
    }
    if(channel.isClosed()){
      if(in.available()>0) continue; 
      System.out.println("exit-status: "+channel.getExitStatus());
      break;
    }
    try{Thread.sleep(1000);}catch(Exception ee){}
  }
  channel.disconnect();
  session.disconnect();
}
catch(Exception e){
  System.out.println(e);
}

阅读 588

收藏
2020-11-30

共1个答案

小编典典

您的ping source x.x.x.x host y.y.y.y语法对我来说似乎很奇怪。但我相信您,它可以在终端上正常工作。

该ping命令可能取决于某些环境变量或其他配置来解析源地址。

JSch中的“ exec”通道(正确地)没有为会话分配伪终端(PTY)。结果,(可能)获得了一组不同的启动脚本。基于TERM环境变量的存在/不存在,使用脚本中的和/或不同分支。因此,环境可能不同于您与SSH客户端一起使用的交互式会话。

如果这使ping命令中断,则很明显是服务器端配置错误,而不是JSch故障。该ping命令不是交互式命令,因此即使在非交互式会话上也应起作用。您应该找出破坏的原因,ping并相应地修复启动脚本。

要验证这是根本原因,请在SSH客户端中禁用伪终端分配。例如在PuTTY中,它是Connection> SSH> TTY>不要分配伪终端。然后转到“连接”>“ SSH”>“远程”命令并输入您的ping source …命令。检查会话>退出时关闭窗口>从不,然后打开会话。

另一种(不推荐)的方法是使用以下.setPty方法强制为“ exec”通道分配伪终端:

Channel channel=session.openChannel("exec");
((ChannelExec)channel).setPty(true);
2020-11-30