java connects to the server via ssh to execute shell command details and examples

  • 2020-06-03 06:40:19
  • OfStack

java connects to the server via ssh to execute shell command detail

java connects to the server via ssh to execute the shell command: JSch is a pure Java implementation of SSH2. It allows you to connect to an sshd server, port forward, X11 forward, file transfer, etc. You can integrate its functions into your own programs. The project also provides a version of J2ME for direct access to SSHD servers on mobile phones.

SSH is short for Secure Shell, a security protocol based on the application and transport layers. SSH encrypts all data during connection and transfer and can be used for secure connections between different systems or servers. SSH offers two types of security authentication: password-based authentication and key-based authentication. Among them, password based authentication is relatively simple, as long as you know the user name and password of the remote host, you can log in. Key-based authentication is cumbersome and time-consuming to connect, which I won't cover here.

There are many CLIENTS based on SSH protocol, such as PuTTY, OpenSSH, Xshell 4, which can connect to almost all UNIX platforms remotely. At the same time, you can connect to a host via the Linux uername@host command line.

In your project, how do you implement SSH with code and execute Shell scripts remotely? JSch is the abbreviation of Java Secure Channel. It is a pure Java implementation of SSH2 function. For details, please refer to JSch official website. It allows you to connect to an SSH server and can use port forwarding, X11 forwarding, file transfer, etc., while you can also integrate its functionality into your own applications. Before using, you need to download and import the JSch package: ES50en-0.1.50.jar.

The sample program


package com.stormma.demo;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
 
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
 
public class Shell {
  // Remote host ip address 
  private String ip;
  // Remote host login user name 
  private String username;
  // Login password for remote host 
  private String password;
  // Set up the ssh The remote port to connect to 
  public static final int DEFAULT_SSH_PORT = 22; 
  // A container that holds the output 
  private ArrayList<string> stdout;
 
  /**
   *  Initialize login information 
   * @param ip
   * @param username
   * @param password
   */
  public Shell(final String ip, final String username, final String password) {
     this.ip = ip;
     this.username = username;
     this.password = password;
     stdout = new ArrayList<string>();
  }
  /**
   *  perform shell The command 
   * @param command
   * @return
   */
  public int execute(final String command) {
    int returnCode = 0;
    JSch jsch = new JSch();
    MyUserInfo userInfo = new MyUserInfo();
 
    try {
      // create session And open the connection because it's created session Then open the connection actively 
      Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
      session.setPassword(password);
      session.setUserInfo(userInfo);
      session.connect();
 
      // Open the channel, set the channel type, and the command to execute 
      Channel channel = session.openChannel("exec");
      ChannelExec channelExec = (ChannelExec)channel;
      channelExec.setCommand(command);
 
      channelExec.setInputStream(null);
      BufferedReader input = new BufferedReader(new InputStreamReader
          (channelExec.getInputStream()));
 
      channelExec.connect();
      System.out.println("The remote command is :" + command);
 
      // Receives the result of a command executed by the remote server 
      String line;
      while ((line = input.readLine()) != null) { 
        stdout.add(line); 
      } 
      input.close(); 
 
      //  get returnCode
      if (channelExec.isClosed()) { 
        returnCode = channelExec.getExitStatus(); 
      } 
 
      //  Close the channel 
      channelExec.disconnect();
      // Shut down session
      session.disconnect();
 
    } catch (JSchException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return returnCode;
  }
  /**
   * get stdout
   * @return
   */
  public ArrayList<string> getStandardOutput() {
    return stdout;
  }
 
  public static void main(final String [] args) { 
    Shell shell = new Shell("xxx.xxx.xxx.xxx", "username", "password");
    shell.execute("uname -s -r -v");
 
    ArrayList<string> stdout = shell.getStandardOutput();
    for (String str : stdout) { 
      System.out.println(str); 
    } 
  } 
}

MyUserInfo


package com.stormma.demo;
 
import com.jcraft.jsch.UserInfo;
 
public class MyUserInfo implements UserInfo {
 
  @Override
  public String getPassphrase() {
    // TODO Auto-generated method stub
    System.out.println("MyUserInfo.getPassphrase()");
    return null;
  }
 
  @Override
  public String getPassword() {
    // TODO Auto-generated method stub
    System.out.println("MyUserInfo.getPassword()");
    return null;
  }
 
  @Override
  public boolean promptPassphrase(String arg0) {
    // TODO Auto-generated method stub
    System.out.println("MyUserInfo.promptPassphrase()");
    System.out.println(arg0);
    return false;
  }
 
  @Override
  public boolean promptPassword(String arg0) {
    // TODO Auto-generated method stub
    System.out.println("MyUserInfo.promptPassword()"); 
    System.out.println(arg0);
    return false;
  }
 
  @Override
  public boolean promptYesNo(String arg0) {
    // TODO Auto-generated method stub'
     System.out.println("MyUserInfo.promptYesNo()"); 
     System.out.println(arg0); 
     if (arg0.contains("The authenticity of host")) { 
       return true; 
     } 
    return true;
  }
 
  @Override
  public void showMessage(String arg0) {
    // TODO Auto-generated method stub
    System.out.println("MyUserInfo.showMessage()"); 
  }
 
}

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: