【问题描述】
之前一直用sudo su -切换到root账户,后来发现使用sudo -s也可以直接切换,便想深究。
【解决思路】
当然了,还是使用屡试不爽的方法,直接man sudo。后查到-s参数含义为
The -s (shell) option runs the shell specified by the SHELL envi- ronment variable if it is set or the shell as specified in the password database. If a command is specified, it is passed to the shell for execution via the shell’s -c option. If no command is specified, an interactive shell is executed.
大意为:
所运行的shell是由预先设置好的SHELL变量指定的,或者是由存放用户密码的数据库实体决定。 指定一个命令后,经由"-c"参数,最终传到shell里面执行。 如果没指定命令,就会交互执行shell。
好吧,翻译还是太生涩了,还是直接上实例吧。
比如新创建一个lxh用户,然后执行visudo,将下面一行加入到配置文件中
lxh ALL=(ALL) NOPASSWD: ALL
紧接着,切换到lxh用户下。
root@nfs-server lxh$su - lxh lxh@nfs-server ~$sudo -s root@nfs-server lxh$pwd /home/lxh root@nfs-server lxh$exit exit lxh@nfs-server ~$sudo su - root@nfs-server ~$pwd /root root@nfs-server ~$
可以看到,执行sudo su -后切换至root,同时环境变量HOME也切换到root下。而执行sudo -s后成功切换至root用户,但是家目录并没有切换到root下。
要想连带家目录一起切换,只需更改sudoers文件中的以下两行文件即可。
visudo #Defaults always_set_home #注释掉 意为保留原HOME变量的值 Defaults env_keep += "HOME" #不注释即可
接着再来一次sudo -s,可以看到,已成功切换到root用户且家目录也为/root
root@nfs-server lxh$visudo root@nfs-server lxh$exit exit lxh@nfs-server ~$sudo -s root@nfs-server ~$
【附录】
sudo常见命令总结:
1.sudo sh -c "cat 1.txt > 2.txt"
或
$ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"
sudo 后面跟的是exec 所以带上sh -c是commad
2.$ sudo -u yaz ls ~yaz
To list the home directory of user yaz on a machine where the file system holding ~yaz is not exported as root:
3.$ sudo -u www vi ~www/htdocs/index.html
To edit the index.html file as user www:
原文:http://xoyabc.blog.51cto.com/7401264/1723046