---
title: "ssh 远程执行异常"
author: "chenchangqun"
date: "2016-11-15T12:00:21Z"
tags: []
categories: ["开源软件"]
slug: "ssh"
draft: false
lastmod: "2016-11-15T11:56:40Z"
id: 2338013
url: "https://chenchangqun.iteye.com/blog/2338013"
---

因为项目要求，需要远程执行命令，maven配置和代码如下


```java

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build209</version>
</dependency>

```


```java


public class InvokeShellTest {
     public static void main(String[] args) {  

            String hostname = "10.103.16.16";  
            String username = "sa";  
            String password = "123456";  
            //指明连接主机的IP地址  
            Connection conn = new Connection(hostname,9880);  
            Session ssh = null;  
            try {  
                //连接到主机  
                conn.connect();  
                //使用用户名和密码校验  
                boolean isconn = conn.authenticateWithPassword(username, password);  
                if(!isconn){  
                    System.out.println("用户名称或者是密码不正确");  
                }else{  
                    System.out.println("已经连接OK");  
                    ssh = conn.openSession();  
                    //使用多个命令用分号隔开  
//                    ssh.execCommand("ps -ef|grep java");  
                      ssh.execCommand("sh /opt/ali-rocketmq/devenv/bin/mqadmin consumerProgress -n \"10.103.16.77:9876;10.103.16.15:9876\"");  
  
                    //只允许使用一行命令，即ssh对象只能使用一次execCommand这个方法，多次使用则会出现异常  
 
                    //将屏幕上的文字全部打印出来  
                    InputStream  is = new StreamGobbler(ssh.getStdout());  
                    BufferedReader brs = new BufferedReader(new InputStreamReader(is));  
                    while(true){  
                        String line = brs.readLine();  
                        if(line==null){  
                            break;  
                        }  
                        System.out.println(line);  
                    }  

                }  
                //连接的Session和Connection对象都需要关闭  
                ssh.close();  
                conn.close();  

            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  

        }  


}

```

报错
ERROR: Please set the JAVA_HOME variable in your environment, We need java(x64)! !!
 
在mqadmin脚本中加入  export JAVA_HOME=/usr/local/java 解决，正常输出结果