Skip to content
Advertisement

Send Commands remotely from Windows to Linux through Java

I searched everywhere but can’t find a solution that works.

I have a Linux Debian machine in my network, which is running as a Mqtt Broker. I want to write a java programm to send sub and pub commands to the broker from another computer (Windows). Is there a way to send Linux commands from a Windows Computer?

If yes, is it possible to do it through java code and recieve the proper outputs?

I tried the following:

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);
        }
    }
}

The output is:

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

I feel like this might work, if the right commands would be added.

I have heard of libraries like “Eclipse Paho”, but I want to know if my solution can work.

Thanks in advance!

Advertisement

Answer

Your solution can work if you fallow this approach Run a command over SSH with JSch

but you mention MQTT. therefore you dont need to use ssh. you can connect to mqtt and make run commands with it. here is mqtt connection example https://www.hivemq.com/blog/how-to-get-started-with-mqtt

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement