java远程调用linux的命令或者脚本
為什么80%的碼農都做不了架構師?>>> ??
轉載請出自出處: http://eksliang.iteye.com/blog/2105862? ?
? ?Java通過SSH2協議執行遠程Shell腳本(ganymed-ssh2-build210.jar)?
?使用步驟如下:
1.導包
官網下載:
http://www.ganymed.ethz.ch/ssh2/
maven坐標:
<dependency><groupId>com.ganymed.ssh2</groupId><artifactId>ganymed-ssh2-build</artifactId><version>210</version></dependency>?
2.apI說明
1.??首先構造一個連接器,傳入一個需要登陸的ip地址
Connection conn = new Connection(hostname);
2.??模擬登陸目的服務器?傳入用戶名和密碼?,
boolean isAuthenticated = conn.authenticateWithPassword(username, password);它會返回一個布爾值,true?代表成功登陸目的服務器,否則登陸失敗
3.??打開一個session,有點象Hibernate的session?,執行你需要的linux?腳本命令 。
Session sess = conn.openSession();
sess.execCommand("last");
4.?接收目標服務器上的控制臺返回結果,讀取br中的內容
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
5.得到腳本運行成功與否的標志?:0-成功?非0-失敗
System.out.println("ExitCode: " + sess.getExitStatus());
6.關閉session和connection
?sess.close();
?conn.close();
?
備注:
1.通過第2步認證成功后,當前目錄就位于/home/username/目錄之下,你可以指定腳本文件所在的絕對路徑,或者通過cd導航到腳本文件所在的目錄,然后傳遞執行腳本所需要的參數,完成腳本調用執行。
?
2.執行腳本以后,可以獲取腳本執行的結果文本,需要對這些文本進行正確編碼后返回給客戶端,避免亂碼產生。
?
3.如果你需要執行多個linux控制臺腳本,比如第一個腳本的返回結果是第二個腳本的入參,你必須打開多個Session,也就是多次調用
Session sess = conn.openSession();,使用完畢記得關閉就可以了
?
3.實例代碼,這個類可以直接拷貝過去用
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.commons.lang.StringUtils; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler;/*** 遠程執行linux的shell script* @author Ickes* @since V0.1*/ public class RemoteExecuteCommand {//字符編碼默認是utf-8private static String DEFAULTCHART="UTF-8";private Connection conn;private String ip;private String userName;private String userPwd;public RemoteExecuteCommand(String ip, String userName, String userPwd) {this.ip = ip;this.userName = userName;this.userPwd = userPwd;}public RemoteExecuteCommand() {}/*** 遠程登錄linux的主機* @author Ickes* @since V0.1* @return* 登錄成功返回true,否則返回false*/public Boolean login(){boolean flg=false;try {conn = new Connection(ip);conn.connect();//連接flg=conn.authenticateWithPassword(userName, userPwd);//認證} catch (IOException e) {e.printStackTrace();}return flg;}/*** @author Ickes* 遠程執行shll腳本或者命令* @param cmd* 即將執行的命令* @return* 命令執行完后返回的結果值* @since V0.1*/public String execute(String cmd){String result="";try {if(login()){Session session= conn.openSession();//打開一個會話session.execCommand(cmd);//執行命令result=processStdout(session.getStdout(),DEFAULTCHART);//如果為得到標準輸出為空,說明腳本執行出錯了if(StringUtils.isBlank(result)){result=processStdout(session.getStderr(),DEFAULTCHART);}conn.close();session.close();}} catch (IOException e) {e.printStackTrace();}return result;}/*** @author Ickes* 遠程執行shll腳本或者命令* @param cmd* 即將執行的命令* @return* 命令執行成功后返回的結果值,如果命令執行失敗,返回空字符串,不是null* @since V0.1*/public String executeSuccess(String cmd){String result="";try {if(login()){Session session= conn.openSession();//打開一個會話session.execCommand(cmd);//執行命令result=processStdout(session.getStdout(),DEFAULTCHART);conn.close();session.close();}} catch (IOException e) {e.printStackTrace();}return result;}/*** 解析腳本執行返回的結果集* @author Ickes* @param in 輸入流對象* @param charset 編碼* @since V0.1* @return* 以純文本的格式返回*/private String processStdout(InputStream in, String charset){InputStream stdout = new StreamGobbler(in);StringBuffer buffer = new StringBuffer();;try {BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));String line=null;while((line=br.readLine()) != null){buffer.append(line+"\n");}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return buffer.toString();}public static void setCharset(String charset) {DEFAULTCHART = charset;}public Connection getConn() {return conn;}public void setConn(Connection conn) {this.conn = conn;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserPwd() {return userPwd;}public void setUserPwd(String userPwd) {this.userPwd = userPwd;} }? ? 測試代碼:
?
public static void main(String[] args) {RemoteExecuteCommand rec=new RemoteExecuteCommand("192.168.238.133", "root","ickes");//執行命令System.out.println(rec.execute("ifconfig"));//執行腳本rec.execute("sh /usr/local/tomcat/bin/statup.sh");//這個方法與上面最大的區別就是,上面的方法,不管執行成功與否都返回,//這個方法呢,如果命令或者腳本執行錯誤將返回空字符串rec.executeSuccess("ifconfig");}??
?
?需要導入的包:
<dependency><groupId>com.ganymed.ssh2</groupId><artifactId>ganymed-ssh2-build</artifactId><version>210</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version><type>jar</type><scope>compile</scope></dependency>?
參考文獻:http://wenku.baidu.com/link?url=jZXKsN-pbJStW4L93xNAxwcHirTYutHFMF79L1DzT1-HI8AQrJtL3pbU1V4VyERbkNLCIaHp2RtfYoh_5xwIBwQNMQ5NDqbOSg9SNVuSVGi
? ? ? ??
?
?
轉載于:https://my.oschina.net/boltwu/blog/412879
總結
以上是生活随笔為你收集整理的java远程调用linux的命令或者脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4g换5g需不需要换手机
- 下一篇: 3499起 TCL超薄零嵌冰箱T9发布: