java模拟ssh执行shell命令

一、pom.xml

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

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>

二、代码实现

package com.jxq.ssh;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

/**
 * @date 2019/7/3 21:21
 */
public class SshBasic {
    private static final Logger LOGGER = LoggerFactory.getLogger(SshBasic.class);
    private Connection conn;
    private static SshBasic instance;
    private SshBasic() {
    }
    public static SshBasic getInstance() {
        if (instance == null) {
            synchronized (SshBasic.class) {
                instance = new SshBasic();
            }
        }
        return instance;
    }
    /**
     * 连接ssh
     * @param hostname 主机ip
     * @param username 用户名字
     * @param password 密码
     * @return
     */
    public Connection connect(String hostname, String username, String password) {
        try {
            conn = new Connection(hostname);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated == false) {
                throw new IOException("Authentication failed.");
            }
            System.out.println("与主机:" + hostname + "连接成功");
        } catch (IOException e) {
            System.out.println(e.getMessage() + e);
        }
        return conn;
    }

    /**
     * 执行命令
     * @param command 命令字符串
     * @return
     */
    public boolean execCommand(String command) {
        boolean flag = false;
        Session session = null;
        BufferedReader br = null;

        if (conn == null) {
            // IllegalStateException:无效状态异常
            throw new IllegalStateException("没有建立连接");
        }
        System.out.println("开始执行命令" + command);
        int length = -1;
        byte[] buffer = new byte[1024];
        long startTime = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        try {
            session = conn.openSession();
            session.execCommand(command);
            InputStream stderr = session.getStderr();
            while ((length = stderr.read(buffer)) > -1) {
                sb.append(new String(buffer, 0, length));
            }
            System.out.println(sb.toString()); // 实时打印命令执行情况
            flag = true;
            System.out.println("命令执行成功,耗时:秒" + (System.currentTimeMillis() - startTime) / 1000.0 + "秒");

        } catch (IOException e) {
            System.out.println(e.getMessage() + e);
        } finally {
            try {
                if (session != null) {
                    session.close();
                }
                if (null != br) {

                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (conn != null) {
            conn.close();
        }
    }

    public static void main(String[] args) {
        String hostname="192.168.226.128";
        String username="root";
        String password="root";
        SshBasic instance = SshBasic.getInstance();
        instance.connect(hostname,username,password);
        instance.execCommand("mkdir /root/1.txt");
   
        instance.close();
    }
}

3、执行结果
在这里插入图片描述
原文地址:https://blog.csdn.net/u013144287/article/details/77506334

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值