Java远程链接服务器并执行命令--jsch

Java远程链接服务器并执行命令

1.依赖

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

2.demo

package common.utils;

import common.exception.SshException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @Describe:
 * @Author:zqm
 * @Date: 2022/2/28
 */
public class SshUtils {
    private static Session session = null;

    public static HashMap getResult(ConnectParam param) throws SshException {
        HashMap<String, String> map = new HashMap<>();
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(param.getUserName(), param.getIp(), Integer.parseInt(param.getPort()));
            session.setPassword(param.getPassWord());
            // 使用密码登录 禁止使用秘钥登录(默认先使用秘钥,失败后使用密码,耗时严重)
            session.setConfig("StrictHostKeyChecking", "no");
            session.setConfig("PreferredAuthentications", "password");
            // 连接超时
            session.connect(5000);
            Channel channel = session.openChannel("exec");
            ChannelExec exec = (ChannelExec) channel;
            // 返回结果流(命令执行错误的信息通过getErrStream获取)
            InputStream errorStream = exec.getErrStream();
            exec.setCommand(param.getCommand());

            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);
//                        String[] arrayList = gbk.replace(" ", "").split("\\|");
//                        if (arrayList.length >= 2) {
//                            map.put(arrayList[0], arrayList[1]);
//                        }
//                    }
                    // 对错误的处理结果进行处理
                    if (errorStream.available() > 0) {
                        byte[] tmp = new byte[1024];
                        int i = errorStream.read(tmp, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        throw new SshException(new String(tmp, 0, i));
                    }
                    if (exec.isClosed()) {
                        break;
                    }
                }

            } catch (SshException e) {
                throw new SshException(e.getMessage());
            } finally {
                //关闭连接
                channel.disconnect();
            }
            return map;
        } catch (Exception e) {
            throw new SshException(e.getMessage());
        } finally {
            close();
        }

    }


    /**
     * 关闭连接
     */
    private static void close() {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ConnectParam {
        private String userName = "root";
        private String passWord = "123456";
        private String ip;
        private String port = "22";
        private String command = "ls";

        public ConnectParam(String ip) {
            this.ip = ip;
        }

        public ConnectParam(String userName, String passWord, String ip, String port) {
            this.userName = userName;
            this.passWord = passWord;
            this.ip = ip;
            this.port = port;
        }
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        ConnectParam connectParam = new ConnectParam("168.1.1.112");
        System.out.println(getResult(connectParam));
    }

}

3.备注 – 连接远程耗时的原因

// 使用密码登录 禁止使用秘钥登录(默认先使用秘钥,失败后使用密码,耗时严重)
 session.setConfig("StrictHostKeyChecking", "no");
// 之前没加这句大概慢17s
 session.setConfig("PreferredAuthentications", "password");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值