Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute Linux commands on a remote machine using Java?

Tags:

java

linux

ssh

I have two secured linux servers. In one machine my Java application is running. I need to run Linux commands on second machine from first machine in Java. How might I do this?

like image 331
VamsiKrishna Avatar asked Oct 31 '11 04:10

VamsiKrishna


People also ask

Can we run Linux command in Java?

You can use java. lang. Runtime. exec to run simple code.

How do I run a Linux command remotely?

Syntax for running commands on a remote Linux or Unix host ssh : The ssh (or other SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. USER-NAME : Remote host user name. REMOTE-HOST : Remote host ip-address or host name, such as fbsd.cyberciti.biz.

Does Java do SSH?

SSH, also known as Secure Shell or Secure Socket Shell, is a network protocol that allows one computer to securely connect to another computer over an unsecured network. In this tutorial, we'll show how to establish a connection to a remote SSH server with Java using the JSch and Apache MINA SSHD libraries.


2 Answers

Jsch (here) allows you to connect to a remote server using SSH and executes shell commands easily (and lot of other things like SCP, SFTP...). There is not a lot of documentation, but you have a few really helpful implementation examples here (and even an example of what you want to do here).

You can also combine Jsch with Expect4j and this way have a better control on the commands you want to execute (nice example here).

like image 184
talnicolas Avatar answered Sep 23 '22 01:09

talnicolas


Essentially, you need to open an ssh connection to the other server from within your Java application. The OpenSSH site has some useful information on libraries that will give you ssh support in Java.

It looks like Ganymed SSH-2 for Java is the nicest of the pick there, but I haven't used any of them so you will need to look at what you need.

Once you have an ssh connection, you will be able to run commands just as if you logged in using any other ssh client.

like image 30
Cogito Avatar answered Sep 22 '22 01:09

Cogito