我正在尝试执行一个简单的linux命令,通过我的java代码将一些文本附加到远程服务器中的文件中。但它不起作用。当我在linux框中运行相同的命令时,它可以正常工作。
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session sessionwrite = jsch.getSession(user2, host2, 22);
sessionwrite.setPassword(password2);
sessionwrite.setConfig(config);
sessionwrite.connect();
System.out.println("Connected");
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
System.out.println("done");
}
答案 0 :(得分:0)
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
System.out.println("done");
您错过了对channel.connect()
的通话。 connect()
是实际将请求发送到远程服务器以调用命令的方法。完成通道后,您还应该调用channel.disconnect()
来终止它。您的代码可能如下所示:
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
channel.connect();
channel.disconnect();
System.out.println("done");
我要补充一点,在这个特定的例子中,没有理由在exec频道的标准输入上打开输入流,所以你可以把它留下来。