java遠端呼叫linux的命令或者指令碼
Java通過SSH2協議執行遠端Shell指令碼(ganymed-ssh2-build210.jar)
使用步驟如下:
1.導包
官網下載:
http://www.ganymed.ethz.ch/ssh2/
maven座標:
[java] view plain copy print?- <dependency>
- <groupId>com.ganymed.ssh2</groupId>
- <artifactId>ganymed-ssh2-build</artifactId>
- <version>210</version>
- </dependency>
<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.例項程式碼,這個類可以直接拷貝過去用
[java] view plain copy print?- 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
- */
- publicclass RemoteExecuteCommand {
- //字元編碼預設是utf-8
- privatestatic 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();
- }
- publicstaticvoid setCharset(String charset) {
- DEFAULTCHART = charset;
- }
- public Connection getConn() {
- return conn;
- }
- publicvoid setConn(Connection conn) {
- this.conn = conn;
- }
- public String getIp() {
- return ip;
- }
- publicvoid setIp(String ip) {
- this.ip = ip;
- }
- public String getUserName() {
- return userName;
- }
- publicvoid setUserName(String userName) {
- this.userName = userName;
- }
- public String getUserPwd() {
- return userPwd;
- }
- publicvoid setUserPwd(String userPwd) {
- this.userPwd = userPwd;
- }
- }
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-8
private 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;
}
}
測試程式碼:
[java] view plain copy print?- publicstaticvoid 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");
- }
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");
}
需要匯入的包:
[java] view plain copy print?- <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>
<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>
相關推薦
java遠端呼叫linux的命令或者指令碼
Java通過SSH2協議執行遠端Shell指令碼(ganymed-ssh2-build210.jar) 使用步驟如下: 1.導包 官網下載: http://www.ganymed.ethz.ch/ssh2/ maven座標: [java] view plain copy print?
java遠端連線linux,執行指令碼命令
1.maven的POM.xml需要配置包 <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifac
在Android APK中呼叫底層linux命令或者指令碼
由於工作需要,接觸到百度語音識別SDK移植,由於需要實現在APK裡面控制物理硬體的效果,第一次接觸到Runtime.getRuntime().exec方法。 通過網上查閱資料,得知Runtime.getRuntime().exec的使用方法,程式碼如下:
java遠端呼叫linux上jar包
首先在遠端伺服器上編寫一個測試指令碼test.sh,並賦予可執行許可權:chmod +x test.sh#!/bin/bash echo $1$1是指令碼傳進來的第一個引數,現在列印一下傳進來的第一個引數。在pom中新增依賴<dependency> <
java 遠端執行 linux 命令
Maven: <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 --> <dependency> <groupId>ch.e
java遠端呼叫ssh2執行Linux命令
java SSH2遠端登入Linux服務執行命令 前一段時間工作中用到了java遠端呼叫Linux伺服器,執行相關命令,因為比較常用,故此,在部落格中記錄下來。其中用到了ganymed-ssh2這個jar包,可以在http://www.ganymed.ethz
java本地呼叫cmd,shell命令,遠端呼叫Linux執行命令方法總結
有時候經常會碰到需要遠端呼叫Linux或者本地呼叫Linux或者本地呼叫cmd的一些命令,最近小結了一下這幾種用法 本地呼叫cmd命令 @Test public void testCmd()throws Exception{
Java 呼叫Linux 命令,並獲取命令執行結果
1.工具類 public class ExcuteLinux { public static String exeCmd(String commandStr) { String result = null; try { St
吻逗死(windows)系統下自動部署指令碼(for java spring*)及linux命令列工具
轉載請註明出處:https://www.cnblogs.com/funnyzpc/p/10051647.html (^^)(^^)自動部署指令碼原本在上個公司就在使用,由於近期同事需要手動部署一個SpringCloud應用,一邊是sftp軟體上傳,一邊是SourceCRT命令列工具,看這著實很累,就順手把我
Java遠端呼叫shell指令碼(專案實戰)
前言 Java遠端呼叫shell指令碼,需要用到SSH建立連結(類似於xshell連線linux),然後再根據合法的引數進行shell指令碼呼叫 1 首先,從業務層開始,我這裡實現重傳指令碼的業務,程式碼如下. //重傳 public
java程式碼中呼叫linux命令
有時候需要在java程式碼中呼叫linux的一些命令實現某些功能。例如1:將音訊的.wav格式轉換成.mp3格式,windows系統下可以直接呼叫ffmpeg的命令;在linux系統下,需要安裝配置好ffmpeg的環境,呼叫ffmpeg在linux轉換的命令。例如2:需要在linux
Java呼叫Shell命令和指令碼
1.介紹 有時候我們在Linux中執行Java程式時,需要呼叫一些Shell命令和指令碼。而Runtime.getRuntime().exec()方法給我們提供了這個功能,而且Runtime.getRuntime()給我們提供了以下幾種exec()方法: Process e
sshxcute --java遠端執行linux/unix命令的工具類
原文地址:https://www.ibm.com/developerworks/cn/opensource/os-sshxcute/ ----------------------------------------------------------------------
java呼叫linux命令並獲取返回值
其實就是用java的IO流去讀取檔案public static String ReadTxtFile(String strFilePath) { String path = strFilePa
java呼叫Linux命令
需求:呼叫一條命令(grep 'processor' /proc/cpuinfo | sort -u | wc -l)拿到系統的執行緒數(JAVA) String[] cmd = {"sh","-c","grep 'processor' /proc/cpuinfo | so
redis在linux中安裝步驟以及java遠端呼叫redis
redis在linux中安裝步驟: 1.安裝準備環境:安裝gcc yum install gcc-c++ 2.下載redis安裝包 wget http://download.redis.io/releases/redis-5.0.0.tar.gz 3.解壓redis tar
Java調用Linux命令(cd的處理)
time wait adl 連接 ktr lose exce 簡單 res 一、Java調用Linux系統的命令非常簡單 這是一個非常常用的調用方法示例: 1 public String executeLinuxCmd(String cmd) { 2
[一天幾個linux命令] shell指令碼之正則表示式
shell指令碼之正則表示式 原文連結:Linux–shell指令碼之正則表示式 概念及特點 概念 正則表示式是對字串操作的一種邏輯公式,就是用事先定義好的一些特定的字元、及這些特定字元的組合,組成一個"規則字串",這個"規則字串"用來表達對字串的一種過濾邏輯。規定一些特殊語
幾個Linux命令及指令碼使用中的奇淫巧技
例項1.建立一個別名,刪除原始檔案,同時在使用者的home目錄下backup中儲存副本。 #/bin/bash cp [email protected] ~/backup && rm -rf [email protected] 例項2.For
java中呼叫shell命令
import java.io.BufferedReader; import java.io.InputStreamReader; public class Shell { public static void main(String[] args) { String command =