Run the command 'sudo su' on the rake command

I am developing a Rails v2.3 application. and using MySQL v5.1 on an Ubuntu machine.

I have a rake task to stop and start the mysql database, for example the following:

namespace :db do task :some_db_task => :environment do ... exec 'sudo /etc/init.d/mysql stop' ... exec 'sudo /etc/init.d/mysql start' end end 

As you see above in the code, I used sudo to make sure the command is complete. However, because of this, sudo , when I run the rake task , I will be prompted for the root password , although the rake task will run successfully.

I want to avoid entering a password, so I thought I could run a shell command to switch to root user first and then stop / start MySQL, so I changed my code to the following:

 namespace :db do task :some_db_task => :environment do ... exec 'sudo su' exec '/etc/init.d/mysql stop' ... exec '/etc/init.d/mysql start' end end 

See, I added the sudo su command to start over. Now I run my rake command again , but by the way, the rake task starts before exec 'sudo su' , after which it stops , the rest of the codes do not even start. What for? How to get rid of it?

(As a rule, I do not want to enter the root password during the execution of the rake task to start and stop MySQL)

+4
source share
3 answers

You have a few issues.

First, the Kernel # exec method will not return. See API Description:

Replaces the current process by running the specified external command.

Secondly, it is very difficult to execute sudo from Ruby. Could you just do sudo rake db:some_db_task ?

UPDATED

Thirdly, Kernel#exec will not return, but Kernel#system will. If you really want sudo in your rake script, you need to use Kernel#system and execute sudo on every command. Example:

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

system 'sudo su' does not work. It will launch the shell with the root user, and when you leave the shell, the Ruby process will not gain root privileges.

+4
source

I would recommend creating shell aliases for these two commands instead. The Rake tasks in Rails are not really designed to perform specific system tasks.

Add these lines to your .bashrc to speed up start and stop.

 alias mysql_start = 'sudo /etc/init.d/mysql start' alias mysql_stop = 'sudo /etc/init.d/mysql stop' 

If you want to do this as a type of deployment, capistrano is better for working.

+1
source

I think you should use sudo for rake not for the user command (i.e. sudo rake db: some_db_task)? or try exec “sudo su” the first time, another executable without “sudo”, but I think rake can run exec every time for a new session, and sudo su was closed on the next exec.

Some link about this problem http://www.ruby-forum.com/topic/69967

0
source

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


All Articles