[英]How to execute shell commands as root in Java
I'm working on a cross-platform installation utility written in Java. 我正在使用Java编写的跨平台安装实用程序。 I would like to be able to execute shell commands, for example "apt-get ..." on Linux.
我希望能够执行shell命令,例如在Linux上执行“ apt-get ...”。 I'm using the ProcessBuilder API for this purpose.
我为此使用ProcessBuilder API。
Unfortunately, some commands require root privileges. 不幸的是,某些命令需要root特权。 I would like to execute the following shell command as root:
我想以root身份执行以下shell命令:
bash -c apt-get install -y [some package] bash -c apt-get install -y [某些软件包]
If I try to add "sudo" before "apt-get" nothing works because there is no terminal "sudo" can get the password from. 如果我尝试在“ apt-get”之前添加“ sudo”,则不会起作用,因为没有终端“ sudo”可以从中获取密码。
What should I do in order to ask the user for a password and then execute the above mentioned shell command? 为了询问用户密码然后执行上述shell命令,我该怎么做?
A short code snippet would be very appreciated! 简短的代码片段将不胜感激! Thanks in advance!
提前致谢! Max
马克斯
您可以运行gksudo <your command>
但这会将您的应用程序gksudo <your command>
到某个UI,例如gnome,kde等。
You could write all the the root-tasks to a scriptfile and ask the user to execute it with root privileges. 您可以将所有的根任务写入脚本文件,并要求用户以root特权执行它。 I know this sounds clumsy, but its done that way by quite a lot of "enterprise level" software vendors (eg the (Java-) installer of the Oracle RDBMS at least up to 11g).
我知道这听起来很笨拙,但是它是由许多“企业级”软件供应商(例如,Oracle RDBMS的(Java)安装程序至少达到11g)完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.