java操作shell工具类

该博客介绍了如何在Java后台通过JSch库连接并执行远程Linux服务器的Shell命令,包括设置连接参数、发送命令及读取返回结果。示例展示了如何执行`lsof -i:8080`命令来检查端口占用情况。
摘要由CSDN通过智能技术生成

项目场景:

在开发自动化部署的过程中后台需要连接Linux服务器,如此就需要后台能改操作shell指令

引入依赖包

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

工具类

@Slf4j
public class ExecuteShellUtil {

	private Vector<String> stdout;

	Session session;

	public ExecuteShellUtil(final String ipAddress, final String username, final String password, int port) {
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(username, ipAddress, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect(3000);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}

	}

	public int execute(final String command) {
		int returnCode = 0;
		ChannelShell channel = null;
		PrintWriter printWriter = null;
		BufferedReader input = null;
		stdout = new Vector<String>();
		try {
			channel = (ChannelShell) session.openChannel("shell");
			channel.connect();
			input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
			printWriter = new PrintWriter(channel.getOutputStream());
			printWriter.println(command);
			printWriter.println("exit");
			printWriter.flush();
			log.info("The remote command is: ");
			String line;
			while ((line = input.readLine()) != null) {
				stdout.add(line);
				System.out.println(line);
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return -1;
		}finally {
			IoUtil.close(printWriter);
			IoUtil.close(input);
			if (channel != null) {
				channel.disconnect();
			}
		}
		return returnCode;
	}

	public void close(){
		if (session != null) {
			session.disconnect();
		}
	}

	public String executeForResult(String command) {
		execute(command);
		StringBuilder sb = new StringBuilder();
		for (String str : stdout) {
			sb.append(str);
		}
		return sb.toString();
	}

}

示例

//连接服务器
ExecuteShellUtil executeShellUtil = new ExecuteShellUtil("127.0.0.1", "root", "123456","8080");
String command ="lsof -i:8080";
 executeShellUtil.execute(command);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值