让Java程序运行sudo命令

在Linux下临时执行一些高权限命令需要用到sudo,但是sudo命令在运行时要求输入用户密码,这在手工操作的时候没什么问题,但若放在程序中调用sudo命令就比较麻烦,特别是若要在后台服务程序(如Java Servlet)中执行sudo命令的话,是没有可以是输入密码的地方的,这就要找个办法,能够自动给sudo命令提供密码,或者索性让sudo命令不需要密码也能执行。

1. 直接传递sudo密码

首先尝试了自动给sudo传输密码,方法如下:

echo \"password\" | sudo -S exec-cmd
这是利用linux的“管道”功能将密码通过标准输入传递给sudo,这就要求sudo命令带有-S参数,这个参数告诉sudo从标准输入stdin中获取密码,并且将输出信息写入到stderr设备中,而不是通过终端(Terminal)传递输入输出。这个命令在终端窗口中执行正常,但是放到Java代码中却没见效果。代码如下:

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

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

   /**
    * @param args
    * @throws IOException 
    * @throws InterruptedException 
    */
   public static void main(String[] args) throws IOException, InterruptedException
   {
      testExecuteCommand();
   }

   private static void testExecuteCommand() throws IOException, InterruptedException
   {
      String cmd = LogicVolume.sudoCmd + "ls -l /home/kingfox";
      LogicVolume.runCmd(cmd);
   }
}
执行的结果是把echo后面的字符串输出了一遍,没有真正执行sudo命令,看来是错误的方法。

2. 利用bash调用sudo

后来在网上查了资料,说是可以启动bash来执行sudo,于是把代码改写如下:

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

/**
 * @author kingfox
 *
 */
public class LogicVolume
{
   private static void runCmds(String[] cmds) throws IOException, InterruptedException
   {
      for(String cmd : cmds)
      {
         System.out.print(cmd);
         System.out.print(' ');
      }
      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);
      }
   }
   
   protected static String sudoCmd = "echo \"Abcd123456\" | sudo -S ";

   /**
    * @param args
    * @throws IOException 
    * @throws InterruptedException 
    */
   public static void main(String[] args) throws IOException, InterruptedException
   {
      testExecuteCommand();
   }

   private static void testExecuteCommand() throws IOException, InterruptedException
   {
      String cmds[] = {"/bin/bash", "-c", sudoCmd + "ls -l /home/kingfox"};
      LogicVolume.runCmds(cmds);
   }
}
执行结果如下:


看来这是可以正常运行的。

3. 取消sudo密码

还有一种彻底的方法,可以不要用密码,方法是修改/etc/sudoers文件,在其中加上一行:

username   ALL=(ALL) NOPASSWD:ALL
其中,username是当前试图执行sudo的用户的用户名。

这样修改之后,在终端中执行sudo命令就不再需要密码了,而上面的程序中sudoCmd的赋值也可以改成这样:

   protected static String sudoCmd = "sudo ";
不过这种做法可能会导致潜在的安全隐患,所以建议还是使用第2中种方法为好。

下面是一个完整的运行sudo命令的Java类:

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

/**
 * <p>
 * 这个类用于在Java程序中构建和执行Linux中的sudo命令。
 * 用法1:
 *    1. 执行buildCommands(...)方法构造sudo命令串。有两种方法可以构造sudo命令串:
 *
 *       若调用builderCommands(String cmd)方法构造sudo命令串,则此前应先修改/etc/sudoers文件,
 *       在其中添加一行:
 *          username  ALL=(ALL) NOPASSWD:ALL
 *       其中,"username"是需要运行这个程序的用户名。
 *
 *       若不想修改/etc/sudoers文件,则需要调用builderCommands(String cmd, String passwd)方法
 *       构造sudo命令串,
 *
 *       注意:无论使用哪种方法,形参cmd中均值包含需要以sudo方式执行的命令,不包含"sudo"命令本身。
 *
 *    2. 调用run(String[] cmds)执行由buildCommands返回的命令串数组。
 *
 * 用法2:
 *    1. 修改/etc/sudoers文件,在其中添加一行:
 *          username  ALL=(ALL) NOPASSWD:ALL
 *       其中,"username"是需要运行这个程序的用户名。
 *
 *    2. 调用run(String cmd)方法执行命令。
 *
 *    注意:形参cmd中仅包含需要以sudo方式执行的命令字符串,不要包含"sudo"命令本身。
 * </p>
 */

/**
 * @author kingfox
 *
 */
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);
      }
   }

   /**
    *
    * @param cmd
    * @return
    */
   public static String[] buildCommands(String cmd)   // to use this method, you should modify /etc/sudoers
   {
      String[] cmds = {shellName, shellParam, sudoCmd + " " + cmd};
      return cmds;
   }

   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";

   /**
    * @param args
    * @throws InterruptedException
    * @throws IOException
    */
   public static void main(String[] args) throws IOException, InterruptedException
   {
      SudoExecutor se = new SudoExecutor();
      se.testExecuteCommand();
   }

   private void testExecuteCommand() throws IOException, InterruptedException
   {
      String cmd = "cat /etc/sudoers";
      //      SudoExecutor.run(cmd);  // should modify /etc/sudoers
      //      SudoExecutor.run(buildCommands(cmd));  // should modify /etc/sudoers
      SudoExecutor.run(buildCommands(cmd, "Abcd123456"));    // don't need modify /etc/sudoers
   }

}




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值