java ssh2 连接并执行 linux命令
2018-03-29 本文已影响43人
wolfies
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
或者官方下载: http://www.ganymed.ethz.ch/ssh2/
package ;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
* @Description 远程执行linux命令
*/
public class SSHUtil {
private String host; // ip
private String username;
private String password;
/**
* @param host(ip)
* @param username(用户名)
* @param password(密码)
*/
public SSHUtil(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
private Connection conn = null;
/**
* 连接
*/
private boolean connect() {
conn = new Connection(host);
try {
conn.connect();
if (conn.authenticateWithPassword(username, password)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 执行命令
*/
public String execute(String command) {
if (command == null || "null".equals(command)) {
return "传入命令为空!!!";
}
if (!connect()) {
return "连接服务器失败!!!";
}
Session session = null;
try {
session = conn.openSession();
session.execCommand(command);
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
StringBuffer sb = new StringBuffer();
// ExitCode正常为0
// 1:报错、2:误用命令、126:命令不得执行、127:没找到命令、130:ctrl+c结束、255:返回码超出范围
sb.append("ExitCode: " + session.getExitStatus() + "\n");
while (true) {
String line = br.readLine();
if (line == null)
break;
sb.append(line + "\n");
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "error";
} finally {
if (conn != null) {
conn.close();
}
if (session != null) {
session.close();
}
}
}
}
关于返回值(ExitCode),具体看这个。
http://www.tldp.org/LDP/abs/html/exitcodes.html
每次执行不同的对象的时候都会重新连接一次,懒得判断。
execCommand(cmd) 方法好像可以传进去一个String数组,懒得测。
我执行的命令经常给我返回ExitCode: null
反正正确执行了也懒得查什么原因了。