我正在寻找一个解决方案,以解决需要按顺序依次执行的一组命令。同样,一个命令应该只在前一个命令完成其执行之后执行。
String command="cd /home/; ls-ltr;"
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 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()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
System.out.println("DONE");我尝试对每个命令使用";“执行命令,但所有命令都是在一次尝试中执行的。所以,它不起作用。在同一shell / exec中运行每个命令的可能方法是什么?
发布于 2015-12-18 02:02:27
我将实现从"exec“更改为"shell”,并在每个命令之间使用"&&“更新命令。现在,下面的命令只有在前一个命令执行完毕后才会执行。也就是说,"&&“的工作方式是,基于前一个命令的成功状态,即通过检查退出状态,它应该是"0”,否则下一个命令将不会被执行。
更新代码:
try{
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 channel=session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println(command1 + "&&" + command2 + "&&" + command3 +"&&" +command4);
InputStream in=channel.getInputStream();
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()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}发布于 2018-11-09 17:53:48
您可以使用一个接一个的命令,方法是在命令后面加上&&。例如,
jschUtil.openChannel("exec");
jschUtil.getExecSshChannel().setCommand("cd /root/Test1/Test2 && mkdir Neel");在这里,Directory Neel将在Test2中创建。如果您创建两个单独的通道或一个接一个地使用命令,这是永远不可能的。
https://stackoverflow.com/questions/34298239
复制相似问题