使用Java JSch在防火墙设备上通过SSH执行多个命令

时间:2019-06-07 11:58:33

标签: java ssh jsch

我提到了问题Multiple bash commands,并按如下所示实施。我连接到第一个命令应该为configure的设备,然后只有我会提示执行所有其他命令。我没有得到任何命令的输出,并且控件没有返回。

以下是在终端中运行的命令。

ssh uname@ip
configure # this command changes prompt and enable follwoing commands
move shared pre-rulebase security rules TEST top 
commit
exit
exit

脚本

String[] commands = new String[]{
    "configure", "move shared pre-rulebase security rules TEST top", "commit", "exit"};

FileWriter fileOut = new FileWriter(outFileName, true);
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");

System.out.println(commands[0]);
ChannelExec channel = (ChannelExec) session.openChannel("exec");
((ChannelExec) channel).setCommand(commands[0]);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);

InputStream in = channel.getInputStream();
outStream = channel.getOutputStream();
channel.connect();

Thread.sleep(1000);

for(int i=1;i<commands.length;i++) {
    System.out.println("Executing:"+commands[i]);
    outStream.write((commands[i]+"\n").getBytes());
    outStream.flush();
}

byte[] tmp = new byte[1024];
while (true) {
    while (in.available() > 0) {
        int i = in.read(tmp, 0, 1024);
        if (i < 0)
            break;
        resultString = new String(tmp, 0, i);                   
        fileOut.write(resultString);
    }
    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();
outStream.close();
fileOut.close();

1 个答案:

答案 0 :(得分:0)

您设备上的“ exec”通道似乎未正确实现。因此,您不能在“ exec”通道中使用代码。

您可以“ ssh”到设备,“ shell”通道似乎可以正常工作。

默认情况下,JSch为“外壳”通道启用终端仿真,这将带来很多不必要的副作用(请参见Getting unwanted characters when reading command output from SSH server using JSch)。通过调用setPty禁用该功能。

ChannelShell channel = (ChannelShell) session.openChannel("shell"); 

InputStream in = channel.getInputStream(); 
outStream = channel.getOutputStream(); 

channel.setPty(false);
channel.connect(); 

outStream.write('configure\n'.getBytes());  
outStream.write('move shared pre-rulebase security rules TEST top\n'.getBytes());