JAVA通过ssh2远程执行linux命令

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Run {
    public static void main(String[] args) {
      
            String hostname ="host"; 
            String username="username"; 
            String password="password"; 
           try{ 
               //建立连接 
               Connection conn= new Connection(hostname); 
               conn.connect(null, 0, 10000) ;
               //利用用户名和密码进行授权 
               boolean isAuthenticated = conn.authenticateWithPassword(username, password); 
               if(isAuthenticated ==false){ 
                   throw new IOException("Authorication failed"); 
               } 
               //打开会话 
               Session sess = conn.openSession(); 
              //执行命令

              sess.execCommand("sh /test.sh");
              InputStream stdout = new StreamGobbler(sess.getStdout()); 
               BufferedReader br = new BufferedReader(new InputStreamReader(stdout,"GBK")); 
               while(true){ 
                   String line = br.readLine(); 
                   if(line==null) break; 
                   输出返回值            

                   System.out.println(line); 
               } 
               System.out.println(sess.getExitStatus()+" "+(sess.getExitStatus()==null)); 
               sess.close(); 
               conn.close(); 
           }catch(IOException e){ 
               e.printStackTrace();
           } 
           System.exit(0);
       } 
    }
test.sh文件内容如下

#!/bin/sh
a="hello world"
echo $a

执行结果

hello world
0 false

正确执行,sess.getExitStatus()返回0.

猜你喜欢

转载自girl-luo.iteye.com/blog/2343549