是否可以将 linux shell 内的命令输出发送到 JAVA 应用程序?如果可以的话怎么办?我看到有机会从 JAVA 执行 shell 命令,我希望得到相反的结果:SHELL COMMANDS OUTPUT --->to---> Java VARIABLE 或 STRING。谢谢回复
最佳答案
您可以使用 jcraft,然后执行返回输出的命令
示例
host = //your hostIP;
String user = "username";
String password = "pwd";
String command = "the command you want to execute";
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("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;
area.append(new String(tmp, 0, i));
//System.out.print(new String(tmp, 0, i)); //command output
}
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();
return false;
}
关于java - 如何从shell内的Linux命令获取字符串或值到JAVA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121150/