java代码执行Linux的sudo命令

项目需要动态修改文件的所有者,记录一下

package com.zdyl.devicemanagement.common.utils;

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

public class SudoExecutor {

    public static void run(String cmd) throws IOException, InterruptedException {
        String sudoCmd = "sudo " + cmd;
        System.out.println(sudoCmd);
        Process process = Runtime.getRuntime().exec(sudoCmd);
        InputStreamReader ir = new InputStreamReader(process.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
    }

    public static void run(String[] cmds) throws IOException, InterruptedException {
        //      /* __debug_code__
        for (String cmd : cmds) {
            System.out.print(cmd);
            System.out.print(' ');
        }
        System.out.println();
        //      */
        Process process = Runtime.getRuntime().exec(cmds);
        InputStreamReader ir = new InputStreamReader(process.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
    }

    /**
     * 使用这个方法需要修改 /etc/sudoers
     *
     * @param cmd
     * @return
     */
    public static String[] buildCommands(String cmd) {
        String[] cmds = {shellName, shellParam, sudoCmd + " " + cmd};
        return cmds;
    }

    /**
     * 使用这个方法 不 需要修改 /etc/sudoers
     * @param cmd
     * @param sudoPasswd
     * @return
     */
    public static String[] buildCommands(String cmd, String sudoPasswd) {
        String[] cmds = {shellName, shellParam, "echo "" + sudoPasswd + "" | " + sudoCmd + " -S " + cmd};
        return cmds;
    }

    protected static String sudoCmd = "sudo";
    protected static String shellName = "/bin/bash";
    protected static String shellParam = "-c";


}

执行:

 //修改文件所有者
        String s = "chown -R ftp " + path;
        SudoExecutor.run(SudoExecutor.buildCommands(s, "password"));

path是需要修改的文件目录

原文地址:https://www.cnblogs.com/wiliamzhao/p/13490676.html