有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我到处搜索,但找不到有效的解决方案。

我的网络中有一台Linux Debian机器,它作为Mqtt代理运行。我想编写一个java程序,从另一台计算机(Windows)向代理发送sub和pub命令。有没有办法从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);
        }
    }
}

输出为:

Pseudo-terminal will not be allocated because stdin is not a terminal.

如果添加正确的命令,我觉得这可能会起作用。

我听说过像“EclipsePAHO”这样的库,但我想知道我的解决方案是否可行。

提前谢谢


共 (2) 个答案

  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.