【发布时间】:2014-05-30 07:36:28
【问题描述】:
我正在使用 Jsch 库在几台 linux 机器上执行大约 1000 个不同的 shell 脚本并将状态更新到一个表中。
我使用了 jsch exec 通道 [ChannelExec],它仅适用于单个脚本,如果 shell 脚本调用另一个脚本,ChannelExec 不会给出正确的结果。
现在我正在使用 jsch 的 shell 通道。它可以很好地从任何类型的 shell 脚本中获取输出。
问题是,如果我一次执行多个 shell 脚本,我会得到一个批量的所有结果。
没有办法让一个 Shell 脚本执行并收到它的结果。
如果我想获得单个脚本的执行结果,我需要为每个脚本执行登录机器,这需要很长时间。
有人可以发布解决方案,建议如何进行,登录机器一次并执行多个脚本并单独接收每个脚本结果。
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
public class JschShellExample {
public static void main(String[] args) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession("user", "10.32.248.158", 22);
session.setPassword("password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications","publickey,keyboard-interactive,password");
session.setConfig(config);
session.connect(100);
Channel channel = session.openChannel("shell");
OutputStream inputstream_for_the_channel = channel.getOutputStream();
PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
channel.setOutputStream(null);
channel.connect(100);
//shell script
commander.println("cd /user/home/work ; ./checkstaus.sh ; exit");
commander.flush();
System.out.println(channel.getExitStatus());
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String line = null;
StringBuilder sb = new StringBuilder();
boolean isloginStringPassed = false ;
while ((line = br.readLine()) != null) {
sb.append(line.trim());
}
System.out.println("Result ="+sb.toString());
channel.disconnect();
session.disconnect();
System.out.println("completed .. ");
} catch (JSchException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
【问题讨论】:
标签: java shell unix expect jsch