由于最近在做对zookeeper集群状态的监控,了解了一下如何使用java连接linux远程主机并执行shell脚本(或命令)
添加依赖
ssh2的依赖,版本很多,供参考
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
连接主机
代码中常量
private static String DEFAULTCHART = "UTF-8";
/**
* @param url 主机Ip
* @param user 用户名
* @param password 密码
* @return ch.ethz.ssh2.Connection
* @Author r
* @Description 连接主机
*/
public static Connection getConn(String url, String user, String password) {
Connection conn = new Connection(url);
try {
conn.connect();
//判断是否含有用户名与密码
if ((!StringUtils.isEmpty(user)) && (!StringUtils.isEmpty(password))) {
boolean isAuthenticated = conn.authenticateWithPassword(user, password);
if (!isAuthenticated) {
throw new IOException("Authentication failed");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
执行脚本
/**
* 执行shll脚本或者命令
* @param shell 命令(多条命令以;隔开)
* @return 结果
*/
public static String execute(Connection conn, String shell) {
String result = "";
try {
if (conn != null) {
Session session = conn.openSession();//打开一个会话
session.execCommand(shell);//执行命令
result = processStdout(session.getStdout(), DEFAULTCHART);
//如果为得到标准输出为空,说明脚本执行出错了
if (StringUtils.isBlank(result)) {
result = processStdout(session.getStderr(), DEFAULTCHART);
}
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
结果解析
/**
* 解析脚本执行返回的结果集
*
* @param in 输入流对象
* @param charset 编码
* @return 以纯文本的格式返回
*/
private static String processStdout(InputStream in, String charset) {
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
String line;
while ((line = br.readLine()) != null) {
buffer.append(line + "\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
执行多条命令
linux主机查询zookeeper状态
cd zookeeper-3.4.14/bin
./zkServer.sh status
java执行shell命令查询zookeeper状态
LinuxShellUtil.execute(conn, "cd zookeeper-3.4.14/bin;./zkServer.sh status");
以上便是通过java连接linux主机执行命令的简单实现