Nidis
Nidis

Reputation: 175

Run a script from another machine using Java

I have 3 computers in the same network. I want to write a java program in order to run some scripts on the other machines. My machine runs Windows and the others run Linux and Windows respectively.

Any ideas about it? I show some solutions about remote machines but I hope that there will be an easier way because my pc are in the same network.

Upvotes: 1

Views: 3706

Answers (5)

Sid Malani
Sid Malani

Reputation: 2116

  1. Create a serverSocket or RMI / XMLRPC server on each of the machines.

    ServerSocket serverSocket = new ServerSocket(1234);

    while (true) {

    try {
        Socket socket = serverSocket.accept();
        BufferedReader reader = new BufferedReader(socket.getInputStream());
        // exec a command sent by the client
        Runtime.getRuntime().exec(reader.readLine());
        // or 
        // a static command
    } catch (Exception ex) {
    }
    

    }

  2. On client side

    Socket socket = new Socket("serverip",1234);

    OutputStream os = socket.getOutputStream();

    os.write("echo hello");

    os.flush();

    os.close();

    socket.close();

  3. Where you have linux machines you could do

    try {

    Socket socket = new Socket("serverip",21); // connect to telnet port
    
    OutputStream os = socket.getOutputStream();
    
    // wait for server prompt
    
    Thread.sleep(1000);
    
    os.write("username\n");
    
    // wait for server prompt
    
    Thread.sleep(1000);
    
    os.write("password\n");
    
    Thread.sleep(1000);
    
    os.write("~/xyz/run.sh");
    
    os.close();
    
    socket.close();
    
    } catch(Exception ex) {
    

    }

Upvotes: 1

Wintermute
Wintermute

Reputation: 1511

Don't use Java for this task, if somehow possible. Use a remote management system, like OpenRSM (http://openrsm.sourceforge.net/).

Upvotes: 0

AlexR
AlexR

Reputation: 115378

In addition to @corsair's reply: you can use SSH for Linux, Telnet for both Linux and windows. There are several pure java libraries that implement SSH and Telnet. Take a look on http://www.jcraft.com/jsch/ and http://commons.apache.org/net/

Upvotes: 1

SJuan76
SJuan76

Reputation: 24895

Java is not the best tool for this. Yet, if you want to do with Java, you need to setup a server in each of the remote machines. A server is basically a process that always is running and listens to a port; from that port it will receive the message to run the scripts.

If the scripts are safe (if they run at the wrong time no harm is done), you can do it just with ServerSocket. If they are unsafe (you need to make sure that only you are the one able to launch the process, I would advise using a web server (Jetty, Tomcat) to use its security capabilities (SSL/HTTPS, authentication).

Upvotes: 0

corsair
corsair

Reputation: 668

For linux you can use ssh to execute remote command

Upvotes: 2

Related Questions