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;
public class Run {
public static void main(String[] args) {
String hostname ="host";
String username="username";
String password="password";
try{
//建立连接
Connection conn= new Connection(hostname);
conn.connect(null, 0, 10000) ;
//利用用户名和密码进行授权
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if(isAuthenticated ==false){
throw new IOException("Authorication failed");
}
//打开会话
Session sess = conn.openSession();
//执行命令
sess.execCommand("sh /test.sh");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout,"GBK"));
while(true){
String line = br.readLine();
if(line==null) break;
输出返回值
System.out.println(line);
}
System.out.println(sess.getExitStatus()+" "+(sess.getExitStatus()==null));
sess.close();
conn.close();
}catch(IOException e){
e.printStackTrace();
}
System.exit(0);
}
}
test.sh文件内容如下
#!/bin/sh
a="hello world"
echo $a
执行结果
hello world
0 false
正确执行,sess.getExitStatus()返回0.
本文介绍了一个使用Java通过SSH协议远程执行Linux Shell脚本的示例代码。该示例展示了如何建立SSH连接、执行命令并获取输出结果的过程。具体包括连接设置、身份验证、打开会话、执行命令及读取输出等步骤。
379

被折叠的 条评论
为什么被折叠?



