所需jar包,commons-io-2.6.jar, ganymed-ssh2-262.jar
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class DemoRunShell1 {
public static void main(String[] args) {
String ip = "192.168.137.190";
String username = "root";
String password = "111111";
String runshellbinbash = "'#!/bin/bash'";
String cmd = "rm -rf /home/tony_dir/run_hadoop_wordcount_1.sh;" +
"echo "+runshellbinbash+" >> /home/tony_dir/run_hadoop_wordcount_1.sh; " +
"echo >> /home/tony_dir/run_hadoop_wordcount_1.sh; " +
"chmod 777 /home/tony_dir/run_hadoop_wordcount_1.sh; " +
"/home/tony_dir/run_hadoop_wordcount_1.sh";
String chartset = "UTF-8";
Connection connection = null;
Session session = null;
//首先构造一个连接器,传入一个需要登陆的ip地址
try {
connection = new Connection(ip);
connection.connect();//连接
boolean isAuthenticated = connection.authenticateWithPassword(username, password);
if (isAuthenticated) {
System.out.println("连接成功");
} else {
throw new Exception("连接失败");
}
session = connection.openSession();
//把命令写入脚本,在执行该脚本
// session.execCommand(cmd);
// session.execCommand("/root/tony_dir/shell_demo/demo_for.sh");
// session.execCommand("/root/tony_dir/run_test1.sh");
session.execCommand("ifconfig");
// session.execCommand("pwd");
//获得标准输出流
InputStream is = new StreamGobbler(session.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is, chartset));
List result = new ArrayList();
for (String line = brs.readLine(); line != null; line = brs.readLine()) {
result.add(line);
System.out.println(line);
}
if(result.size() ==0) {
System.out.println(result);
}
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 1000 * 3600);
System.out.println("ExitCode: " + session.getExitStatus()); //得到脚本运行成功与否的标志 :0 成功,非0 失败
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
}
}
}