springboot 远程调用shell脚本,环境为windows

简介: 本文是博主学习SpringBoot的记录,希望对大家有所帮助。

由于需要调用shell脚本实现一些自动化控制操作,特记录一下实现代码。
主要使用到Ganymed SSH-2 for Java包,是java实现SSH-2协议的一个包,利用它在Java程序中连接SSH服务器。
包地址:点我下载
maven仓库地址:点我打开

pom.xml配置

......
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- SSH-2协议的包 -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>
    </dependencies>
......

yml配置文件

ssh1:
  host: 192.168.227.3
  port: 22
  user: root
  password: 123
 
ssh2:
  host: 192.168.227.4
  port: 22
  user: root
  password: 123

实体类

package com.bq8023.task.domain;

import lombok.Data;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author bq8023
 * @Date 21/5/9 19:36
 * @Version 1.0
 */
@Data
public class SSHEntity {
    /**
     * 编码
     */
    private Charset charset = StandardCharsets.UTF_8;
    /**
     * 主机(IP)
     */
    private String host;
    /**
     * 连接端口
     */
    private int port;
    /**
     * 账号
     */
    private String user;
    /**
     * 密码
     */
    private String password;

}

配置服务器SSH

package com.bq8023.task.conf;

import com.bq8023.task.domain.SSHEntity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置各服务器ssh连接信息
 *
 * @Author bq8023
 * @Date 21/5/9 20:44
 * @Version 1.0
 */

@Configuration
public class SSHConfig {

    @Bean(name = "ssh1")
    @ConfigurationProperties(prefix = "ssh1")
    public SSHEntity sshEntity3() {
        return new SSHEntity();
    }

    @Bean(name = "ssh2")
    @ConfigurationProperties(prefix = "ssh2")
    public SSHEntity sshEntity4() {
        return new SSHEntity();
    }

}

可以在此处配置多台服务器

具体业务

package com.bq8023.task.service;

import com.bq8023.task.domain.SSHEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author bq8023
 * @Date 21/5/9 19:56
 * @Version 1.0
 */
@Service
public interface SSHService {
    /**
     * 连接服务器并 执行shell脚本
     *
     * @param sshEntity ssh连接信息
     * @param shell     shell语句
     * @return shell执行结果
     * @throws IOException 读写异常
     */
    StringBuilder exec(SSHEntity sshEntity, String shell) throws IOException;
}
package com.bq8023.task.service.serviceImpl;

import com.bq8023.task.domain.SSHEntity;
import com.bq8023.task.service.SSHService;

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

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.springframework.stereotype.Service;

/**
 * @Author bq8023
 * @Date 21/5/9 19:57
 * @Version 1.0
 */
@Service
public class SSHServiceImpl implements SSHService {
    private Connection connect;

    /**
     * 连接服务器并 执行shell脚本
     *
     * @param sshEntity ssh连接信息
     * @param shell     shell语句
     * @return shell执行结果
     * @throws IOException 读写异常
     */
    @Override
    public StringBuilder exec(SSHEntity sshEntity, String shell) throws IOException {
        InputStream inputStream = null;
        StringBuilder result = new StringBuilder();
        try {
            // 认证登录信息
            if (this.login(sshEntity)) {
                // 登陆成功则打开一个会话
                Session session = connect.openSession();
                session.execCommand(shell);
                inputStream = session.getStdout();
                result = this.processStdout(inputStream);
                connect.close();
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
        }
        return result;
    }

    private boolean login(SSHEntity sshEntity) {
        connect = new Connection(sshEntity.getHost(), sshEntity.getPort());
        try {
            connect.connect();
            return connect.authenticateWithPassword(sshEntity.getUser(), sshEntity.getPassword());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private StringBuilder processStdout(InputStream in) {
        byte[] buf = new byte[1024];
        StringBuilder builder = new StringBuilder();
        try {
            int length;
            while ((length = in.read(buf)) != -1) {
                builder.append(new String(buf, 0, length));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder;
    }
}

测试

package com.bq8023.task;

import com.bq8023.task.domain.SSHEntity;
import com.bq8023.task.service.SSHService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;

@SpringBootTest
class JdtaskApplicationTests {

    @Qualifier("SSHServiceImpl")
    @Autowired
    private SSHService sshService;

    @Resource(name = "ssh1")
    private SSHEntity sshEntity;

    @Test
    void contextLoads() throws IOException {
        StringBuilder stringBuilder = sshService.exec(sshEntity, "pwd");
        System.out.println(stringBuilder);
    }
}

结果输出
在这里插入图片描述

目录
相关文章
|
3天前
|
分布式计算 Hadoop Shell
使用shell脚本实现自动SSH互信功能
使用shell脚本实现自动SSH互信功能
10 1
|
4天前
|
Unix Shell Linux
轻松编写 AIX Shell 脚本
轻松编写 AIX Shell 脚本
11 1
|
4天前
|
监控 关系型数据库 Shell
Shell脚本入门:从基础到实践,轻松掌握Shell编程
Shell脚本入门:从基础到实践,轻松掌握Shell编程
|
4天前
|
关系型数据库 MySQL Shell
在Centos7中利用Shell脚本:实现MySQL的数据备份
在Centos7中利用Shell脚本:实现MySQL的数据备份
|
6天前
|
Shell Linux 编译器
C语言,Linux,静态库编写方法,makefile与shell脚本的关系。
总结:C语言在Linux上编写静态库时,通常会使用Makefile来管理编译和链接过程,以及Shell脚本来自动化构建任务。Makefile包含了编译规则和链接信息,而Shell脚本可以调用Makefile以及其他构建工具来构建项目。这种组合可以大大简化编译和构建过程,使代码更易于维护和分发。
24 5
|
7天前
|
Shell 程序员 数据安全/隐私保护
shell 脚本 if-else判断 和流程控制 (基本语法|基础命令)
shell 脚本 if-else判断 和流程控制 (基本语法|基础命令)
|
7天前
|
存储 Shell C语言
shell脚本 编程 变量 基本入门(详解)
shell脚本 编程 变量 基本入门(详解)
|
7天前
|
Shell Linux 编译器
C语言,Linux,静态库编写方法,makefile与shell脚本的关系。
总结:C语言在Linux上编写静态库时,通常会使用Makefile来管理编译和链接过程,以及Shell脚本来自动化构建任务。Makefile包含了编译规则和链接信息,而Shell脚本可以调用Makefile以及其他构建工具来构建项目。这种组合可以大大简化编译和构建过程,使代码更易于维护和分发。
15 3
|
13天前
|
弹性计算 运维 监控
|
13天前
|
存储 弹性计算 运维
自动化收集员工信息的Shell脚本
【4月更文挑战第30天】
11 0