java 远程linux系统,并读取执行shell命令

所需maven配置

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

代码及测试(可直接使用)

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * java 登录linux系统,并读取执行shell命令结果
 * @author wanghonggang
 * 2018-10-30
 */
public class LinuxShell {

	private Session session;

	/**
	 * 远程登录
	 * @param host 主机ip
	 * @param port 端口号,默认22
	 * @param user 主机登录用户名
	 * @param password 主机登录密码
	 * @return
	 * @throws JSchException
	 */
	public void login(String host, int port, String user,String password)  {
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(user, host, port);
			session.setPassword(password);
			// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
			session.setConfig("StrictHostKeyChecking", "no");
			// 连接超时
			session.connect(1000*10);

		} catch (JSchException e) {
			System.out.println("登录时发生错误!");
			e.printStackTrace();
		}
	}

	/**
	 * 执行shell脚本
	 * @param command shell命令脚本
	 * @return
	 * @throws Exception
	 */
	public String executeShell(String command) throws Exception {

		byte[] tmp = new byte[1024];
		StringBuffer resultBuffer = new StringBuffer(); // 命令返回的结果

		Channel channel = session.openChannel("exec");
		ChannelExec exec = (ChannelExec) channel;
		// 返回结果流(命令执行错误的信息通过getErrStream获取)
		InputStream stdStream = exec.getInputStream();

		exec.setCommand(command);
		exec.connect();

		try {
			// 开始获得SSH命令的结果
			while (true) {
				while (stdStream.available() > 0) {
					int i = stdStream.read(tmp, 0, 1024);
					if (i < 0) break;
					resultBuffer.append(new String(tmp, 0, i));
				}
				if (exec.isClosed()) {
//					System.out.println(resultBuffer.toString());
					break;
				}
				try {
					Thread.sleep(200);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} finally {
			//关闭连接
			channel.disconnect();
		}

		return resultBuffer.toString();
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		if (session.isConnected())
			session.disconnect();
	}

	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {

		String ip="192.168.x.xxx";
		String username="root";
		String password="xxx";

		LinuxShell linux = new LinuxShell();

		linux.login(ip, 22, username,password);
		String command = "ls";//命令
		try {
			String result = linux.executeShell(command);
			System.out.println(result);
			linux.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值