Linux 如何以用户而不是 root 用户身份运行 cron 作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8178545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:21:34  来源:igfitidea点击:

How to run the cron job as a user instead of root user

linuxbashcron

提问by Jeevan Dongre

I have few bash scripts which are adding to cron jobs with specified timing, but it needs to be executed as root user. I am trying to run those scripts i.e., crob jobs but it needs root user permission, since I am running this jobs in ubuntu ec2 instance where root user is restricted. What would be the work around to run those scripts as root user.

我有几个 bash 脚本会添加到指定时间的 cron 作业中,但它需要以 root 用户身份执行。我正在尝试运行这些脚本,即 crob 作业,但它需要 root 用户权限,因为我在 root 用户受限的 ubuntu ec2 实例中运行这些作业。以 root 用户身份运行这些脚本的解决方法是什么。

Thanks

谢谢

采纳答案by Tilo

There are several possibilities:

有几种可能:

1) add the script(s) to the crontab of root. To do this you have to do sudo su -or su -to become root, then add the cron jobs by using crontab -e

1) 将脚本添加到 root 的 crontab 中。为此,您必须执行sudo su -su -成为 root,然后使用以下命令添加 cron 作业crontab -e

2) allow a non-root user to use a crontab, and add the cron job to that user's crontab , by using crontab -eandset the set-uid flag of your script and change ownership to root, so it will execute as root chmod +s scriptname; chown root scriptname

2) 允许非 root 用户使用 crontab,并将 cron 作业添加到该用户的 crontab 中,方法是使用crontab -e设置脚本的 set-uid 标志并将所有权更改为 root,因此它将以 root 身份执行chmod +s scriptname; chown root scriptname

回答by Brendan Long

You can make a script execute as root by using the setuid flag, which makes a script run as its owner:

您可以使用setuid 标志使脚本以 root 身份执行,这使脚本以其所有者身份运行:

chmod +s yourscript
chown root yourscript

Just make yourscriptrun whatever command you want to run as root.

只需yourscript运行您想以 root 身份运行的任何命令即可。

Note that with this method, any user can run the script.

请注意,使用此方法,任何用户都可以运行该脚本。

回答by MBober

Basile is right with his comment. If you want to run something as rootin Ubuntu, use sudo.

Basile 的评论是对的。如果您想像root在 Ubuntu 中一样运行某些东西,请使用sudo.

If you want to execute a script (or some commands) automatically with superuser rights without having to type in a password, run

如果您想使用超级用户权限自动执行脚本(或某些命令)而无需输入密码,请运行

sudo visudo

to edit the sudoersfile. To make sudostop asking for a password for a specific script (or command) insert

编辑sudoers文件。为了sudo停止要求特定脚本密码(或命令)插入

username ALL = NOPASSWD: /path/to/script

where usernameis the name of the user calling sudo.

哪里username是调用 sudo 的用户的名字。