【发布时间】:2016-01-16 22:27:56
【问题描述】:
我正在使用 JSch 执行通道登录到多个服务器并运行一些命令。然后我需要捕获输出并将其存储在一个名为log 的文件中。出于某种奇怪的原因,文件在执行后保持空白。
try (OutputStream log = new BufferedOutputStream(new FileOutputStream(outputFilePath))) {
ArrayList<String> lists = new ArrayList<String>();
lists.add("hostname");
lists.add("df -l");
String host ="localhost";
JSch jsch = new JSch();
try {
String user = "user";
String password = "pass";
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(getProperties());
session.setTimeout(20 * 1000);
System.out.println(session.getTimeout());
session.connect();
if (session.isConnected()) {
System.out.println(host + " Session Established ");
}
for (String elem : lists) {
Channel channel = session.openChannel("exec");
channel.setOutputStream(log);
((ChannelExec) channel).setCommand(elem);
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();
程序通过 IDE 控制台显示输出,但输出文件已创建但仍为空白。
然后我将system.setOut 设置为一个文件,这会阻止控制台显示更多数据,但output.txt 文件仍为空白。
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));
【问题讨论】:
-
为什么不使用日志库?这可能会更容易......
-
您有示例或链接可用作参考吗?
-
例如:stackoverflow.com/questions/15758685/… - 但如果你用谷歌搜索“java 日志到文件示例”,我相信你会找到很多示例。