Reputation: 175
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
Reputation: 2116
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) {
}
}
On client side
Socket socket = new Socket("serverip",1234);
OutputStream os = socket.getOutputStream();
os.write("echo hello");
os.flush();
os.close();
socket.close();
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
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
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
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