首页 > 开发 > Java > 正文

java通过ssh连接服务器执行shell命令详解及实例

2020-07-28 14:13:09
字体:
来源:转载
供稿:网友

java通过ssh连接服务器执行shell命令详解

java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。

SSH是Secure Shell的缩写,一种建立在应用层和传输层基础上的安全协议。SSH在连接和传送过程中会加密所有数据,可以用来在不同系统或者服务器之间进行安全连接。SSH提供两种的安全验证方式:基于密码的认证和基于密匙的认证。其中,基于密码的认证比较简单,只要知道远程主机的用户名和密码,就可以进行登录。基于密匙的认证比较麻烦,而且连接比较耗时,这里不详细介绍。

有很多基于SSH协议的客户端,例如:PuTTY、OpenSSH、Xshell 4等,可以远程连接几乎所有UNIX平台。同时,可以通过Linux命令行ssh uername@host连接到某主机。

在项目中,如何利用代码实现SSH,远程执行Shell脚本呢?JSch是Java Secure Channel的缩写,是一个SSH2功能的纯Java实现,具体信息可以参考JSch官网。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,同时你也可以集成它的功能到你自己的应用程序。在使用前,需要下载并导入JSch包:jsch-0.1.50.jar。

示例程序

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);     }   } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表