<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
複製代碼
Connection conn = new Connection(ipAddr);
複製代碼
boolean isAuthenticated = conn.authenticateWithPassword(userName, passWord);
複製代碼
它會返回一個布爾值,true 表明成功登錄目的服務器,不然登錄失敗。java
Session session = conn.openSession();
session.execCommand(「ifconfig」);
複製代碼
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
複製代碼
System.out.println(「ExitCode: 」 + session.getExitStatus());
複製代碼
session.close();
conn.close();
複製代碼
Tips:linux
- 經過第二部認證成功後當前目錄就位於/home/username/目錄之下,你能夠指定腳本文件所在的絕對路徑,或者經過cd導航到腳本文件所在的目錄,而後傳遞執行腳本所須要的參數,完成腳本調用執行。
- 執行腳本之後,能夠獲取腳本執行的結果文本,須要對這些文本進行正確編碼後返回給客戶端,避免亂碼產生。
- 若是你須要執行多個linux控制檯腳本,好比第一個腳本的返回結果是第二個腳本的入參,你必須打開多個Session,也就是屢次調用 Session sess = conn.openSession();,使用完畢記得關閉就能夠了。
public class SSHTool {
private Connection conn;
private String ipAddr;
private Charset charset = StandardCharsets.UTF_8;
private String userName;
private String password;
public SSHTool(String ipAddr, String userName, String password, Charset charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
/** * 登陸遠程Linux主機 * * @return 是否登陸成功 */
private boolean login() {
conn = new Connection(ipAddr);
try {
// 鏈接
conn.connect();
// 認證
return conn.authenticateWithPassword(userName, password);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/** * 執行Shell腳本或命令 * * @param cmds 命令行序列 * @return 腳本輸出結果 */
public StringBuilder exec(String cmds) throws IOException {
InputStream in = null;
StringBuilder result = new StringBuilder();
try {
if (this.login()) {
// 打開一個會話
Session session = conn.openSession();
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
conn.close();
}
} finally {
if (null != in) {
in.close();
}
}
return result;
}
/** * 解析流獲取字符串信息 * * @param in 輸入流對象 * @param charset 字符集 * @return 腳本輸出結果 */
public StringBuilder processStdout(InputStream in, Charset charset) throws FileNotFoundException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
// OutputStream os = new FileOutputStream("./data.txt");
try {
int length;
while ((length = in.read(buf)) != -1) {
// os.write(buf, 0, c);
sb.append(new String(buf, 0, length));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
public static void main(String[] args) throws IOException {
SSHTool tool = new SSHTool("192.168.100.40", "root", "123456", StandardCharsets.UTF_8);
StringBuilder exec = tool.exec("bash /root/test12345.sh");
System.out.println(exec);
}
}
複製代碼
echo "Hello"
複製代碼
輸出結果 shell