shell(11) : java调用shell

参考 java操作linux,调用shell命令 - 路迢迢 - 博客园


import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * @Author: liyue
 * @Date: 2021/12/27/10:18
 * @Description:
 */
public class ShellUtil {

    private static Boolean isPrintShell = Boolean.FALSE;

    static {
        if (wc("ls |grep printShell") == 1) {
            isPrintShell = Boolean.TRUE;
        }
    }

    public static void main(String[] args) {
        write("t", "1111111\n2222\n4444");
        System.out.println(read("t"));
    }

    // 创建文件
    public static void write(String file, String content) {
        exec("cat > " + file + " <<'EOF'\n" + content + "\nEOF");
    }

    // 读取文件
    public static String read(String file) {
        return exec("cat " + file);
    }

    // 统计数量
    public static Integer wc(String cmd) {
        return Integer.parseInt(exec(cmd + "|wc -l").replaceAll(" ", ""));
    }

    // 计算大小
    // 远程加自定义命令
    // KB
    public static String remoteSizeExecSh(String ip, int port, String username, String cmd) {
        return "ssh -p " + port + " " + username + "@" + ip + " \"du -s " + cmd + "\" |awk '{print $1}'";
    }

    // 计算大小
    // 远程
    // KB
    public static String remoteSizeExec(String ip, int port, String username, String cmd) {
        return exec("ssh -p " + port + " " + username + "@" + ip + " \"du -s " + cmd + "\" |awk '{print $1}'");
    }

    // 计算大小
    // 本地
    // KB
    public static String localSizeExec(String file) {
        return exec("du -s " + file + " |awk '{print $1}'");
    }

    // 文件上传
    public static String upload(String ip, int port, String username, String file, String remotPath) {
        return exec("scp -r -P " + port + " " + file + " " + username + "@" + ip + ":" + remotPath);
    }

    // 文件下载
    public static String download(String ip, int port, String username, String localPath, String remotPath) {
        return exec("scp -r -P " + port + " " + username + "@" + ip + ":" + remotPath + " " + localPath);
    }

    // 远程命令
    public static String remoteExec(String ip, int port, String username, String cmd) {
        return exec("ssh -p " + port + " " + username + "@" + ip + " \"" + cmd + "\"");
    }

    // 远程解压
    public static String remoteExecTar(String ip, int port, String username, String file, String path) {
        String cmd = "tar -zxvf " + file + " -C " + path + "  >> /dev/null  2>&1";
        return exec("ssh -p " + port + " " + username + "@" + ip + " \"" + cmd + "\"");
    }

    // 远程命令
    // 本地追加处理
    public static String remoteExecLocal(String ip, int port, String username, String cmd, String localcmd) {
        return exec("ssh -p " + port + " " + username + "@" + ip + " \"" + cmd + "\" " + localcmd);
    }

    // 忽略输出
    public static void execNr(String cmd) {
        if (isPrintShell) {
            System.out.println("\033[37m" + DateUtil.getNowhm() + "|SHELL|开始执行shell,cmd:\n[--------------\n" + cmd + "\n--------------] \033[0m");
        }
        try {
            Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd + " >> /dev/null  2>&1"}, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 执行shell
    public static String exec(String cmd) {
        if (isPrintShell) {
            System.out.println("\033[37m" + DateUtil.getNowhm() + "|SHELL|开始执行shell,cmd:\n[--------------\n" + cmd + "\n--------------] \033[0m");
        }
        StringBuffer strList = new StringBuffer();
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd}, null, null);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            process.waitFor();
            while ((line = input.readLine()) != null) {
                strList.append(line).append("\n");
            }
            if (strList.length() > 0) {
                strList.delete(strList.length() - 1, strList.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isPrintShell) {
            System.out.println("\033[37m" + DateUtil.getNowhm() + "|SHELL|shell执行完成,result:\n[--------------\n" + strList + "\n--------------] \033[0m");
        }
        return strList.toString();
    }
}

END。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用`Runtime`类或`ProcessBuilder`类来调用Shell命令。下面是两种常见的方法: 1. 使用`Runtime`类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class ShellCommand { public static void main(String[] args) { try { // 执行Shell命令 String command = "ls -l"; Process process = Runtime.getRuntime().exec(command); // 读取命令输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 int exitCode = process.waitFor(); System.out.println("Exit Code: " + exitCode); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用`ProcessBuilder`类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class ShellCommand { public static void main(String[] args) { try { // 构建Shell命令 ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l"); // 执行Shell命令 Process process = processBuilder.start(); // 读取命令输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 int exitCode = process.waitFor(); System.out.println("Exit Code: " + exitCode); } catch (Exception e) { e.printStackTrace(); } } } ``` 这两种方法都可以用于调用Shell命令并获取输出结果。你可以根据需要修改命令和处理输出的方式。注意,调用Shell命令可能存在安全风险,请谨慎使用,并确保只执行可信任的命令。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值