I'm trying to change the user of the child process to a user with minor privileges but when i execute the start method of ProcessBuilder the subprocess exec with the same user of the parent
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("USE开发者_运维知识库RNAME", "otheruser");
enviroment.put("SHELL", "/bin/false");
builder.directory(new File("/home/otheruser"));
Process process = builder.start();
process.waitFor();
I'm working in Linux(Ubuntu)
Jim is absolutely right. But if you still want to run your program as different user you have to user platform dependent tools.
Windows: use runas command, e.g.: runas /user:domain\jamesbond regedt32.exe Unfortunately runas requires from user to type password manually. The following article explains how to work around the problem: http://www.windowsnetworking.com/kbase/WindowsTips/WindowsXP/AdminTips/Miscellaneous/RunprogramsasanotheruserinWindows2000WindowsXP.html
Alternatively you can write your own utility in VBS and run it from java. See this post for details: http://weblogs.asp.net/hernandl/archive/2005/12/02/startprocessasuser.aspx
Unix: see reference of su and sudo. su is fine but it requires password too (unless current user is root). To work around this you can create expect script (see http://en.wikipedia.org/wiki/Expect). Expect is installed on most unix distributions by default.
Good luck!
You cannot change the effective user just by passing in a different USER
environment variable. This is a security feature of Linux (and Unix in general), otherwise a malicious user could just set the USER variable to ROOT
. Subprocesses always execute as the same user as the parent unless the executable is marked setuid
or the process does a setuid() to change the effective user (and the setuid() is allowed).
精彩评论