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,如需转载请自行联系原作者
相关文章
|
6月前
|
人工智能 搜索推荐 IDE
MCP 是什么?一文看懂模型上下文协议
MCP(模型上下文协议)由Anthropic于2024年推出,旨在解决AI大模型的数据滞后问题,通过连接第三方数据源提升回答的时效性和相关性。传统联网搜索依赖公开信息,难以满足行业内部或定制化需求。MCP提供统一标准,使开发者能安全双向连接数据源与AI工具,简化集成流程。例如,Apifox MCP Server可将API文档作为数据源提供给支持MCP的IDE,助力智能代码生成。未来,MCP有望推动AI工具从封闭系统转向开放协作网络,显著提升开发效率与创新能力。
|
Serverless 云计算 Python
基本技术指标 Python 实现(1)
基本技术指标 Python 实现
451 3
|
Ubuntu 网络协议 Linux
Linux(20) Ubuntu 20.04 网络接口自动切换路由配置
Linux(20) Ubuntu 20.04 网络接口自动切换路由配置
874 0
|
网络协议 Linux 开发工具
Centos7 /etc/sysconfig/network-scripts/ifcfg-<interface>网络配置
自动化网络配置:NetworkManager 可以自动检测网络连接,并根据网络环境自动配置网络。这使得用户可以无需手动配置即可连接到网络。 支持多种网络连接:NetworkManager 支持多种网络连接,包括有线、无线、VPN、Wi-Fi 热点等。这使得用户可以根据需要选择合适的网络连接。 提供图形化和命令行工具:NetworkManager 提供了图形化工具和命令行工具,用户可以根据自己的喜好选择使用。
1117 4
|
Ubuntu Linux 开发工具
WSL2(3)安装Linux headers完美解决方案
WSL2(3)安装Linux headers完美解决方案
2097 0
|
数据安全/隐私保护 Windows
|
传感器 存储 机器学习/深度学习
Python树莓派开发
Python树莓派开发
621 0
Python树莓派开发
|
网络安全
解决win10下WinSCP老是断线重连
解决win10下WinSCP老是断线重连