简体   繁体   中英

SSH connect to a remote database server

I have a Rake task to stop a remote MySQL server like following:

   task :stop_mysql do

     #SSH connect to the remote db server first
     #how???

     #then, run the following command
     system 'sudo /etc/init.d/mysql stop'
   end

As you see above, now the database server is remote , I know the IP address of the database server.

How can I programmatically make ssh connection to the database server and run the command in the rake task above to stop MySQL?

PS the ssh configuration has been done (I mean the keys). Do not need to worry SSH configurations. I only need to know how the ruby code should be to make the SSH connection.

ssh can execute a single command instead of opening a new shell. This way, you can use system to execute your command on the remote host.

Try

system 'ssh user@host sudo /etc/init.d/mysql stop'

(It might require some escaping for the second arg)

Wrap it into a simple function and it's really handy:

def run( cmd )
  system "ssh user@host '#{cmd}' "
end

run( 'echo "aha coolness" >> test.txt' )
run( 'ls *.txt' )
run( 'cat test.txt' )

echo's something into a file test.txt runs ls remotely cat's the file remotely.

For your use case run('sudo /etc/init.d/mysql stop')

Have an identity file and .ssh/config setup and it doesn't require typing passwords...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM