通过Java从Windows到Linux远程发送命令

时间:2018-07-26 06:47:18

标签: java linux windows mqtt

我到处搜索,但找不到可行的解决方案。

我的网络中有一台Linux Debian计算机,它以Mqtt Broker的身份运行。我想编写一个Java程序,以从另一台计算机(Windows)向代理发送子命令和发布命令。有没有办法从Windows计算机发送Linux命令?

如果可以,是否可以通过Java代码来完成并接收正确的输出?

我尝试了以下操作:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class AA
{
    public static void main(String[] args) throws Exception
    {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c",
                "ssh 10.20.0.30 -l username"); // Ip of the Mqtt Broker
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
        String line;
        while (true)
        {
            line = r.readLine();
            if (line == null)
            {
                break;
            }
            System.out.println(line);
        }
    }
}

输出为:

  

由于stdin不是终端,因此不会分配伪终端。

如果可以添加正确的命令,我觉得这可能可行。

我听说过诸如“ Eclipse Paho”之类的库,但是我想知道我的解决方案是否可以工作。

提前谢谢!

2 个答案:

答案 0 :(得分:0)

如果您放弃这种方法Run a command over SSH with JSch

,您的解决方案就可以工作

但是您提到MQTT。因此,您不需要使用ssh。您可以连接到mqtt并使用它执行运行命令。这是mqtt连接示例https://www.hivemq.com/blog/how-to-get-started-with-mqtt

答案 1 :(得分:-1)

尝试在您的代码中使用ssh -tt,这可能对您有用。

From ssh manpage:

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary 
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty
        allocation, even if ssh has no local tty.