Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a command over SSH with JSch

Tags:

java

ssh

jsch

I'm trying to run a command over SSH with JSch, but JSch has virtually no documentation and the examples I've found are terrible. For example, this one doesn't show code for handling the output stream. And, this one uses an ugly hack to know when to stop reading from the output stream.

like image 799
jshen Avatar asked Mar 09 '10 00:03

jshen


People also ask

What is the use of JSch?

JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.

What is JSch SFTP?

2.1 In JSch , we can use put and get to do file transfer between servers. We use put to transfer files from a local system to the remote server. channelSftp. put(localFile, remoteFile); We use get to download files from a remote server to the local system.

What is JSch session?

A Session represents a connection to a SSH server. One session can contain multiple Channel s of various types, created with openChannel(java. lang. String) . A session is opened with connect() and closed with disconnect() .


1 Answers

The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.

  /*    * SSHManager   *    * @author cabbott   * @version 1.0   */   package cabbott.net;    import com.jcraft.jsch.*;   import java.io.IOException;   import java.io.InputStream;   import java.util.logging.Level;   import java.util.logging.Logger;    public class SSHManager   {   private static final Logger LOGGER =        Logger.getLogger(SSHManager.class.getName());   private JSch jschSSHChannel;   private String strUserName;   private String strConnectionIP;   private int intConnectionPort;   private String strPassword;   private Session sesConnection;   private int intTimeOut;    private void doCommonConstructorActions(String userName,         String password, String connectionIP, String knownHostsFileName)   {      jschSSHChannel = new JSch();       try      {         jschSSHChannel.setKnownHosts(knownHostsFileName);      }      catch(JSchException jschX)      {         logError(jschX.getMessage());      }       strUserName = userName;      strPassword = password;      strConnectionIP = connectionIP;   }    public SSHManager(String userName, String password,       String connectionIP, String knownHostsFileName)   {      doCommonConstructorActions(userName, password,                  connectionIP, knownHostsFileName);      intConnectionPort = 22;      intTimeOut = 60000;   }    public SSHManager(String userName, String password, String connectionIP,       String knownHostsFileName, int connectionPort)   {      doCommonConstructorActions(userName, password, connectionIP,          knownHostsFileName);      intConnectionPort = connectionPort;      intTimeOut = 60000;   }    public SSHManager(String userName, String password, String connectionIP,        String knownHostsFileName, int connectionPort, int timeOutMilliseconds)   {      doCommonConstructorActions(userName, password, connectionIP,           knownHostsFileName);      intConnectionPort = connectionPort;      intTimeOut = timeOutMilliseconds;   }    public String connect()   {      String errorMessage = null;       try      {         sesConnection = jschSSHChannel.getSession(strUserName,              strConnectionIP, intConnectionPort);         sesConnection.setPassword(strPassword);         // UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION         // sesConnection.setConfig("StrictHostKeyChecking", "no");         sesConnection.connect(intTimeOut);      }      catch(JSchException jschX)      {         errorMessage = jschX.getMessage();      }       return errorMessage;   }    private String logError(String errorMessage)   {      if(errorMessage != null)      {         LOGGER.log(Level.SEVERE, "{0}:{1} - {2}",              new Object[]{strConnectionIP, intConnectionPort, errorMessage});      }       return errorMessage;   }    private String logWarning(String warnMessage)   {      if(warnMessage != null)      {         LOGGER.log(Level.WARNING, "{0}:{1} - {2}",             new Object[]{strConnectionIP, intConnectionPort, warnMessage});      }       return warnMessage;   }    public String sendCommand(String command)   {      StringBuilder outputBuffer = new StringBuilder();       try      {         Channel channel = sesConnection.openChannel("exec");         ((ChannelExec)channel).setCommand(command);         InputStream commandOutput = channel.getInputStream();         channel.connect();         int readByte = commandOutput.read();          while(readByte != 0xffffffff)         {            outputBuffer.append((char)readByte);            readByte = commandOutput.read();         }          channel.disconnect();      }      catch(IOException ioX)      {         logWarning(ioX.getMessage());         return null;      }      catch(JSchException jschX)      {         logWarning(jschX.getMessage());         return null;      }       return outputBuffer.toString();   }    public void close()   {      sesConnection.disconnect();   }    } 

For testing.

  /**      * Test of sendCommand method, of class SSHManager.      */   @Test   public void testSendCommand()   {      System.out.println("sendCommand");       /**       * YOU MUST CHANGE THE FOLLOWING       * FILE_NAME: A FILE IN THE DIRECTORY       * USER: LOGIN USER NAME       * PASSWORD: PASSWORD FOR THAT USER       * HOST: IP ADDRESS OF THE SSH SERVER      **/      String command = "ls FILE_NAME";      String userName = "USER";      String password = "PASSWORD";      String connectionIP = "HOST";      SSHManager instance = new SSHManager(userName, password, connectionIP, "");      String errorMessage = instance.connect();       if(errorMessage != null)      {         System.out.println(errorMessage);         fail();      }       String expResult = "FILE_NAME\n";      // call sendCommand for each command and the output       //(without prompts) is returned      String result = instance.sendCommand(command);      // close only after all commands are sent      instance.close();      assertEquals(expResult, result);   } 
like image 194
Charity Leschinski Avatar answered Sep 23 '22 04:09

Charity Leschinski