远程执行linux命令代码

代码不是在服务器部署时,但是需要执行这个服务器的linux命令

maven库

<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>
package com.demo.common.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 * @author zhaosongbin
 */
public class SshUtil {

    private final static String host = "192.168.1.1";
    private final static int port = 22;
    private final static String username = "root";
    private final static String password = "root";
    private final static String directory = "/home/";
    private static SshUtil ftp = new SshUtil();
    private static Connection con = new Connection(host, port);

    /**
     * 执行传来的linux指令
     *
     * @param command
     * @return
     */
    public static List<String> execCom(String command) {
        Session session = ftp.session();
        BufferedReader br = null;
        List<String> msgList = new ArrayList<String>();
        try {
            session.requestPTY("vt100", 80, 24, 640, 480, null);
            session.execCommand(command);
            InputStream stdout = new StreamGobbler(session.getStdout());
            br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                msgList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        session.close();
        con.close();
        return msgList;
    }

    public Session session() {
        Session session = null;
        try {
            con.connect();
            // 远程服务器的用户名密码
            con.authenticateWithPassword(username, password);
            session = con.openSession();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return session;
    }


}

本地执行linux命令代码

代码在服务器部署,并且需要执行服务器linux命令

package com.demo.common.linux;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaosongbin
 */
public class RunTimeUtil {

    private final static Logger logger = LoggerFactory.getLogger(RunTimeUtil.class);

    private static List<String> msg=new ArrayList<String>();

    public static List<String> execCom(String cmd) {
        List<String> msgList=new ArrayList<String>();
        try {
            //执行命令
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});

            InputStreamReader ir = new InputStreamReader(process.getInputStream(),"utf-8");
            LineNumberReader input = new LineNumberReader(ir);

            String line;
            //输出结果
            while ((line = input.readLine()) != null) {
                msgList.add(line);
            }
        } catch (IOException e) {
            //捕捉异常
            logger.error("IOException " + e.getMessage());
        }
        return msgList;
    }

    public static List<String> execComs(String strings)  {

        msg.clear();
        try {
            //执行命令
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", strings});
            read(process.getInputStream(),"input");
            read(process.getErrorStream(),"error");
        } catch (IOException e) {
            //捕捉异常
           logger.error("IOException " + e.getMessage());
        }
        return msg;
    }
    private static void read(InputStream inputStream, String str) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                if("input".equals(str)){ msg.add(line);}
                else if("error".equals(str)){ msg.add(line);}

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐