【问题标题】:'Echo' linux command is not working through Java Code'Echo' linux 命令无法通过 Java 代码运行
【发布时间】:2016-08-17 00:28:48
【问题描述】:

我正在尝试执行一个简单的 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");
}

【问题讨论】:

  • 不工作是什么意思?你认为welcome.txt 最终会在哪里?您是否尝试过使用shell 频道?

标签: java linux jsch


【解决方案1】:
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 通道的标准输入上打开输入流,因此您可以省略该行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2015-07-12
    • 1970-01-01
    • 2020-02-26
    • 2018-11-18
    • 2014-03-12
    相关资源
    最近更新 更多