Java执行linux的脚本:
1 pom
<!-- shell认证支持 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
2 执行类
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import cn.hutool.core.util.CharsetUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
/**
* shell执行
*/
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ShellExecute {
/* 连接器 */
private Connection connect;
/* 主机(IP) */
private String host;
/* 连接端口 */
private Integer port;
/* 用户 */
private String user;
/* 密码 */
private String password;
/** 编码 */
private String charset = CharsetUtil.UTF_8;
/**
* 登录Centos主机
*/
private boolean login() {
if(Objects.nonNull(port)){
connect = new Connection(host, port);
}else {
connect = new Connection(host);
}
try {
connect.connect();
return connect.authenticateWithPassword(user, password);
} catch (IOException e) {
log.error("连接主机失败", e);
return false;
}
}
/**
* 获取返回信息
*/
private StringBuffer processStdout(InputStream in) {
byte[] buf = new byte[1024];
StringBuffer buffer = new StringBuffer();
try {
int length;
while ((length = in.read(buf)) != -1) {
buffer.append(new String(buf, 0, length, charset));
}
} catch (IOException e) {
log.error("执行shell获取返回时失败", e);
}
return buffer;
}
/**
* exec shell命令
*/
public String execute(String shell) {
InputStream inputStream = null;
StringBuffer result = new StringBuffer();
try {
// 认证登录信息
if (this.login()) {
// 登陆成功则打开一个会话
Session session = connect.openSession();
session.execCommand(shell);
inputStream = session.getStdout();
result = this.processStdout(inputStream);
connect.close();
}
} catch (Exception e) {
log.error("执行shell时失败", e);
throw new BusinessException("远程shell脚本执行失败");
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭输入流失败", e);
}
}
}
return result.toString();
}
}
3 执行
public static void main(String[] args) {
ShellExecute shellExecute = new ShellExecute();
shellExecute.setHost("1.1.1.1");
shellExecute.setPort(22);
shellExecute.setUser("root");
shellExecute.setPassword("root");
String result = shellExecute.execute("ls -l");
System.out.println(result);
}
网上借鉴,做一个笔记……