What happens when I sudo bash -c? [closed]

狂风中的少年 提交于 2019-12-23 06:29:51

问题


I know that sudo bash -c 'some_command' will run some_command with the same privileges as sudo.

I'm confused as to what's happening? Does it run some_command in bash as sudo (same as sudo bash) then switch back to my current user? Why am I not left in an instance of bash with sudo privileges like I would when I run sudo bash?

I tried running man bash and it describes the -c option (quoted below). However, I am struggling to piece how the description relates to the behaviour I observed when running sudo bash -c 'some_command'

If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, they are assigned to the positional parameters, starting with $0.


回答1:


sudo switches users and then executes bash, passing it the other arguments. bash running as the new user runs the command in the argument after -c.




回答2:


Consider this snippet (pay attention to UID & PID/PPID columns.):

$ sudo ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
root      8997  8715  0 11:57 pts/17   00:00:00 sudo ps -f
root      8998  8997  0 11:57 pts/17   00:00:00 ps -f

$ sudo bash -c 'ps -f'
UID        PID  PPID  C STIME TTY          TIME CMD
root      8909  8715  3 11:55 pts/17   00:00:00 sudo bash -c ps -f
root      8910  8909  0 11:55 pts/17   00:00:00 ps -f

$ sudo bash -c 'echo hi; ps -f'
hi
UID        PID  PPID  C STIME TTY          TIME CMD
root      8957  8715  0 11:56 pts/17   00:00:00 sudo bash -c echo hi; ps -f
root      8958  8957  0 11:56 pts/17   00:00:00 bash -c echo hi; ps -f
root      8959  8958  0 11:56 pts/17   00:00:00 ps -f
  1. In 1st case, sudo starts ps -f as root user.
  2. In 2nd case, sudo starts bash as root user with arguments -c 'ps -f'. It appears that as an optimization, bash is using exec to start ps -f. Hence, only 2 processes are seen.
  3. In 3rd case, sudo starts bash as root user with arguments -c 'echo hi; ps -f'. The command (argument to -c) is not a simple executable + args. They are 2 commands separated by ;. So, bash cannot call exec directly. It uses the standard fork+exec mechanism. So, bash is the parent of the ps process.


来源:https://stackoverflow.com/questions/37851390/what-happens-when-i-sudo-bash-c

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