java调用ssh脚本

java调用ssh脚本

  1. 建立maven项目
    在这里插入图片描述
  2. 修改pom文件

 <!--java远程调用linux 脚本-->
    <dependency>
      <groupId>ch.ethz.ganymed</groupId>
      <artifactId>ganymed-ssh2</artifactId>
      <version>262</version>
    </dependency>
    
    <!-- lombok 自动生成getter/setter -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.22</version>
      <scope>provided</scope>
    </dependency>
  1. 编写ssh连接实体类
    在这里插入图片描述
  2. 编写ssh工具类

/**
 * @author qyl
 * @program SshConnectUtils.java
 * @Description ssh连接linux
 * @createTime 2022-08-15 09:03
 */
@Slf4j
public class SshConnectUtil {
    // 连接对象
    private static Connection connection;
    // 是否连接
    private static boolean isConnect = false;

    /**
     * @return boolean
     * @description 登录ssh
     * @author qyl
     * @date 2022/8/15 9:16
     */
    public static void login() throws IOException {
        connection = new Connection(Config.ip, Config.port);
        if (!isConnect) {
            connection.connect();
            isConnect = connection.authenticateWithPassword(Config.username, Config.password);
        }
    }

    /**
     * @description 运行ssh命令
     * @param command
     * @return String
     * @author qyl
     * @date 2022/8/15 18:12
     */
    public static String execute(String command) {
        Session session = null;
        try {
            session = connection.openSession();
            if (session != null) {
                session.execCommand(command);
                return processStdout(session.getStdout(), "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @description 关闭连接
     * @return boolean
     * @author qyl
     * @date 2022/8/15 18:13
     */
    public static boolean closeConnection() {
        connection.close();
        return isConnect = false;
    }

    /**
     * 获取控制台输出
     * @param in
     * @param charset
     * @return
     */
    public static String processStdout(InputStream in, String charset) {
        StringBuffer buffer = new StringBuffer();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new StreamGobbler(in), charset))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
  1. 编写测试hello.py
    在这里插入图片描述
  2. 进行最终测试在这里插入图片描述
    效果如下:
    在这里插入图片描述
    有不懂的欢迎提问~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值