Running UNIX commands as different user, from Java

烂漫一生 提交于 2019-11-28 08:27:47

Have sudo installed, have the user running the Java program entered in /etc/sudoers for the commands in question, and use sudo -u jim ls ~bob.

Problem solved. Used JSch (http://www.jcraft.com/jsch/) to SSH into the server with known username and password, and execute command. Thanks all for your suggestions!

Possibly a java implementation of Expect? ExpectJ comes up when googling but I couldn't find any documentation regarding running under 1.4.2.

Have you tried redirecting the sudo commands input and writing to that. I haven't used Java in a while but I believe there is a way to get the input stream and write to it. You could use that to write the password followed by a new line and sudo or su should accept the password.

Use getInputStream() and write your password out to that.

su jim -c ls ~Bob

Perhaps this would work:

Process process = Runtime.getRuntime().exec("su jim && ls ~bob");

OutputStream standardInput = process.getOutputStream();
Writer standardInputWriter = new OutputStreamWriter(standardInput);
standardInputWriter.write("password\n");
standardInputWriter.close();

I'm not sure this code:

Process p = Runtime.getRuntime().exec("su jim && ls ~bob");

will be executed in a shell, needed to evaluate the &&, that is a shell command (/bin/sh). You should pass the command "ls ~bob" via a command line swith of su. Something like:

su jim -c 'ls ~bob'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!