在 Ruby on Rails 应用程序中执行 sudo 命令
我正在尝试从 Ruby on Rails 应用程序执行这样的命令:
sudo服务squid3重新启动
如果我用这段代码尝试:
output = ´sudo service squid3 retsart´
它不起作用,在控制台中我看到linux询问密码。 如何使用此命令传递密码?或者其他建议...
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:
output = ´sudo service squid3 retsart´
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将以下行添加到您的 sudoers 文件 (/etc/sudoers)
这基本上会让rails_user 用户以 sudo 的身份执行服务命令,并且系统不会要求您输入密码。
rails_user 应该替换为您运行 Rails 进程的任何用户。您还应该确保
/etc/sudoers 中不存在该内容。如果没有,您将无法从脚本中使用 sudo。
You can add the following line to your sudoers file (/etc/sudoers)
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
is not present in your /etc/sudoers. If not you won't be able use sudo from a script.
如果您的系统上可用,您可以尝试 sudo -S 标志(检查 man):
这意味着密码将是明确的,因此您可以将需要执行任务的用户添加到 sudoers(这会产生另一个安全问题)方式)。
You can try the sudo -S flag if available on you system (check man):
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).
您的
sudo
有-A
开关吗?我不建议以任何方式让您的网络服务器进程使用密码,因此您需要使用 sudoers 文件。
Does your
sudo
have a-A
switch?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.
您可以使用 expect 方法 来捕获密码提示并发送密码。但是,最好使用 /etc/sudoers 中的 NOPASSWD 选项允许 Rails 用户无需密码即可访问服务命令。
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.