IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> Springboot连接远程服务器执行linux命令 -> 正文阅读

[大数据]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.前端展示

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

在这里插入图片描述

代码写的不好,还请各位大神批评指正!!!

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-01-01 13:58:47  更:2022-01-01 14:01:23 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 14:01:20-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码