大网数据广告活动
服务器运维问答

The opposite of su: run a command without root privileges

· 52CE 我爱测

I'm writing a shell script where most commands don't require root privileges. The script should be ran by the administrator. But I would like to be able to "su" to a normal user account for the parts of the scripts that don't req…

问题原文

原帖链接 · John Smith Optional · CC BY-SA 3.0

I'm writing a shell script where most commands don't require root privileges. The script should be ran by the administrator. But I would like to be able to "su" to a normal user account for the parts of the scripts that don't require root privileges. This would minimize the number of operations done with root privileges and would improve security.

Is there a linux command to do that?

I know it is possible to su to any user account but I don't want to rely on the hypothesis that a particular username exists on the machine.

I thought of creating a temporary account for the time of the script and delete it at the end of the script. But if I don't set a password on this account, wouldn't an attacker be able to use it during the short lifetime of the account? I can't set the user shell to /sbin/nologin because apparently this prevents executing commands in a shell script "suing" to the account.

Thanks for your help.

已采纳解答

原帖链接 · Craig Watson · CC BY-SA 3.0

I would personally invert your strategy and run the script as a non-privileged user, with sudo used to run the commands requiring root privileges. Is there any specific reason you need to run the script as root?

To answer your question however, you can use the -c flag to run a specific command as a user:

su someuser -c "touch /tmp/file"

Reference: http://linux.die.net/man/1/su

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2013-05-14)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。