前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java: SpringBoot通过SSH远程执行命令

Java: SpringBoot通过SSH远程执行命令

作者头像
Freedom123
发布2024-03-29 13:36:13
1360
发布2024-03-29 13:36:13
举报
文章被收录于专栏:DevOpsDevOps

简介

Java通过SSH jar包,远程连接Host进行命令执行,支持接收正常返回结果以及异常结果

代码

Pom配置:

代码语言:javascript
复制
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

Java工具类 :

代码语言:javascript
复制
//SshUtil类定义
@Data
public class SshHost {
	String sshId;
	String platform;
	String ip;
	String user;
	String pwd;
	Integer port = 22;
}

//工具类定义 
@Slf4j
public class SshUtil {

	static public SshUtil sshUtil = null;

	static public SshUtil getRemoteClient(SshHost sshHost) throws JSchException {
		if (sshUtil == null) {
			sshUtil = new SshUtil(sshHost);
		}
		return sshUtil;
	}

	public SshHost sshHost = null;

	public SshUtil(SshHost host) throws JSchException {

		sshHost = host;
	}

	public List<String> exceCommond(String commond) {
		List<String> listResult = new ArrayList<>();
		Session session = null;
		try {
			JSch jsch = new JSch();
			session  = jsch.getSession(sshHost.getUser(), sshHost.getIp(), sshHost.getPort());
			session.setPassword(sshHost.getPwd());
			// 使用密码登录 禁止使用秘钥登录(默认先使用秘钥,失败后使用密码,耗时严重)
			session.setConfig("StrictHostKeyChecking", "no");
			session.setConfig("PreferredAuthentications", "password");

			// 连接超时
			session.connect(5000);
			Channel channel = session.openChannel("exec");
			ChannelExec exec = (ChannelExec) channel;
			// 返回结果流(命令执行错误的信息通过getErrStream获取)

			exec.setCommand(commond);
			exec.connect();
			try {
				// 开始获得SSH命令的结果
				while (true) {
					InputStream inputStream = exec.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
					String buf;
					// 此处是对结果进行封装,封装成自己想要的样子,我这里是map
					while ((buf = reader.readLine()) != null) {
						String gbk = new String(buf.getBytes("gbk"), StandardCharsets.UTF_8);
						listResult.add(gbk);
					}

					// 对错误的处理结果进行处理
					InputStream errorStream = exec.getErrStream();
					if (errorStream.available() > 0) {
						byte[] tmp = new byte[1024];
						int i = errorStream.read(tmp, 0, 1024);
						if (i < 0) {
							break;
						}

						log.error(new String(tmp, 0, i));
						//Throw.bizStatusException(new String(tmp, 0, i));
					}
					if (exec.isClosed()) {
						break;
					}
				}
			} finally {
				//关闭连接
				channel.disconnect();
			}
			return listResult;
		} catch (JSchException e) {
			e.printStackTrace();
			Throw.bizStatusException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			Throw.bizStatusException(e.getMessage());
		} finally {
			if (session != null && session.isConnected()) {
				session.disconnect();
			}
			return listResult;
		}
	}
}
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-03-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com