• 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是需要修改的文件目录

  • 相关阅读:
    .Net Core自动化部署系列(一):Jenkins + GitLab
    经典案例复盘——运维专家讲述如何实现K8S落地(摘抄)
    Quartz系列(一):基础介绍
    生产环境项目问题记录系列(二):同步方法调用异步方法
    微服务理论系列(一):服务发现四问四答(摘抄)
    Java中的继承、封装、多态的理解
    Java三大主流框架概述
    面试的技巧
    myBaits持久性框架
    MyBaits框架入门总结
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13490676.html
Copyright © 2020-2023  润新知