Java 远程执行 Linux 的命令

在 Java 中可以通过 SSH2 协议远程执行 Linux 系统的命令或 Shell 脚本。

1. 添加依赖

需添加 ganymed-ssh2-build210.jar 包,Maven 依赖如下:

<dependency>  
  <groupId>com.ganymed.ssh2</groupId>  
  <artifactId>ganymed-ssh2-build</artifactId>  
  <version>210</version>  
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
2. api 说明
  1. 首先构造一个连接器,传入一个需要登陆的ip地址;

    Connection conn = new Connection(hostname);

  2. 模拟登陆目的服务器,传入用户名和密码;

    boolean isAuthenticated = conn.authenticateWithPassword(username, password);它会返回一个布尔值,true 代表成功登陆目的服务器,否则登陆失败。

  3. 打开一个session,执行你需要的linux 脚本命令;

    Session session = conn.openSession();
    session.execCommand(“ifconfig”);

  4. 接收目标服务器上的控制台返回结果,读取br中的内容;

    InputStream stdout = new StreamGobbler(sess.getStdout());
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

  5. 得到脚本运行成功与否的标志 :0-成功 非0-失败

    System.out.println(“ExitCode: ” + sess.getExitStatus());

  6. 关闭session和connection

    sess.close();
    conn.close();

备注

1、通过第2步认证成功后,当前目录就位于/home/username/目录之下,你可以指定脚本文件所在的绝对路径,或者通过cd导航到脚本文件所在的目录,然后传递执行脚本所需要的参数,完成脚本调用执行。

2、执行脚本以后,可以获取脚本执行的结果文本,需要对这些文本进行正确编码后返回给客户端,避免乱码产生。

3、如果你需要执行多个linux控制台脚本,比如第一个脚本的返回结果是第二个脚本的入参,你必须打开多个Session,也就是多次调用
Session sess = conn.openSession();,使用完毕记得关闭就可以了。

3. 实例代码
/**
 * @ClassName: RemoteExecuteCommand
 * @Description: 远程执行Linux命令
 * @date: 2017年10月9日 下午5:44:42
 */
public class RemoteExecuteCommand {
  // 字符编码默认是utf-8
  private static String DEFAULTCHART = "UTF-8";
  private Connection conn;
  private String ip;
  private String userName;
  private String userPwd;

  public RemoteExecuteCommand(String ip, String userName, String userPwd) {
    this.ip = ip;
    this.userName = userName;
    this.userPwd = userPwd;
  }


  public RemoteExecuteCommand() {

  }

  /**
   * 远程登录linux主机
   * @since V0.1
   * @return 登录成功返回true,否则返回false
   * @throws Exception
   */
  public Boolean login() throws Exception {
    boolean flg = false;
    try {
      conn = new Connection(ip);
      // 连接
      conn.connect();
      // 认证
      flg = conn.authenticateWithPassword(userName, userPwd);
    } catch (IOException e) {
      throw new Exception("远程连接服务器失败", e);
    }
    return flg;
  }

  /**
   * 远程执行shll脚本或者命令
   * @param cmd 即将执行的命令
   * @return 命令执行完后返回的结果值
   * @throws Exception
   * @since V0.1
   */
  public String execute(String cmd) throws Exception {
    String result = "";
    Session session = null;
    try {
      if (login()) {
        // 打开一个会话
        session = conn.openSession();
        // 执行命令
        session.execCommand(cmd);
        result = processStdout(session.getStdout(), DEFAULTCHART);
        // 如果为输出为空,说明脚本执行出错了
        if (StringUtils.isBlank(result)) {
          result = processStdout(session.getStderr(), DEFAULTCHART);
        }
        conn.close();
        session.close();
      }
    } catch (IOException e) {
      throw new Exception("命令执行失败", e);
    } finally {
      if (conn != null) {
        conn.close();
      }
      if (session != null) {
        session.close();
      }
    }
    return result;
  }

  /**
   * 解析脚本执行返回的结果集
   *
   * @param in 输入流对象
   * @param charset 编码
   * @since V0.1
   * @return 以纯文本的格式返回
   * @throws Exception
   */
  private String processStdout(InputStream in, String charset) throws Exception {
    InputStream stdout = new StreamGobbler(in);
    StringBuffer buffer = new StringBuffer();
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
      isr = new InputStreamReader(stdout, charset);
      br = new BufferedReader(isr);
      String line = null;
      while ((line = br.readLine()) != null) {
        buffer.append(line + "\n");
      }
    } catch (UnsupportedEncodingException e) {
      throw new Exception("不支持的编码字符集异常", e);
    } catch (IOException e) {
      throw new Exception("读取指纹失败", e);
    } finally {
      IOUtils.close(br);
      IOUtils.close(isr);
      IOUtils.close(stdout);
    }
    return buffer.toString();
  }

测试

public static void main(String[] args) { 
  String linuxIP = "192.168.X.XXX";
  String usrName = "root";
  String passwd  = "******";
  RemoteExecuteCommand rec = new RemoteExecuteCommand(linuxIP, usrName, passwd);  
  // 执行命令  
  System.out.println(rec.execute("ifconfig"));  
  // 执行脚本  
  rec.execute("sh /usr/local/tomcat/bin/statup.sh");   
} 




参考:
java远程调用linux的命令或者脚本

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值