java调用执行linux命令

java调用执行当前linux环境命令

public static String exec(String cmdStr){
        final StringBuilder str = new StringBuilder();
        final Runtime runtime = Runtime.getRuntime();
        if (runtime == null){
            return str.toString();
        }
        Process pro = null;
        BufferedReader input = null;
        PrintWriter writer = null;
        BufferedReader errorReader = null;
        try {
            pro = runtime.exec(cmdStr);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            writer = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
            errorReader = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
            String line ;
            while ((line = input.readLine())!= null){
                str.append(line).append("\n");
            }
            while ((line = errorReader.readLine())!= null){
                System.out.println(line);
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally {
            try {
                if (errorReader != null){
                    errorReader.close();
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            try {
                if (input != null){
                    input.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (writer != null){
                writer.close();
            }
            if (pro != null){
                pro.destroy();
            }

        }
        return str.toString();
    }

如果命令中包含了管道符(|),需要特殊处理。管道符是 Shell 中的特殊字符,如果直接使用 Runtime.getRuntime().exec() 方法执行该命令,可能会出现错误。

为了避免这个问题,您可以使用 ProcessBuilder 类来构建带有管道符的命令,例如:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HaproxyExecutor {

    public static String executeCommand(String command) {
        StringBuilder output = new StringBuilder();
        Process process = null;
        try {
            String[] commands = { "/bin/sh", "-c", command };
            process = new ProcessBuilder(commands).start();
            process.waitFor();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        finally {
            if (process != null) {
                process.destroy();
            }
        }

        return output.toString();
    }

}

执行远程Linux环境命令

import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;


import java.io.IOException;
import java.io.InputStream;

public class ExecuteShellUtil {

    public static Session session;

    //登录Linux服务器
    public static void loginLinux(String ipAddress,String username,String password,int port){
        try {
            JSch jSch = new JSch();
            session = jSch.getSession(username, ipAddress, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking","on");
            session.connect(100000);

        } catch (JSchException e) {
            System.out.println("登录服务器失败");
        }
    }


    //执行linux命令
    public static String exeCommand(String command){
        ChannelExec channelExec = null;
        String out = null;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
            InputStream in = channelExec.getInputStream();
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            out = IOUtils.toString(in,"UTF-8");
        } catch (JSchException | IOException e) {
            e.printStackTrace();
        }
        channelExec.disconnect();
        return out;
    }

    //断开连接
    public static void close(){
        if (session!= null){
            session.disconnect();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值