java 代码执行linux命令

18 篇文章 2 订阅

远程执行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();
            }
        }
    }
}
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值