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?
You can use java. lang. Runtime. exec to run simple code.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With