Springboot连接远程服务器执行linux命令

Springboot连接远程服务器执行linux命令

1.在pom文件中添加依赖,我这里用的是com.jcraft,还有一个是ch.ethz.ganymed,可以百度自行研究

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

2.添加工具类

@Component
public class SSHClient {
    /**
     * Server Host IP Address,default value is localhost
     */
    private String host = "localhost";

    /**
     * Server SSH Port,default value is 22
     */
    private Integer port = 22;

    /**
     * SSH Login Username
     */
    private String username = "";

    /**
     * SSH Login Password
     */
    private String password = "";

    /**
     * SSH Login pubKeyPath,这里如果要用密钥登录的话,是你本机的或者项目所在服务器的私钥地址
     */
    
    private String pubKeyPath = "C:/Users/zhangyanhe/.ssh/id_rsa";
//    private String pubKeyPath = "/root/.ssh/id_rsa";

    /**
     * JSch
     */
    private JSch jsch = null;

    /**
     * ssh session
     */
    private Session session = null;

    /**
     * ssh channel
     */
    private Channel channel = null;

    /**
     * timeout for session connection
     */
    private final Integer SESSION_TIMEOUT = 60000;

    /**
     * timeout for channel connection
     */
    private final Integer CHANNEL_TIMEOUT = 60000;

    /**
     * the interval for acquiring ret
     */
    private final Integer CYCLE_TIME = 100;

    public SSHClient() throws JSchException {
        // initialize
        jsch = new JSch();
        jsch.addIdentity(pubKeyPath);
    }

    public SSHClient setHost(String host) {
        this.host = host;
        return this;
    }

    public SSHClient setPort(Integer port) {
        this.port = port;
        return this;
    }

    public SSHClient setUsername(String username) {
        this.username = username;
        return this;
    }

    public SSHClient setPassword(String password) {
        this.password = password;
        return this;
    }

    public Session getSession() {
        return this.session;
    }

    public Channel getChannel() {
        return this.channel;
    }

    /**
     * login to server
     *
     */
    public void login(String username,String host,Integer port) {
        this.username = username;
        this.host = host;
        this.port = port;
        //我的是免密登录,所以不用密码
//        this.password = password;

        try {
            if (null == session) {
                session = jsch.getSession(this.username, this.host, this.port);
//                session.setPassword(this.password);
//                session.setUserInfo(new MyUserInfo());

                // It must not be recommended, but if you want to skip host-key check,
                // invoke following,
                session.setConfig("StrictHostKeyChecking", "no");
            }
            session.connect(SESSION_TIMEOUT);
        } catch (JSchException e) {
            this.logout();
        }
    }

    /**
     * login to server
     */
    public void login() {
        this.login(this.username,this.host,this.port);
    }

    /**
     * logout of server
     */
    public void logout() {
        this.session.disconnect();
    }

    /**
     * send command through the ssh session,return the ret of the channel
     *
     * @return
     */
    public synchronized String sendCmd(String command) {

        // judge whether the session or channel is connected
        if (!session.isConnected()) {
            this.login();
        }
        if (this.session == null)
            return null;
        Channel channel = null;
        //InputStream input = null;
        BufferedReader bufferedReader = null;
        String resp = "";
        try {
            channel = this.session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            channel.connect();

            bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                resp += line + "\n";
            }
            if (resp != null && !resp.equals("")) {
                resp = resp.substring(0, resp.length() - 1);
            }
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
        return resp;
    }
    //写个main方法测试一下效果
    public static void main(String[] args) throws JSchException {
        SSHClient sshClient=new SSHClient();
        sshClient.setHost("192.168.31.250").setPort(22).setUsername("root");
        sshClient.login();
        String commond5 = "sar 1 1";
        String ret5 = sshClient.sendCmd(commond5).trim();
        ret5=ret5.replaceAll("\n",",");
        String[] split5 = ret5.split(",");
        if(split5.length>0){
            ret5=split5[split5.length-1];
            ret5 = ret5.replaceAll("[平均时间:|Average:|all]", "").trim();
            ret5 = ret5.replaceAll("\\s{1,}", ",");
            String[] split6 = ret5.split(",");
            System.out.println(Arrays.toString(split6));
        }
        System.out.println("******************************");
        System.out.println(ret5);
        System.out.println("******************************");
        sshClient.logout();
    }

3.在controller中添加接口

我是在类初始话的时候就将连接建立好了,不然每次都要建立连接,然后关闭连接,耗费资源,因为我的接口是要定时的获取信息。如果发现有服务挂了,再次连接就可以了。
@Scope("session")
@RestController
@RequestMapping("/tool/ssh")
public class SSHController extends BaseController {

    @Autowired
    private ISysOuturlConfigService sysOuturlConfigService;
    
    //定义一个连接池,session作用域的
    private static Map<String, SSHClient> sshPool;

    @PostConstruct
    public void init() {
        //获取大数据服务
        try {
            System.out.println("初始化ssh连接池");
            sshPool = new HashMap<>();
            //获取服务的信息
            List<SysOuturlConfig> sysOuturlConfigs = sysOuturlConfigService.selectSysOuturlConfigList(null);
            for (SysOuturlConfig sysOuturlConfig : sysOuturlConfigs) {
                SSHClient sshClient = new SSHClient();
                sshClient.setHost(sysOuturlConfig.getServiceIp()).setPort(22).setUsername(sysOuturlConfig.getRootUser());
                sshClient.login();
                sshPool.put(sysOuturlConfig.getCode(), sshClient);
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询各个服务状态
     */

    @GetMapping("/dynamicInfo/{code}")
    public AjaxResult dynamicInfo(@PathVariable("code") String code) throws JSchException {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //根据code查询服务信息
        SSHClient sshClient = sshPool.get(code);

        if (!sshClient.getSession().isConnected()) {
            sshClient.login();
            sshPool.put(code,sshClient);
        }
        //执行命令
        //系统CPU情况
        String commond5 = "sar 1 1";
        String ret5 = sshClient.sendCmd(commond5).trim();
        ret5=ret5.replaceAll("\n",",");
        String[] split5 = ret5.split(",");
        if (split5.length > 0) {
            ret5=split5[split5.length-1];
            ret5 = ret5.replaceAll("[平均时间:|Average:|all]", "").trim();
            ret5 = ret5.replaceAll("\\s{1,}", ",");
            String[] split6 = ret5.split(",");
            map.put("cpuUserUsage", split6[0]);
            map.put("cpuSysUsage", split6[2]);
            map.put("cpuIdleUsage", split6[5]);
        } else {
            map.put("cpuUserUsage", 0);
            map.put("cpuSysUsage", 0);
            map.put("cpuIdleUsage", 0);
        }

        //系统内存情况
        double memtotal = 1.0;
        double memfree = 0.0;
        String commond6 = "cat /proc/meminfo | awk '$1 ~/MemTotal/' |awk '{print $2}'";
        String ret6 = sshClient.sendCmd(commond6).trim();
        if (StringUtils.isNotEmpty(ret6)) {
            memtotal = Double.valueOf(ret6);
        }
        String commond7 = "cat /proc/meminfo | awk '$1 ~/MemFree/' |awk '{print $2}'";
        String ret7 = sshClient.sendCmd(commond7).trim();
        if (StringUtils.isNotEmpty(ret7)) {
            memfree = Double.valueOf(ret7);
        }

        if (memtotal > 0 && memfree > 0 && (memtotal - memfree) > 0) {
            map.put("memUsage", (memtotal - memfree) / memtotal * 100);
        } else {
            map.put("memUsage", 0.0);
        }

        //应用信息
        SysOuturlConfig sysOuturlConfig = sysOuturlConfigService.selectSysOuturlConfigByCode(code);
        map.put("appName", sysOuturlConfig.getName());
        map.put("appUrl", sysOuturlConfig.getUrl());
        map.put("appIcon", sysOuturlConfig.getIcon());

        //应用服务状态和启动时间
        List<Map<String, Object>> list = new ArrayList<>();
        String retc = sshClient.sendCmd("ps aux|grep" + " " + code + " " + "|grep -v \"grep\"|awk '{print $2,$9,$10,$8}'");
        if (StringUtils.isNotEmpty(retc)) {
            retc = retc.replaceAll("\n", ",");
            String[] split = retc.split(",");
            for (String s : split) {
                Map<String, Object> mp = new HashMap<>();
                String[] sp = s.split("\\s{1,1}");
                mp.put("appPid", sp[0]);
                mp.put("appStartTime", sp[1] + " " + sp[2]);
                mp.put("appStatus", sp[3]);
                list.add(mp);
            }
        }

        map.put("appProcess", list);

        //应用服务CPU占用率
        double appCpuUsage = 0.0;
        String commond8 = "ps aux|grep" + " " + code + " " + "|grep -v \"grep\"|awk '{print $3}'";
        String ret8 = sshClient.sendCmd(commond8);
        ret8 = ret8.replaceAll("\n", ",");
        ret8 = ret8 + "0";
        String[] split1 = ret8.split(",");
        for (String s : split1) {
            appCpuUsage += Double.valueOf(s);
        }
        map.put("appCpuUsage", appCpuUsage);

        //应用服务内存占用率
        double memoryUsage = 0.0;
        String commond9 = "ps aux|grep" + " " + code + " " + "|grep -v \"grep\"|awk '{print $4}'";
        String ret9 = sshClient.sendCmd(commond9);
        ret9 = ret9.replaceAll("\n", ",");
        ret9 = ret9 + "0";
        String[] split9 = ret9.split(",");
        for (String s : split9) {
            memoryUsage += Double.valueOf(s);
        }
        map.put("appMemoryUsage", memoryUsage);

        return AjaxResult.success(map);
    }

    /**
     * 查询各个服务状态
     */

    @GetMapping("/sysInfo/{code}")
    public AjaxResult sysInfo(@PathVariable("code") String code) throws JSchException {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //根据code查询服务信息
        SSHClient sshClient = sshPool.get(code);

        if (!sshClient.getSession().isConnected()) {
            sshClient.login();
        }
        //执行命令
        //服务器名称
        String commond1 = "hostname";
        String ret1 = sshClient.sendCmd(commond1).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("hostName", ret1);
        //操纵系统
        String commond2 = "cat /etc/redhat-release";
        String ret2 = sshClient.sendCmd(commond2).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("operSystem", ret2);
        //服务器IP
        String commond3 = "ifconfig |head -2 |grep inet |awk '{print $2}'";
        String ret3 = sshClient.sendCmd(commond3).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("serviceIp", ret3);
        //系统架构
        String commond4 = "arch";
        String ret4 = sshClient.sendCmd(commond4).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("systemArch", ret4);
        //物理cpu个数
        String cmdPhysicalNum = "cat /proc/cpuinfo |grep \"physical id\"|sort|uniq|wc -l";
        String physicalNum = sshClient.sendCmd(cmdPhysicalNum).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("physicalNum", physicalNum);
        //每个物理cpu核数
        String cmdCoresNUm = "cat /proc/cpuinfo |grep \"cpu cores\"|wc -l";
        String coresNUm = sshClient.sendCmd(cmdCoresNUm).replaceAll("[\\s*\\t\\n\\r]", "");
        map.put("coresNUm", coresNUm);

        return AjaxResult.success(map);
    }
   }

4.前端展示

下面是我弄的前端页面。毕竟不是搞前端的,凑合看吧!!!

在这里插入图片描述

代码写的不好,还请各位大神批评指正!!!
  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值