需要引入ganymed-ssh2-build210.jar包。
其實很簡單。所以直接貼代碼,代碼說話。
1 package com.eshore.framework.util; 2 3 4 5 import java.io.BufferedReader; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.IOException; 9 import java.io.InputStream; 10 import java.io.InputStreamReader; 11 import java.util.ArrayList; 12 import java.util.List; 13 14 import ch.ethz.ssh2.Connection; 15 import ch.ethz.ssh2.session; 16 import ch.ethz.ssh2.StreamGobbler; 17 import ch.ethz.ssh2.log.Logger; 18 /** 19 * shell腳本調用類 20 * @author clear 21 * 22 */ 23 public class SshBasic{ 24 25 //連接,登陸 26 public Connection login(String hostname,int port,String username,String passWord){ 27 28 //獲取連接 29 Connection conn = new Connection(hostname, port); 30 try { 31 //連接 32 conn.connect(); 33 //輸入賬號密碼登陸 34 boolean isAuthenticated = conn.authenticateWithPassword(username, password); 35 //登陸失敗,返回錯誤 36 if(isAuthenticated == false){ 37 throw new IOException("isAuthentication failed."); 38 } 39 } catch (IOException e) { 40 41 e.PRintStackTrace(); 42 } 43 44 return conn; 45 } 46 //獲取Session 47 public Session getSession(Connection conn){ 48 Session sess = null; 49 try { 50 sess = conn.openSession(); 51 } catch (IOException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 return sess; 56 } 57 //獲取控制臺打印信息 58 public String printCmd(String path,Connection conn,Session sess, String date, String city){ 59 String txt = ""; 60 try { 61 sess.execCommand("chmod 755 "+path+" && "+path+" "+date+" "+city); 62 //打印信息 63 InputStream stdout = new StreamGobbler(sess.getStdout()); 64 //打印錯誤 65 InputStream stderr = new StreamGobbler(sess.getStderr()); 66 BufferedReader brout = new BufferedReader(new InputStreamReader(stdout,"UTF-8")); 67 BufferedReader brerr = new BufferedReader(new InputStreamReader(stderr,"UTF-8")); 68 while(true){ 69 String line = brout.readLine(); 70 if(line==null){ 71 break; 72 } 73 txt += line+"<br/>"; 74 System.out.println(line); 75 } 76 while(true){ 77 String line = brerr.readLine(); 78 if(line==null){ 79 break; 80 } 81 txt += line+"<br/>"; 82 System.out.println(line); 83 } 84 } catch (IOException e) { 85 // TODO Auto-generated catch block 86 e.printStackTrace(); 87 } 88 89 return txt; 90 } 91 92 public static void main(String[] args) { 93 94 SshBasic m = new SshBasic(); 95 //連接并登陸 96 Connection conn = m.login("132.122.1.51", 22, "srglweb", "srglweb123"); 97 //獲取Session 98 Session sess = m.getSession(conn); 99 //獲取控制臺信息100 String cmd = m.printCmd("shelltest/two.sh", conn,sess,"20140905","200");101 System.out.println("cmd:"+cmd);102 System.out.println("--->"+sess);103 //判斷會話是否成功104 int result = sess.getExitStatus();//如果成功返回0105 System.out.println("result:"+result);106 sess.close();107 conn.close();108 }109 110 }
要解釋的也在代碼內。主要是記錄下,以后用的時候就不用找得麻煩了。
新聞熱點
疑難解答