How do I sudo the current process?

蹲街弑〆低调 提交于 2019-12-01 03:56:17

Unfortunately, I'm not aware of a way to do what you want to do cleanly. I think your best bet is to make the program setuid (or run it under sudo) and then either do your dirty work and drop permissions, or fork() and drop permissions from one process and keep the other one around to do your root work.

What you're looking for are the setuid(2) / setreuid(2) / setregid(2) / setgroups(2) calls, but they are all hard wired to not allow you to gain privileges mid-invocation. You can only use them to "give away" privileges, as far as I know.

Aptitude has a "become root" option. You may wish to see what the author did there.

ℝaphink

If you want to deal cleanly with administrative rights inside a program, you might want to use PolicyKit rather than sudo, depending on the OS you plan to run your program on.

For PolicyKit for Python, see python-slip.

Otherwise, there are two ways to call sudo to become root:

sudo -s

will make you root and keep your current environment (equivalent to sudo su)

sudo -i

will make you root and give you root's environment, too (equivalent to sudo su -)

Another way of dealing with the problem is to consider that you have the rights you need, and let the user of the program choose how to give the rights to your program (using sudo/setuid/unix groups/whatever else).

See also this question on ServerFault on the same subject.

Your magic function/command could be

sudo su
echo 'echo tee; echo hee'|sudo -s

The output is:

tee
hee

I don't like the idea of being able to run arbitrary commands as root from a lower privileged process. However, since you want it, one of the ideas that comes to mind is to keep a setuid restricted shell which can only execute the commands you're interested in allowing. You can then use the subprocess.Popen functions to run your command using this restricted shell that will run it with elevated privileges.

I wonder if this would work:

Add another group to your system, install the script as a root program and have the sudoers file contain a line that allows the script to be executed by this group. Finally add the group to the list of accounts that need to run the script.

Then the script can only be run by root or any account that has the special group in the group set after supplying the account password at the start.

See Sudo Manual for other options.

You want to authenticate with PAM. There's an example here.

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