java 代码执行linux命令


远程执行linux命令代码

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

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();
            }
        }
    }
}

你可能感兴趣的:(linux,java)