Home > Java > javaTutorial > Detailed introduction to java connecting to the server through ssh to execute shell commands and sample code

Detailed introduction to java connecting to the server through ssh to execute shell commands and sample code

黄舟
Release: 2017-03-08 10:33:42
Original
1813 people have browsed it

This article mainly introduces the detailed explanation and example methods of java connecting to the server through ssh to execute shell commands.

java The detailed explanation of java connecting to the server through ssh to execute shell commands

java connects to the server through ssh to execute shell commands: JSch is a pure Java implementation of SSH2. It allows you to connect to an sshd server, use port forwarding, X11 forwarding, file transfers and more. You can integrate its functionality into your own programs. At the same time, the project also provides a J2ME version for direct connection to the SSHD server on the mobile phone.

SSH is the abbreviation of Secure Shell, a security protocol based on the application layer and transport layer. SSH encrypts all data during the connection and transmission process, and can be used to establish secure connections between different systems or servers. SSH provides two security authentication methods: 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 more troublesome and the connection is more time-consuming, so we will not introduce it in detail here.

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

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

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 {
  //远程主机的ip地址
  private String ip;
  //远程主机登录用户名
  private String username;
  //远程主机的登录密码
  private String password;
  //设置ssh连接的远程端口
  public static final int DEFAULT_SSH_PORT = 22; 
  //保存输出内容的容器
  private ArrayList<string> stdout;
 
  /**
   * 初始化登录信息
   * @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>();
  }
  /**
   * 执行shell命令
   * @param command
   * @return
   */
  public int execute(final String command) {
    int returnCode = 0;
    JSch jsch = new JSch();
    MyUserInfo userInfo = new MyUserInfo();
 
    try {
      //创建session并且打开连接,因为创建session之后要主动打开连接
      Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
      session.setPassword(password);
      session.setUserInfo(userInfo);
      session.connect();
 
      //打开通道,设置通道类型,和执行的命令
      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);
 
      //接收远程服务器执行命令的结果
      String line;
      while ((line = input.readLine()) != null) { 
        stdout.add(line); 
      } 
      input.close(); 
 
      // 得到returnCode
      if (channelExec.isClosed()) { 
        returnCode = channelExec.getExitStatus(); 
      } 
 
      // 关闭通道
      channelExec.disconnect();
      //关闭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); 
    } 
  } 
}
Copy after login

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&#39;
     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()"); 
  }
 
}
Copy after login


The above is the detailed content of Detailed introduction to java connecting to the server through ssh to execute shell commands and sample code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template