Running the sudo command in a Ruby on Rails application

I am trying to execute a command like this from a Ruby on Rails application:

sudo service squid3 restart

If I try with this code:

output = ยดsudo service squid3 retsartยด 

This does not work, in the console I see linux asking for a password. How can I pass the password with this command? Or other suggestions ...

+3
source share
4 answers

You can try the sudo -S flag if it is available on your system (check man):

 echo secretPasswd | sudo -S service squid3 restart 

This means that the password will be cleared so that you can add the user who must complete the task for sudoers (which creates, by the way, another security problem).

+3
source

You can add the following line to the sudoers file (/ etc / sudoers)

 rails_user ALL=(root) NOPASSWD:/usr/sbin/service 

Basically, this will allow the user rails_user to execute a utility command as sudo, and the system will not ask you to enter a password.

rails_user should be replaced by any user you work with in the rails process. And you must also make sure that

 Defaults requiretty 

not in your / etc / sudoers. If not, you cannot use sudo from the script.

+6
source

You can use the wait method to catch the password request and send the password. However, it would be better to let your Rails user access the service command without a password using the NOPASSWD option in / etc / sudoers.

0
source

Does your sudo a -A switch?

-A
Usually, if sudo requires a password, it will read it from the current terminal. If the -A (askpass) parameter is specified, a helper program is run to read the user's password and output the password to standard output. If the environment variable SUDO_ASKPASS , it indicates the path to the helper program. Otherwise, the value specified by the askpass parameter in sudoers (5) is used .

I would not recommend that the password have any way access to your web server processes, so you want to use the sudoers file.

0
source

Source: https://habr.com/ru/post/1383085/


All Articles