前言
该内容实现了纯Java代码跨Linux服务器拷贝文件及远程命令执行的功能。
public static String deploy (String host,String userName,String pwd,Integer port) {
try {
if (StringUtils.isAnyBlank(host, userName, pwd) || port == null) {
return "连接参数不完整,请检查!";
}
if (!this.isPortOpen(host, port, 2000)) {
return "目标服务器连接失败!";
}
//安装部署
this.remoteDeploy(host, port, userName, pwd, 5000l);
return null;
} catch (Exception e) {
logger.error("remote deploy error : ", e);
return e.getMessage();
}
}
/**
* 检查给定的主机和端口是否可达。
*
* @param host 要检查的主机名或IP地址
* @param port 要检查的端口号
* @param timeout 连接超时时间(毫秒)
* @return 如果主机和端口可达则返回true,否则返回false
*/
private boolean isPortOpen(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
socket.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 远程部署
* @param sshIp
* @param sshPort
* @param sshUser
* @param connTimeout
* @param sshPassword
* @throws Exception
*/
private void remoteDeploy(String sshIp, int sshPort, String sshUser, String sshPassword, long connTimeout) throws Exception {
logger.info("SSH start remoteDeploy......");
SshClient sshClient = null;
ClientSession clientSession = null;
try {
try {
sshClient = SshClient.setUpDefaultClient();
sshClient.start();
clientSession = sshClient.connect(sshUser, sshIp, sshPort).verify(connTimeout).getClientSession();
} catch (Exception e) {
logger.error("SSH connect host failed:", e);
throw new Exception("ssh连接所在的主机异常");
}
logger.info("SSH connect with pwd......");
try {
//解密连接SSH
clientSession.addPasswordIdentity(sshPassword);
clientSession.auth().verify(connTimeout);
} catch (Exception e) {
logger.error("SSH auth failed,auth timeout/username or password error:", e);
throw new Exception("ssh认证异常,认证超时/用户名或密码错误");
}
logger.info("SSH send file......");
//1.发送文件
SftpFileSystem sftpFileSystem = SftpClientFactory.instance().createSftpFileSystem(clientSession);
String remoteDir = "/opt/AutoDeploy";
try {
// 创建多层目录
Path remote = sftpFileSystem.getDefaultDir().resolve(remoteDir);
Files.createDirectories(remote);
// 将目标文件拷贝至目标目录
String fileName = "Install_Package.tar.gz";
Files.copy(Paths.get("/data/" + fileName), remote.resolve(fileName), REPLACE_EXISTING);
}catch (Exception e){
logger.error("SSH send file failed:", e);
throw new Exception("ssh发送文件失败");
}
logger.info("SSH start install......");
try {
//2.解压文件
String unzipCmd = String.format("cd %s && tar -zxf %s",remoteDir,fileName);
clientSession.executeRemoteCommand(unzipCmd);
logger.info("SSH unzip finished......");
//3.删除压缩包
String delZipCmd = String.format("rm -f %s/%s",remoteDir,fileName);
clientSession.executeRemoteCommand(delZipCmd);
logger.info("SSH delZipPackage finished......");
//4.启动程序
String startCmd = String.format("cd %s/bin && ./Start.sh > /dev/null 2>&1 &",remoteDir);
clientSession.executeRemoteCommand(startCmd);
logger.info("SSH install success");
} catch (Exception e) {
logger.error("SSH install failed:", e);
throw new Exception("ssh安装失败");
}
} catch (Exception e) {
throw new Exception(e);
} finally {
if(ObjectUtils.isNotEmpty(clientSession)) {
clientSession.close();
}
if(ObjectUtils.isNotEmpty(sshClient)) {
sshClient.close();
}
}
}