使用ganymed工具調用ssh2
阿新 • • 發佈:2017-07-13
.sh basic string 賬號 clear () -- 調用 try
需要引入ganymed-ssh2-build210.jar包。
其實很簡單。所以直接貼代碼,代碼說話。
package com.eshore.framework.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import ch.ethz.ssh2.log.Logger; /** * shell腳本調用類 * @author clear * */ public class SshBasic{ //連接,登陸 public Connection login(String hostname,int port,String username,String password){//獲取連接 Connection conn = new Connection(hostname, port); try { //連接 conn.connect(); //輸入賬號密碼登陸 boolean isAuthenticated = conn.authenticateWithPassword(username, password); //登陸失敗,返回錯誤 if(isAuthenticated == false){throw new IOException("isAuthentication failed."); } } catch (IOException e) { e.printStackTrace(); } return conn; } //獲取Session public Session getSession(Connection conn){ Session sess = null; try { sess = conn.openSession(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sess; } //獲取控制臺打印信息 public String printCmd(String path,Connection conn,Session sess, String date, String city){ String txt = ""; try { sess.execCommand("chmod 755 "+path+" && "+path+" "+date+" "+city); //打印信息 InputStream stdout = new StreamGobbler(sess.getStdout()); //打印錯誤 InputStream stderr = new StreamGobbler(sess.getStderr()); BufferedReader brout = new BufferedReader(new InputStreamReader(stdout,"UTF-8")); BufferedReader brerr = new BufferedReader(new InputStreamReader(stderr,"UTF-8")); while(true){ String line = brout.readLine(); if(line==null){ break; } txt += line+"<br/>"; System.out.println(line); } while(true){ String line = brerr.readLine(); if(line==null){ break; } txt += line+"<br/>"; System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return txt; } public static void main(String[] args) { SshBasic m = new SshBasic(); //連接並登陸 Connection conn = m.login("132.122.1.51", 22, "srglweb", "srglweb123"); //獲取Session Session sess = m.getSession(conn); //獲取控制臺信息 String cmd = m.printCmd("shelltest/two.sh", conn,sess,"20140905","200"); System.out.println("cmd:"+cmd); System.out.println("--->"+sess); //判斷會話是否成功 int result = sess.getExitStatus();//如果成功返回0 System.out.println("result:"+result); sess.close(); conn.close(); } }
使用ganymed工具調用ssh2