I'm trying to set up a class so that I can ssh into a remote server (I have the IP, username, and password) and then send a command like "echo "test"" and then receive back the output (e.g., "test"). I'm using JSch to do this but I don't understand how to do it.
import com.jcraft.jsch.*;
public class ConnectSSH {
public int execute (String command) {
JSch jsch = new JSch();
String ip = "00.00.00.00;
String user = "root";
String pass = "password";
int port = 22;
try {
Session session = jsch.getSession(user, ip, port);
session.setPassword(pass);
session.connect();
...
I'm not sure what to do, I'm stuck after connecting.
Any advice is greatly appreciated.
Try this:
shamnu's answer above was right. I couldn't add a comment to it, so here are a few examples to enhance his answer. One is how to do a remote execution of 'ls -l', another of 'mkdir', and another of a local to remote copy. All done with version 0.1.51 of jsch (http://www.jcraft.com/jsch/).
I suggest looking at the hidden example on the JCraft website: http://www.jcraft.com/jsch/examples/UserAuthKI.java
Their example prompts for username, hostname, password, so it is ready to test out of the box. I ran it on my network and was able to connect to an AIX server without changing any code.
Note, their example has a problem (this may be why it is hidden).. it does not ever close the channel. If you send 'exit' the server will disconnect you, but the channel object stays open and your Java program never exits. I have provided a fix for that here: Never ending of reading server response using jSch