Java实现跨服务器文件发送及远程执行命令

前言

        该内容实现了纯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();
			}
		}
	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现连接远程服务器执行命令,可以使用Java中的SSH协议。SSH(Secure Shell)是一种加密网络协议,可用于安全地连接到远程服务器执行命令Java中有一些SSH库可以用来实现这个功能,比如JSch和Apache Mina SSHD。下面是一个使用JSch的示例代码: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "remotehost.com"; String user = "username"; String password = "password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand("ls -la"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception e) {} } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 这个代码片段使用JSch创建一个SSH会话,并通过该会话连接到远程主机。然后它打开一个执行通道并设置要执行的命令(在这个例子中是“ls -la”)。执行通道连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开连接,并且会话关闭。 需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑使用密钥进行身份验证,而不是密码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值