JschUtil ssh连接远程主机 利用线程控制执行时间
maven的依赖如下:
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.7</version>
</dependency>
自定义线程类
import cn.hutool.extra.ssh.JschUtil;
import com.jcraft.jsch.Session;
import lombok.Data;
import java.nio.charset.Charset;
@Data
public class MySSHThread extends Thread{
private String result;
private String host;
private String username;
private String passwd;
private String cmd;
public MySSHThread(String host, String username, String passwd, String cmd){
this.host=host;
this.username=username;
this.passwd=passwd;
this.cmd=cmd;
}
@Override
public void run(){
Session session = JschUtil.openSession(host, 22, username, passwd);
result = JschUtil.exec(session,cmd, Charset.defaultCharset());
JschUtil.close(session);
}
}
使用线程类进行连接主机及控制超时时间
MySSHThread mySSHThread=new MySSHThread(one.getHost(),one.getUser(),one.getPasswd(),one.getCmd());
mySSHThread.start();
mySSHThread.join(one.getOutTime()*1000);
Thread.State state = mySSHThread.getState();
if (state!=Thread.State.TERMINATED){
System.out.println("脚本执行超时");
System.out.println(mySSHThread.getResult());
return R.error("脚本执行超时");
}else {
System.out.println("脚本执行成功");
System.out.println(mySSHThread.getResult());
appListService.updateById(byId);
return R.ok("脚本执行成功");
}
one为一个远程对象
@Data
@TableName("sh_list")
public class ShListEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId
private Integer id;
/**
* 名称
*/
private String name;
/**
* 操作主机ip
*/
private String host;
/**
* 操作主机端口
*/
private String port;
/**
* 用户名
*/
private String user;
/**
* 操作主机密码
*/
private String passwd;
/**
* 执行命令
*/
private String cmd;
/**
* 对应应用id
*/
private Integer appId;
/**
* 开启/停止
*/
private String appAction;
/**
* 超时时间(s)
*/
private Integer outTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}