2023年12月9日發(作者:辦學模式)

java遠程執行Shell命令-通過ganymed-ssh2連接
一、實現遠程執行
此程序的目的是執行遠程機器上的Shell腳本。
【環境參數】
遠程機器IP:192.168.243.21
用戶名:ur
密碼:password
命令:python /data/applogs/bd-job/jobhandler/gluesource/
【具體步驟】
1、導入需要依賴的jar包。
2、編寫RemoteShellExecutor工具類。
package ;
import .*;
import t;
import lCondition;
import tion;
import n;
import Gobbler;
import s;
public class RemoteShellExecutor {
private Connection conn;
/** 遠程機器IP */
private String ip;
/** 用戶名 */
private String osUrname;
/** 密碼 */
private String password;
private String chart = tChart().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
public RemoteShellExecutor(String ip, String usr, String pasword) {
= ip;
name = usr;
rd = pasword;
}
/**
* 登錄
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip);
t();
return ticateWithPassword(osUrname, password);
}
/**
* 執行腳本
*
* @param cmds
* @return
* @throws Exception
*/
public int exec(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
// Open a new {@link Session} on this connection
Session ssion = ssion();
// Execute a command on the remote machine.
mmand(cmds);
stdOut = new StreamGobbler(out());
outStr = processStream(stdOut, chart);
stdErr = new StreamGobbler(err());
outErr = processStream(stdErr, chart);
rCondition(_STATUS, TIME_OUT);
n("outStr=" + outStr);
n("outErr=" + outErr);
ret = tStatus();
} el {
throw new Exception("登錄遠程機器失敗" + ip); // 自定義異常類 實現略
}
} finally {
if (conn != null) {
();
}
uietly(stdOut);
uietly(stdErr);
}
return ret;
}
private String processStream(InputStream in, String chart) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while ((buf) != -1) {
(new String(buf, chart));
}
return ng();
}
public static void main(String args[]) throws Exception {
RemoteShellExecutor executor = new RemoteShellExecutor("192.168.243.21", "ur", "password");
// 執行 參數為java Know dummy
n(2("python /data/bluemoon/kettle/runScript/ods/fact_org_ "));
}
}
3、運行結果
備份數據成功。
4、說明:
getExitStatus方法的返回值
注:一般情況下shell腳本正常執行完畢,getExitStatus方法返回0。
此方法通過遠程命令取得Exit Code/status。但并不是每個rver設計時都會返回這個值,如果沒有則會返回null。
二、ganymed-ssh講解:
1. Jar包:
2. 步驟:
a) 連接:
Connection conn = new Connection(ipAddr);
t();
b)認證:
boolean authenticateVal = ticateWithPassword(urName, password);
c) 打開一個Session:
if(authenticateVal)
Session ssion = ssion();
d) 執行Shell命令:
1)若是執行簡單的Shell命令:(如 jps 、last 這樣的命令 )
mmand(cmd);
2) 遇到問題:
用方法execCommand執行Shell命令的時候,會遇到獲取不全環境變量的問題,
比如執行 hadoop fs -ls 可能會報找不到hadoop 命令的異常
試著用execCommand執行打印環境變量信息的時候,輸出的環境變量不完整
與Linux主機建立連接的時候會默認讀取環境變量等信息
可能是因為ssion剛剛建立還沒有讀取完默認信息的時候,execCommand就執行了Shell命令
解決:
所以換了另外一種方式來執行Shell命令:
// 建立虛擬終端
tPTY("bash");
// 打開一個Shell
hell();
// 準備輸入命令
PrintWriter out = new PrintWriter(in());
// 輸入待執行命令
n(cmd);
n("exit")
// 6. 關閉輸入流
();
// 7. 等待,除非1.連接關閉;2.輸出數據傳送完畢;3.進程狀態為退出;4.超時
rCondition( | | _STATUS , 30000);
用這種方式執行Shell命令,會避免環境變量讀取不全的問題,第7步里有許多標識可以用,比如當exit命令執行后或者超過了timeout時間,則ssion關閉
這里需要注意,當一個Shell命令執行時間過長時,會遇到ssh連接超時的問題,
解決辦法:
1. 之前通過把Linux主機的sshd_config的參數ClientAliveInterval設為60,同時將第7步中timeout時間設置很大,來保
證命令執行完畢,
因為是執行Mahout中一個聚類算法,耗時最少7、8分鐘,數據量大的話,需要幾個小時。
2. 后來將命令改成了nohup的方式執行,nohup hadoop jar .... >> && touch &
這種方式是提交到后臺執行,即使當前連接斷開也會繼續執行,把命令的輸出結果寫入日志,如果hadoop命令執行成
功,則生成.end文件
獲取文件的方法 也提供了,如下
SCPClient scpClient = SCPClient();
("remoteFiles","localDirectory"); //從遠程獲取文件
e) 獲取Shell命令執行結果:
InputStream stderr = new StreamGobbler(err());
InputStream in = new StreamGobbler(out());
獲取流中的數據:
private String processStdErr(InputStream in, String chart)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in, chart));
StringBuffer sb = new StringBuffer();
if (ble() != 0) {
while (true) {
String line = ne();
if (line == null)
break;
(line).append(perty("tor"));
}
}
return ng();
}
三、使用實
1、使用mmand(cmds);來執行命令會出現一個問題,就是還沒有加載完成服務器的環境變量就開始執行命令了
這導致了很多情況是找不到命令,解決的辦法就是:
/**
* 執行腳本
*
* @param cmds
* @return
* @throws Exception
*/
public int exec2(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
Session ssion = ssion();
// 建立虛擬終端
tPTY("bash");
// 打開一個Shell
hell();
stdOut = new StreamGobbler(out());
stdErr = new StreamGobbler(err());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdOut));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stdErr));
// 準備輸入命令
PrintWriter out = new PrintWriter(in());
// 輸入待執行命令
n(cmds);
n("exit");
// 6. 關閉輸入流
();
// 7. 等待,除非1.連接關閉;2.輸出數據傳送完畢;3.進程狀態為退出;4.超時
rCondition( | | _STATUS , 30000);
n("Here is the output from stdout:");
while (true)
{
String line = ne();
if (line == null)
break;
n(line);
}
n("Here is the output from stderr:");
while (true)
{
String line = ne();
if (line == null)
break;
n(line);
}
/* Show exit status, if available (otherwi "null") */
n("ExitCode: " + tStatus());
ret = tStatus();
();/* Clo this ssion */
();/* Clo the connection */
} el {
throw new Exception("登錄遠程機器失敗" + ip); // 自定義異常類 實現略
}
} finally {
if (conn != null) {
();
}
uietly(stdOut);
uietly(stdErr);
}
return ret;
}
2、scp復制一個文件到服務器上
/**
* 遠程傳輸單個文件
*
* @param localFile
* @param remoteTargetDirectory
* @throws IOException
*/
public void transferFile(String localFile, String remoteTargetDirectory) throws IOException {
File file = new File(localFile);
if (ctory()) {
throw new RuntimeException(localFile + " is not a file");
}
String fileName = e();
execCommand("mkdir -p " + remoteTargetDirectory);
SCPClient sCPClient = SCPClient();
SCPOutputStream scpOutputStream = (fileName, (), remoteTargetDirectory, "0600");
String content = ng(new FileInputStream(file),_8);
(es());
();
();
}
/**
* 傳輸整個目錄
*
* @param localDirectory
* @param remoteTargetDirectory
* @throws IOException
*/
public void transferDirectory(String localDirectory, String remoteTargetDirectory) throws IOException {
File dir = new File(localDirectory);
if (!ctory()) {
throw new RuntimeException(localDirectory + " is not directory");
}
String[] files = ();
for (String file : files) {
if (With(".")) {
continue;
}
String fullName = localDirectory + "/" + file;
if (new File(fullName).isDirectory()) {
String rdir = remoteTargetDirectory + "/" + file;
execCommand("mkdir -p " + remoteTargetDirectory + "/" + file);
transferDirectory(fullName, rdir);
} el {
transferFile(fullName, remoteTargetDirectory);
}
}
}
使用:
public static void main(String[] args) throws IOException {
SSHAgent sshAgent = new SSHAgent();
ssion("192.168.243.21", "ur", "password#");
erFile("C:","/data/applogs/bd-job/jobhandler/2018-09-13");
();
}
參考文章
Java遠程執行Shell命令
Ganymed SSH2 模擬類似FileZilla遠程傳輸文件
本文發布于:2023-12-09 21:28:06,感謝您對本站的認可!
本文鏈接:http://www.newhan.cn/zhishi/a/170212848640126.html
版權聲明:本站內容均來自互聯網,僅供演示用,請勿用于商業和其他非法用途。如果侵犯了您的權益請與我們聯系,我們將在24小時內刪除。
本文word下載地址:java遠程執行Shell命令-通過ganymed-ssh2連接.doc
本文 PDF 下載地址:java遠程執行Shell命令-通過ganymed-ssh2連接.pdf
| 留言與評論(共有 0 條評論) |