Ganymed
SSH-2 for Java是一個純Java實現的SHH2庫,官網爲http://www.ganymed.ethz.ch/ssh2/,最新的更新時間爲2006年10月,在用之前,請仔細看一下FAQ,真的能避免很多很多問題
在google上找到的ganymed-ssh2的官網是http://www.ganymed.ethz.ch/ssh2/,進去看官網的英文簡介可以看到該網站已經不維護該項目,並已經遷移到http://www.cleondris.ch/,在這個網站點擊右上角的Contact,再點擊open source就可以看到這個項目的新家,http://www.cleondris.ch/opensource/ssh2/,上面簡單介紹了該項目能遠程連接上遠程機器,支持命令模式和shell模式,本地和遠程端口轉發,沒有任何JCE依賴等,最後特別指出這個項目是爲瑞士蘇黎世的一個項目所創建。下面提供了2010-08-23發佈的ganymed-ssh2-build251beta1.zip可供下載使用,下面還有在線文檔和FAQ供開發者參考。
JSch
採用java編寫,使用ssh來操作遠程服務器。JSch 是SSH2的一個純Java實現。它允許你連接到一個sshd 服務器,支持文件的上傳和下載,支持在遠程機上執行shell命令、shell腳本、重啓等操作。
但是這個類庫偏向底層,僅是ssh2的實現,連文件夾的上傳下載都不支持,並不是針對自動化部署的,編寫的代碼比較長,上手和實際使用起來不太方便,所以要對其進行必要的封裝,比如封裝連接的獲取釋放、文件夾和文件的拷貝、遠程命令的執行等。
sshxcute
sshxcute 框架是對JSch 的簡單封裝,提供了更爲便捷的 API 接口,提供了更加靈活實用的功能,從而可以讓開發人員更加得心應手的使用。sshxcute 是一個框架,它允許工程師利用 Java 代碼通過 SSH 連接遠程執行 Linux/UNIX 系統上的命令或者腳本,這種方式不管是針對軟件測試還是系統部署,都簡化了自動化測試與系統環境部署的步驟。
但是它的封裝比較簡單,功能比較弱,只有上傳和執行命令或腳本的功能。
包裝Ganymed。實現了文件的上傳下載,文件夾的上傳,遠程執行命令,執行本地命令等基礎API:
package base;
import java.io.IOException;
import java.io.InputStream;
public final class ExecLocakCommand {
public static final String processUseBasic(String cmd) {
Process p = null;
StringBuilder sb = new StringBuilder();
try {
String os = System.getProperty("os.name").toLowerCase();
if (os.startsWith("win")) {
String commands = "cmd /c " + cmd;
p = Runtime.getRuntime().exec(commands);
} else if (os.startsWith("linux")) {
String[] commands = new String[] { "/bin/sh", "-c", cmd };
p = Runtime.getRuntime().exec(commands);
}
String error = read(p.getErrorStream());
String outInfo = read(p.getInputStream());
String resultCode = "0";// 腳本中輸出0表示命令執行成功
if (error.length() != 0) { // 如果錯誤流中有內容,表明腳本執行有問題
resultCode = "1";
}
sb.append(resultCode).append("\n");
sb.append(error).append("\n");
sb.append(outInfo);
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
p.getErrorStream().close();
p.getInputStream().close();
p.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static final String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
int ch;
while (-1 != (ch = in.read()))
sb.append((char) ch);
return sb.toString();
}
public static void main(String[] args) {
String comands = "dir";
//String comands = "ls ";
String ret = ExecLocakCommand.processUseBasic(comands);
System.out.println(ret);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class propertyUtil {
private static Properties prop = new Properties();
private static void load(String fileName) {
try {
prop.load(new FileInputStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String fileName, String key) {
load(fileName);
return prop.getProperty(key);
}
public static void setProper(String fileName, String key, String value) {
try {
load(fileName);
prop.setProperty(key, value);
FileOutputStream fos = new FileOutputStream(fileName);
prop.store(fos, null);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(propertyUtil.getProperty("test.properties", "key"));
propertyUtil.setProper("test.properties", "key", "xxxx");
System.out.println(propertyUtil.getProperty("test.properties", "key"));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package base;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.common.base.Splitter;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class RemoteExecutionApi {
private int port = 22;
private String username;
private String password;
public RemoteExecutionApi(int port, String username, String password) {
super();
this.port = port;
this.username = username;
this.password = password;
}
public RemoteExecutionApi(String username, String password) {
super();
this.username = username;
this.password = password;
}
// 下載文件,目前只能下載單個文件
public void getFile(String remoteFile, String localTargetDirectory, String ips) {
Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);
for (String ip : result) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localTargetDirectory);
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
// Logger operator
System.exit(2);
}
}
}
//上傳文件或者文件夾
public void putFile(String localFile, String remoteTargetDirectory, String ips) {
Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);
for (String ip : result) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
System.err.println("authentication failed");
}
// folder
if (new File(localFile).isDirectory()) {
// 先創建根目錄
String dirName = new File(localFile).getName();
remoteTargetDirectory = remoteTargetDirectory + "/" + dirName;
Session sess1 = conn.openSession();
sess1.execCommand("mkdir -p " + remoteTargetDirectory);
sess1.waitForCondition(ChannelCondition.EOF, 0);
sess1.close();
putDir(conn, localFile, remoteTargetDirectory);
} else if (new File(localFile).isFile()) {// file
SCPClient client = new SCPClient(conn);
client.put(localFile, remoteTargetDirectory);
}
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
// Logger operator
System.exit(2);
}
}
}
private void putDir(Connection conn, String localDirectory, String remoteTargetDirectory) throws IOException {
String[] fileList = new File(localDirectory).list();
for (String file : fileList) {
String fullFileName = localDirectory + new File(localDirectory).separator + file;
if (new File(fullFileName).isDirectory()) {
final String subDir = remoteTargetDirectory + "/" + file;
Session sess = conn.openSession();
sess.execCommand("mkdir " + subDir);
sess.waitForCondition(ChannelCondition.EOF, 0);
sess.close();
putDir(conn, fullFileName, subDir);
} else {
SCPClient client = new SCPClient(conn);
client.put(fullFileName, remoteTargetDirectory);
}
}
}
// 執行命令
public String runCommand(String command, String ips) {
StringBuilder sb = new StringBuilder();
Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);
for (String ip : result) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
System.err.println("authentication failed");
}
Session sess = conn.openSession();
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
sb.append(line).append("\n");
}
System.out.println("ExitCode: " + sess.getExitStatus());
br.close();
sess.close();
conn.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
// Logger operator
System.exit(2);
}
}
return sb.toString();
}
// 刪除臨時文件
public void delTempDir(String remotePath, String ips) {
runCommand("rm -rf " + remotePath, ips);
}
// 修改配置文件
public void modfiyPropertyFile(String remoteFileName, String key, String value, String ips) {
String tempDir = "tempDir";
File folder = new File(tempDir);
folder.mkdirs();
Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);
for (String ip : result) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFileName, tempDir);
String tmpFileName = tempDir + File.separator
+ remoteFileName.substring(remoteFileName.lastIndexOf("/"));
propertyUtil.setProper(tmpFileName, key, value);
client.put(tmpFileName, remoteFileName.substring(0, remoteFileName.lastIndexOf('/')));
conn.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
// Logger operator
System.exit(2);
}
}
clearDir(folder);
}
private void clearDir(File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
clearDir(f);
f.delete();
}
}
file.delete();
}
// 在配置文件後添加新行
public void propertyFileAddNewline(String remoteFileName, String newline, String ips) {
runCommand("echo " + newline + " >> " + remoteFileName, ips);
}
// 重啓機器
public void reboot(String ips) {
runCommand("reboot", ips);
}
// 執行本地命令
public String runLoaclCommand(String command) {
return ExecLocakCommand.processUseBasic(command);
}
public static void main(String[] args) {
RemoteExecutionApi client = new RemoteExecutionApi("root", "123456");
// client.getFile("/root/test.txt","C:", "192.168.238.129");
//client.putFile("D:\\test", "/root", "192.168.238.129");
// String ret = client.runCommand("ls /", "192.168.238.129");
// System.out.println(ret);
// client.putDir("D:\\test", "/root", "192.168.238.129");
// client.modfiyPropertyFile("/root/test.proprety", "key", "yyy",
// "192.168.238.129");
// client.propertyFileAddNewline("/root/xx.txt", "yyyyy=xxxxx",
// "192.168.238.129");
String ret = client.runLoaclCommand("dir");
System.out.println(ret);
System.out.println("----");
}
}
---------------------
作者:jieniyimiao
來源:CSDN
原文:https://blog.csdn.net/u013467442/article/details/72621372
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!