在Java中远程执行SSH2脚本命令

由于项目需要,需要在项目中执行SSH脚本,在网上找资料,发现使用
有两种方式可使用

1.使用ganymed-ssh2


        <!--ssh2架包-->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>

可以进行SSH的使用,包括远程登录,执行脚本命令等,具体的Util包如下:


//定义一个连接

/**
     * 
     * @Title: 连接Linux服务
     * @Description: 通过用户名和密码关联linux服务器
     * @return
     * @return String
     * @throws
     */
    public Connection connectLinux(String ip, String userName, String password) {

        log.info("ConnectLinuxCommand  scpGet===" + "ip:" + ip + "  userName:" + userName + "  commandStr:"
                + commandStr);

        String returnStr = "";
        boolean result = true;
        RemoteConnect remoteConnect = new RemoteConnect();
        remoteConnect.setIp(ip);
        remoteConnect.setUserName(userName);
        remoteConnect.setPassword(password);
        try {
Connection conn=login(remoteConnect)
            if (conn!=null) {
                         return conn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

/**
     * 
     * @Title: login
     * @Description: 用户名密码方式 远程登录linux服务器
     * @return: Boolean
     * @throws
     */
    public Connection login(RemoteConnect remoteConnect) {
        boolean flag = false;
        try {
            conn = new Connection(remoteConnect.getIp());
            conn.connect();// 连接
            flag = conn.authenticateWithPassword(remoteConnect.getUserName(), remoteConnect.getPassword());// 认证
            if (flag) {
                log.info("认证成功!");
                               return conn;
            } else {
                log.info("认证失败!");
                conn.close();
                               return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//此外,还可以使用证书登录,再写使用证书登录的操作

/**
     * 
     * @Title: execute
     * @Description: 远程执行shll脚本或者命令
     * @param conn 连接
     * @param cmd 脚本命令
     * @return: result 命令执行完毕返回结果
     * @throws
     */
    public  String execute(Connection  conn, String cmd) {
        String result = "";
        try {
            Session session = conn.openSession();// 打开一个会话
            session.execCommand(cmd);// 执行命令
            result = processStdout(session.getStdout(), DEFAULTCHARTSET);
            // 如果为得到标准输出为空,说明脚本执行出错了
            if (StringUtils.isBlank(result)) {
                result = processStdout(session.getStderr(), DEFAULTCHARTSET);
            }
            conn.close();
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

RemoteConnect 的内容为:

import lombok.Data;

@Data
public class RemoteConnect {

    private String ip;
    private String userName;
    
    private String password;
}

主要执行的命令为创建防火墙规则或重启一些指定的服务

测试命令为:

SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx",
                "firewall-cmd --zone=public --add-port=8850/tcp --permanent");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx", "firewall-cmd --reload");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx",
                " firewall-cmd --zone=public --remove-port=8850/tcp --permanent ");
SSH2Utils.connectLinux("192.168.xxx.xxx", "xxx", "xxxxxxxxx", "firewall-cmd --reload");

2.使用jsch

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

由于Hutool中已经进行了封装,因此直接使用Hutool操作即可,但是没有检查为什么,必须要引入上面的jsch包之后才能用

Session session = JschUtil.createSession("192.168.xxx.xxx", YYY, "XXXX", "xxxxxxxxxxx");
JschUtil.exec(session, "firewall-cmd --zone=public --add-port=8850/tcp --permanent", null);
JschUtil.exec(session, "firewall-cmd --reload", null);
JschUtil.exec(session, " firewall-cmd --zone=public --remove-port=8850/tcp --permanent ", null);
JschUtil.exec(session, "firewall-cmd --reload", null);

至此两种方式的使用,全部完成

可以使用免密登录,若生成的密钥版本太高,无法使用,可以使用
ssh-keygen -p -f id_rsa -m pem -P "" -N "" 更新密码为可用情况

JSch jsch = new JSch();

    try {
        String pubKeyPath = "C:\\Users\\用户名\\.ssh\\id_rsa";
        jsch.addIdentity(pubKeyPath);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    try {
        String username = "sss";
        String host = "192.168.20.207";
        Session session = jsch.getSession(username, host, 22);// 为了连接做准备
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

// Channel channel=session.openChannel("shell");
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(" docker stats --no-stream --format "{{ json . }}" ");
//channel.setCommand(" cat /proc/stat | grep "cpu "");
//channel.setCommand("cat /proc/net/dev");
//channel.setCommand("df -lm");
// channel.setCommand("ps aux");
// channel.setInputStream(System.in);
// channel.setOutputStream(System.out);
// InputStream in=channel.getInputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        channel.connect();
        
        String msg;
        while ((msg = in.readLine()) != null) {
            System.out.println(msg);
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容