我正在尝试将子进程的用户更改为具有次要权限的用户 但是当我执行 ProcessBuilder 的 start 方法时,子进程 exec 与父进程的同一用户
LinkedList<String> commands = new LinkedList<String>();
commands.add("vlc");
ProcessBuilder builder = new ProcessBuilder(commands);
Map<String,String> enviroment = builder.environment();
enviroment.clear();
enviroment.put("USER", "otheruser");
enviroment.put("LOGNAME", "otheruser");
enviroment.put("PWD", "/home/otheruser");
enviroment.put("HOME", "/home/otheruser");
enviroment.put("USERNAME", "otheruser");
enviroment.put("SHELL", "/bin/false");
builder.directory(new File("/home/otheruser"));
Process process = builder.start();
process.waitFor();
我在 Linux(Ubuntu) 上工作
最佳答案
吉姆是完全正确的。 但是,如果您仍想以不同的用户身份运行程序,则必须使用依赖于平台的工具。
window : 使用 runas 命令,例如:runas/user:domain\jamesbond regedt32.exe 不幸的是,runas 要求用户手动输入密码。 以下文章介绍了如何解决该问题: http://www.windowsnetworking.com/kbase/WindowsTips/WindowsXP/AdminTips/Miscellaneous/RunprogramsasanotheruserinWindows2000WindowsXP.html
或者,您可以在 VBS 中编写自己的实用程序并从 java 运行它。有关详细信息,请参阅此帖子:http://weblogs.asp.net/hernandl/archive/2005/12/02/startprocessasuser.aspx
Unix: 请参阅 su 和 sudo 的引用资料。 su 很好,但它也需要密码(除非当前用户是 root)。 要解决此问题,您可以创建 expect 脚本(请参阅 http://en.wikipedia.org/wiki/Expect )。 Expect 默认安装在大多数 unix 发行版上。
祝你好运!
关于java - 使用 ProcessBuilder + java 改变用户环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4186904/