需要引入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 }
要解释的也在代码内。主要是记录下,以后用的时候就不用找得麻烦了。
新闻热点
疑难解答