public class SecureShellHelper {
private String username;
private String password;
private String host;
private Session session;
public synchronized void execCommand(String cmd) throws Exception {
createSession();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.connect(3 * 1000);
// 等待命令发送完成
TimeUnit.SECONDS.sleep(2);
channel.disconnect();
}
private void createSession() throws Exception {
if (session != null && session.isConnected())
return;
JSch jsch = new JSch();
session = jsch.getSession(this.username, this.host);
session.setPassword(this.password);
Properties prop = new Properties();
prop.setProperty("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
}
public void quit() {
if (session == null || !session.isConnected())
return;
session.disconnect();
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setHost(String host) {
this.host = host;
}
public static void executeRemoteCommand(Server server, String cmd)
throws Exception {
SecureShellHelper ssh = new SecureShellHelper();
ssh.setHost(server.getHost());
ssh.setUsername(server.getUsername());
ssh.setPassword(server.getPassword());
ssh.execCommand(cmd);
ssh.quit();
}
}
直接执行服务器端命令的方法
最新推荐文章于 2023-06-13 22:33:14 发布