RHEL服务器root无需密码切换用户执行脚本的可行方案问询
我在RHEL服务器上拥有root账号,服务器上有个简单脚本user.sh,内容如下:
#!/bin/bash echo $USER
用root执行它时输出为root。现在想在另一个脚本里,无需输入密码、不将密码存储在脚本或文件中、不修改/etc/sudoers,临时切换到other_user执行user.sh,之后自动回到root账号,请问这是否可行?
我已经尝试过的几种方法
方法1:使用分隔符执行代码块
脚本内容:
#!/bin/bash bash /user.sh su other_user <<EOF echo Current user: $USER EOF
输出结果:
root Current user: root
问题:这里的$USER是在root环境下提前解析的,所以输出还是root,并没有真正在other_user的环境下执行变量解析。
方法2:直接su切换用户后执行命令再退出
脚本内容:
#!/bin/bash bash /user.sh su other_user bash /user.sh exit
输出情况:脚本会暂停执行,终端直接切换到other_user的交互会话(显示root [other_user@my_server]$),必须手动输入exit才会回到root账号继续执行脚本。不过切到other_user后手动执行bash user.sh能得到预期的other_user输出。
方法3:用su - <username> -c执行脚本
脚本内容:
#!/bin/bash bash /user.sh su - other_user -c /path/user.sh
输出结果:
root -bash: /path/user.sh: Permission denied
问题:other_user没有访问该脚本路径或脚本本身的权限。
方法4:使用sudo -i -u other_user
和方法2的问题类似,会跳转到other_user的主目录,但同样进入交互会话导致脚本暂停,需要手动退出才能回到root。
可行的解决方案
其实这个需求完全可以实现,核心点在于:root账号切换到任何普通用户默认不需要输入密码,我们只需要避免进入交互会话,直接以非交互方式执行命令即可。下面给你两种可靠的方案:
方案1:使用su - <用户> -c执行脚本
首先解决方法3的权限问题:
- 如果你想让
other_user直接执行脚本,先给脚本和所在路径添加对应权限:
# 给脚本添加其他用户的执行权限 chmod o+x /path/user.sh # 给脚本所在目录添加其他用户的读和执行权限 chmod o+rx /path/
然后修改脚本为:
#!/bin/bash # 先以root执行脚本 bash /path/user.sh # 切换到other_user非交互执行脚本,执行完自动返回root su - other_user -c "bash /path/user.sh"
如果不想给脚本加执行权限,也可以用管道读取脚本内容执行(只要other_user有读权限就行):
su - other_user -c "cat /path/user.sh | bash"
注:
su -会加载other_user的完整环境变量,如果不需要加载完整环境,去掉-用su other_user -c "..."即可。
方案2:使用带单引号分隔符的Here-Doc
针对方法1的变量解析问题,只要把Here-Doc的分隔符用单引号括起来,就能避免root环境提前解析变量,确保命令在other_user环境下执行:
#!/bin/bash # 先以root执行脚本 bash /path/user.sh # 切换到other_user执行命令,执行完自动返回root su other_user <<'EOF' bash /path/user.sh EOF
这样执行后,输出会是:
root other_user
完全符合你的需求:无需密码、不存密码、不修改sudoers,自动切换执行后返回root。
内容的提问来源于stack exchange,提问作者CyberStems

