java通过ssh2远程连接计算机并执行linux命令的方法(转)

java通过ch.ethz.ssh2远程连接计算机并执行linux命令的方法实现

API详情:  http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.html

jar包:  ganymed-ssh2-build210.jar    下载地址: http://www.ganymed.ethz.ch/ssh2/

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
 
import java.io.IOException;
 
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
 
/*
  @author: Liu Yuanyuan
  purpose: test connecting remote computer and execute linux command
*/
 
public class TestRemoteConnect {
 
    public static void main(String[] args) {
 
        String hostname = "192.168.100.50";
        String username = "root";
        String password = "highgo";
        //指明连接主机的IP地址  
        Connection conn = new Connection(hostname);
        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("sh /root/hello.sh");
                //ssh.execCommand("perl /root/hello.pl");  
                //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,
                //多次使用则会出现异常       
                //使用多个命令用分号隔开  
                //ssh.execCommand("cd /root; sh hello.sh"); 
                 
                //将Terminal屏幕上的文字全部打印出来                  
                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);
                }
            }            
 
        catch (IOException e) 
        {
            e.printStackTrace();
        finally 
        {
            //连接的Session和Connection对象都需要关闭  
            ssh.close();
            conn.close();
        }
 
    }
 
}

 

posted @ 2015-10-28 18:22  snackguo  阅读(5103)  评论(0编辑  收藏  举报