sudo -s与sudo su -

简介:

【问题描述】

  之前一直用sudo su -切换到root账户,后来发现使用sudo -s也可以直接切换,便想深究。

【解决思路】

 当然了,还是使用屡试不爽的方法,直接man sudo。后查到-s参数含义为

1
2
3
4
5
  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.

大意为:

1
2
所运行的shell是由预先设置好的SHELL变量指定的,或者是由存放用户密码的数据库实体决定。
指定一个命令后,经由 "-c" 参数,最终传到shell里面执行。 如果没指定命令,就会交互执行shell。

好吧,翻译还是太生涩了,还是直接上实例吧。

比如新创建一个lxh用户,然后执行visudo,将下面一行加入到配置文件中

1
lxh ALL=(ALL) NOPASSWD: ALL

紧接着,切换到lxh用户下。

1
2
3
4
5
6
7
8
9
10
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文件中的以下两行文件即可。

1
2
3
visudo
#Defaults    always_set_home     #注释掉  意为保留原HOME变量的值
  Defaults   env_keep +=  "HOME"    #不注释即可

接着再来一次sudo -s,可以看到,已成功切换到root用户且家目录也为/root

1
2
3
4
5
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"

1
sudo  后面跟的是 exec   所以带上sh  -c是commad

2.$ sudo -u yaz ls ~yaz

1
2
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

1
  To edit the index.html  file  as user www:



本文转自 xoyabc 51CTO博客,原文链接:http://blog.51cto.com/xoyabc/1723046,如需转载请自行联系原作者
相关文章
|
3月前
|
Linux Shell 数据安全/隐私保护
linux命令之sudo/su
linux命令之sudo/su
34 7
|
5月前
|
Ubuntu 安全 Linux
su,su -,su - root,sudo,sudo -i,sudo su - 有何不同,在ubuntu和centos上用法有什么异同?
sudo -i命令:在Ubuntu和CentOS中,sudo -i命令可以启动一个新的shell会话,并将环境变量设置为root用户的环境变量。在使用该命令时同样需要输入当前用户的密码进行身份验证。
58 0
|
Shell 数据安全/隐私保护
su和sudo
su和sudo是我们常常需要用到的Linux命令,下面就将一下该命令怎么具体怎么使用,区别在哪
972 0
|
Shell 数据安全/隐私保护
3.7 su命令 3.8 sudo命令 3.9 限制root远程登录
3.7 su命令 3.8 sudo命令 3.9 限制root远程登录   su命令 切换用户 [root@centos_1 ~]# su - xiaobo   [root@centos_1 ~]# su - xiaobo 最后一次失败的登录:二 11月 21 01:43:41 CST 2017pts/0 上 最有一次成功登录后有 1 次失败的登录尝试。
1563 0
|
数据安全/隐私保护 网络安全 Shell
|
安全 数据安全/隐私保护
|
Shell 数据安全/隐私保护 网络安全
|
Oracle 关系型数据库 安全

热门文章

最新文章