Execute a Sudo Command in Ruby on Rails App

Execute a sudo command in Ruby on Rails app

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).

execute 'sudo su' command in rake task

You have several problems.

First, the Kernel#exec method won't return. See the API description:

Replaces the current process by running the given external command.

Second, it's really weird to execute sudo from Ruby. Could you simply execute sudo rake db:some_db_task?

UPDATED

Third, Kernel#exec won't return, but Kernel#system will. If you really want to sudo in your rake script, you need to use Kernel#system and execute sudo in every command. Ex:

   system 'sudo /etc/init.d/mysql stop'
system 'sudo /etc/init.d/mysql start'

system 'sudo su' doesn't work. It will start a shell with root user, and when you leave the shell, the Ruby process won't gain root permission.

How do I run commands as root from Rails?

You need to do #2.

Start your application as root, and you will be able to do all operations as root.

Writing code to run as a daemon would work also, but it's harder to debug.

In either case you have to protect against hacking attempts via unauthorized access. One slip and your system would be compromised.

Cap invoke and sudo

Found it - cap invoke COMMAND="command that requires sudo" SUDO=1

Capistrano executes a command with sudo although it is turned off

You're explicitly running a command in sudo: execute :sudo, 'whoami', why are you surprised that it uses sudo?

As explained in the documentation that you quoted, setting the :use_sudo option to false will tell Capistrano not to use sudo when doing certain operations. If you execute sudo whoami though it's not going to modify your command.



Related Topics



Leave a reply



Submit