zoukankan      html  css  js  c++  java
  • 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是需要修改的文件目录

  • 相关阅读:
    窗体控件JFrame的使用
    WindowBuilder的安装与简介
    Swing事件机制
    Swing的MVC结构
    Swing框架的继承关系
    SWT简介
    Swing简介
    AWT简介
    Java界面设计
    使用Java建立聊天客户端
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13490676.html
Copyright © 2011-2022 走看看