`

<转>JSCH 如何实现在远程机器上执行linux命令

 
阅读更多
原链:http://blog.csdn.net/hongbinchen/article/details/6567395

jsch 是纯java实现ssh功能,
下面是如何实现在远程机器上执行linux命令
摘自hadoop开源包的源码:



/**

* Licensed to the Apache Software Foundation (ASF) under one

* or more contributor license agreements.  See the NOTICE file

* distributed with this work for additional information

* regarding copyright ownership.  The ASF licenses this file

* to you under the Apache License, Version 2.0 (the

* "License"); you may not use this file except in compliance

* with the License.  You may obtain a copy of the License at

*

*     http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/



package org.apache.hadoop.util;



import com.jcraft.jsch.*;

import org.apache.commons.logging.LogFactory;

import org.apache.commons.logging.Log;



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Properties;



/**

* Remote Execution of commands  on a remote machine.

*/



public class SSHRemoteExecution implements RemoteExecution {



  static final Log LOG = LogFactory.getLog(SSHRemoteExecution.class);

  static final int SSH_PORT = 22;

  static final String DEFAULT_IDENTITY="id_dsa";

  static final String DEFAULT_KNOWNHOSTS="known_hosts";

  static final String FS = System.getProperty("file.separator");

  static final String LS = System.getProperty("line.separator");

  private int exitCode;

  private StringBuffer output;

  private String commandString;



  final StringBuffer errorMessage = new StringBuffer();

  public SSHRemoteExecution() throws Exception {

  }



  protected String getHomeDir() {

    String currentUser=System.getProperty("user.name");

    String userHome=System.getProperty("user.home");



    return userHome.substring(0, userHome.indexOf(currentUser)-1);

  }



  /**

   * Execute command at remote host under given user

   * @param remoteHostName remote host name

   * @param user is the name of the user to be login under;

   *   current user will be used if this is set to <code>null</code>

   * @param command to be executed remotely

   * @param identityFile is the name of alternative identity file; default

   *   is ~user/.ssh/id_dsa

   * @param portNumber remote SSH daemon port number, default is 22

   * @throws Exception in case of errors

   */

  public void executeCommand (String remoteHostName, String user,

          String  command, String identityFile, int portNumber) throws Exception {

    commandString = command;

    String sessionUser = System.getProperty("user.name");

    String userHome=System.getProperty("user.home");

    if (user != null) {

      sessionUser = user;

      userHome = getHomeDir() + FS + user;

    }

    String dotSSHDir = userHome + FS + ".ssh";

    String sessionIdentity = dotSSHDir + FS + DEFAULT_IDENTITY;

    if (identityFile != null) {

      sessionIdentity = identityFile;

    }



    JSch jsch = new JSch();



    Session session = jsch.getSession(sessionUser, remoteHostName, portNumber);

    jsch.setKnownHosts(dotSSHDir + FS + DEFAULT_KNOWNHOSTS);

    jsch.addIdentity(sessionIdentity);



    Properties config = new Properties();

    config.put("StrictHostKeyChecking", "no");

    session.setConfig(config);



    session.connect(30000);   // making a connection with timeout.



    Channel channel=session.openChannel("exec");

    ((ChannelExec)channel).setCommand(command);

    channel.setInputStream(null);



    final BufferedReader errReader =

            new BufferedReader(

              new InputStreamReader(((ChannelExec)channel).getErrStream()));

    BufferedReader inReader =

            new BufferedReader(new InputStreamReader(channel.getInputStream()));



    channel.connect();

    Thread errorThread = new Thread() {

      @Override

      public void run() {

        try {

          String line = errReader.readLine();

          while((line != null) && !isInterrupted()) {

            errorMessage.append(line);

            errorMessage.append(LS);

            line = errReader.readLine();

          }

        } catch(IOException ioe) {

          LOG.warn("Error reading the error stream", ioe);

        }

      }

    };



    try {

      errorThread.start();

    } catch (IllegalStateException e) {

      LOG.debug(e);

    }

    try {

      parseExecResult(inReader);

      String line = inReader.readLine();

      while (line != null) {

        line = inReader.readLine();

      }



      if(channel.isClosed()) {

        exitCode = channel.getExitStatus();

        LOG.debug("exit-status: " + exitCode);

      }

      try {

        // make sure that the error thread exits

        errorThread.join();

      } catch (InterruptedException ie) {

        LOG.warn("Interrupted while reading the error stream", ie);

      }

    } catch (Exception ie) {

      throw new IOException(ie.toString());

    }

    finally {

      try {

        inReader.close();

      } catch (IOException ioe) {

        LOG.warn("Error while closing the input stream", ioe);

      }

      try {

        errReader.close();

      } catch (IOException ioe) {

        LOG.warn("Error while closing the error stream", ioe);

      }

      channel.disconnect();

      session.disconnect();

    }

  }



  /**

   * Execute command at remote host under given username

   * Default identity is ~/.ssh/id_dsa key will be used

   * Default known_hosts file is ~/.ssh/known_hosts will be used

   * @param remoteHostName remote host name

   * @param user is the name of the user to be login under;

   *   if equals to <code>null</code> then current user name will be used

   * @param command to be executed remotely

   */

  @Override

  public void executeCommand (String remoteHostName, String user,

          String  command) throws Exception {

    executeCommand(remoteHostName, user, command, null, SSH_PORT);

  }



  @Override

  public int getExitCode() {

    return exitCode;

  }



  protected void parseExecResult(BufferedReader lines) throws IOException {

    output = new StringBuffer();

    char[] buf = new char[512];

    int nRead;

    while ( (nRead = lines.read(buf, 0, buf.length)) > 0 ) {

      output.append(buf, 0, nRead);

    }

  }



  /** Get the output of the ssh command.*/

  @Override

  public String getOutput() {

    return (output == null) ? "" : output.toString();

  }



  /** Get the String representation of ssh command */

  @Override

  public String getCommandString() {

    return commandString;

  }

}

分享到:
评论

相关推荐

    Java中通过jsch来连接远程服务器执行linux命令

    本文将详细介绍如何使用JSCH库在Java中连接远程服务器并执行Linux命令。 首先,我们需要导入JSCH库。如果你使用的是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml &lt;dependency&gt; &lt;groupId&gt;com.jcraft&lt;/...

    Java实现Linux的远程拷贝

    一旦连接建立成功,我们可以使用`session`对象的`execCommand()`方法执行Linux命令,比如`cp`或`rsync`进行文件拷贝。例如: ```java Channel channel = session.openChannel("exec"); ((ChannelExec) channel)....

    通过SSHPASS执行命令及相关脚本

    标题中的“通过SSHPASS执行命令及相关脚本”是指在Linux环境下使用`sshpass`工具进行非交互式SSH登录并执行远程命令的技术。`sshpass`是一个命令行实用程序,它允许用户在不手动输入密码的情况下,通过SSH连接执行...

    通过跳板机远程访问

    例如,要在本地监听31521端口,并将其转发到跳板机上的172.18.129.13主机的1521端口,可以执行以下命令: ```bash ssh -L 31521:172.18.129.13:1521 bea@124.225.110.4 ``` 类似地,如果要访问跳板机后的其他服务...

    java远程调试操作步骤

    远程调试是指在一台机器上运行Java应用程序,并允许另一台机器上的IDE连接到该应用程序进行调试的过程。 ##### 3.1 配置应用程序 - **启动诊断工具**:在Linux服务器上,通过Xshell或其他SSH客户端,使用以下命令...

    ssh环境搭建需要的jar包2

    SSH(Secure Shell)是一种网络协议,用于在不安全的网络上提供安全的远程登录和其他服务。在Java开发中,SSH通常指的是Spring、Struts和Hibernate这三个开源框架的组合,它们一起构建了强大的企业级应用开发基础。...

    leetcode下载-java:Studychen编码生涯中的几个java项目

    实现Linux远程连接windows并执行一些命令 ExtendDatabase 提高效率工具工程,扩展 ASE 数据库的data空间和log空间(默认增加 40G data和 10G log)。 DBLogMonitor 监控远程机器的数据库log文件,当日志已满时清空 ...

    blog.zip_blog_blog ssh

    在IT行业中,SSH(Secure Shell)是一种网络协议,用于在不安全的网络上提供安全的远程登录和其他服务。SSH主要用于加密网络通信,确保数据传输过程中的安全性,防止中间人攻击和窃听。对于Java初级工程师而言,理解...

    gossh:gossh是由go语言开发的一种极为简洁的ssh工具。 它只有一个二进制程序,没有任何依赖关系,可以立即使用。 gossh用于管理linux(如unix)计算机

    gossh用于管理linux(如unix)计算机:包括命令和推和拉文件的远程执行,并支持独立和批处理模式。 2,高斯能做什么 高斯的三个核心功能: 连接到远程主机以执行命令。 将本地文件或文件夹推送到远程主机。 将...

    ssh-shell-服务

    例如,可以使用JSch库来在Java程序中集成SSH功能,执行远程命令、传输文件等。JSch是一个纯Java实现的SSH2库,能够连接到SSH服务器,执行shell命令,实现SFTP(SSH文件传输协议)。 综上所述,SSH Shell服务在远程...

Global site tag (gtag.js) - Google Analytics