可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to execute a command like this from a Ruby on Rails app:
sudo service squid3 restart
If i try it with this code:
It don't work, in the console i see that linux asks the password. How can i pass a password with this command? Or other suggestions...
回答1:
You can try the sudo -S flag if available on you system (check man):
echo secretPasswd | sudo -S service squid3 restart
This means that the password will be in clear so you can add the user which needs to perform the task to the sudoers (which creates another security issue by the way).
回答2:
You can add the following line to your sudoers file (/etc/sudoers)
rails_user ALL=(root) NOPASSWD:/usr/sbin/service
This will basically let the rails_user user execute the service command as sudo, and the system won't ask you for a password.
rails_user should be replaced with whatever user that you are running your rails process under. And you should also make sure that
Defaults requiretty
is not present in your /etc/sudoers. If not you won't be able use sudo from a script.
回答3:
You can use the expect method to catch the password prompt and send the password. However, it might be a better idea to allow your Rails user access to the service command without a password using the NOPASSWD option in /etc/sudoers.
回答4:
Does your sudo
have a -A
switch?
-A
Normally, if sudo requires a password, it will read it from the current terminal. If the -A
(askpass) option is specified, a helper program is executed to read the user's password and output the password to the standard output. If the SUDO_ASKPASS
environment variable is set, it specifies the path to the helper program. Otherwise, the value specified by the askpass
option in sudoers(5) is used.
I wouldn't recommend having the password available in any way to your web server processes though so you'd want to use the sudoers file.