Java远程调用Linux脚本

参考:http://blog.csdn.net/xiao_jun_0820/article/details/26254813

   http://blog.csdn.net/a19881029/article/details/20000775

API:http://www.boyunjian.com/javadoc/org.jvnet.hudson/ganymed-ssh2/build210-hudson-1/_/ch/ethz/ssh2/Session.html#execCommand(java.lang.String)

 1 package shell;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.nio.charset.Charset;
 6 
 7 import ch.ethz.ssh2.Connection;
 8 import ch.ethz.ssh2.Session;
 9 
10 public class RemoteShellTool {
11 
12     private Connection conn;
13     private String ipAddr;
14     private String charset = Charset.defaultCharset().toString();
15     private String userName;
16     private String password;
17 
18     public RemoteShellTool(String ipAddr, String userName, String password, String charset) {
19         this.ipAddr = ipAddr;
20         this.userName = userName;
21         this.password = password;
22         if (charset != null) {
23             this.charset = charset;
24         }
25     }
26 
27     public boolean login() throws IOException {
28         conn = new Connection(ipAddr);
29         conn.connect(); // 连接
30         return conn.authenticateWithPassword(userName, password); // 认证
31     }
32 
33     public String exec(String cmds) {
34         InputStream in = null;
35         String result = "";
36         try {
37             if (this.login()) {
38                 Session session = conn.openSession(); // 打开一个会话
39                 session.execCommand(cmds);
40 
41                 in = session.getStdout();
42                 result = this.processStdout(in, this.charset);
43                 session.close();
44                 conn.close();
45             }
46         } catch (IOException e1) {
47             e1.printStackTrace();
48         }
49         return result;
50     }
51 
52     public String processStdout(InputStream in, String charset) {
53 
54         byte[] buf = new byte[1024];
55         StringBuffer sb = new StringBuffer();
56         try {
57             while (in.read(buf) != -1) {
58                 sb.append(new String(buf, charset));
59             }
60         } catch (IOException e) {
61             e.printStackTrace();
62         }
63         return sb.toString();
64     }
65 
66     /**
67      * @param args
68      */
69     public static void main(String[] args) {
70 
71         RemoteShellTool tool = new RemoteShellTool("192.168.134.128", "root", "root", "utf-8");
72 
73 //        String result = tool.exec("./test.sh xiaojun");
74         String result = tool.exec("cd /home;./t.sh");
75         System.out.println(result);
76 
77     }
78 
79 }

 

posted @ 2017-04-26 10:03  MicroCat  阅读(1959)  评论(0编辑  收藏  举报