简体   繁体   English

如何在Shell脚本中执行sudo命令?

[英]How Do I Execute a sudo command in a Shell Script?

I am using the LaunchD Task Scheduler app to schedule jobs on my Mac Mini. 我正在使用LaunchD任务计划程序应用程序在我的Mac Mini上安排作业。 I would like to execute the purge command every two hours so I won't have to remember to do this in the terminal. 我想每两个小时执行一次清除命令,所以我不必记得在终端中执行此操作。 I have to run this using the sudo command. 我必须使用sudo命令运行它。 I want to do this in a way that protects my password. 我想以保护我的密码的方式这样做。

I have found a lot of different ways to accomplish this with a lot of debate about the solutions. 通过对解决方案的大量争论,我找到了很多不同的方法来实现这一目标。 I decided for now to run the following script. 我现在决定运行以下脚本。 From my understanding this should keep the command from being written in .bash_history and in cache files. 根据我的理解,这应该使命令不会被写入.bash_history和缓存文件中。 Right now the permissions for the folder where I have my scripts (and each script) are set to admins & current user having access. 现在,我拥有脚本(和每个脚本)的文件夹的权限设置为admins和当前用户有权访问。

#!/bin/sh
export HISTIGNORE='*sudo -S*'
echo "mypassword" | sudo -S -k purge

I have read about a process where I could put a password in a secure file and I guess access the password from that file. 我已经阅读了一个可以将密码放在安全文件中的过程,我想从该文件中访问密码。 I would like to try that process but I could not find an example of how to do this. 我想尝试这个过程,但我找不到如何做到这一点的例子。 I'm thinking that referencing one secure file with the password may be better than putting the password in each shell script. 我认为使用密码引用一个安全文件可能比将密码放在每个shell脚本中更好。 I would also like to see the command in .bash_history. 我还想在.bash_history中看到命令。

The safe way to do this is to allow the user to run a specific command without a password. 执行此操作的安全方法是允许用户在没有密码的情况下运行特定命令。

See this question from one of StackOverflow's sister sites. 从StackOverflow的姐妹网站之一看到这个问题

You want a script to run, as root, every 2 hours so you do not need to remember? 您希望脚本以root身份每2小时运行一次,这样您就不需要记住了吗?

sudo crontab -e

0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/lightbe/swanky_script.sh

...and then your password is protected. ...然后您的密码受到保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM