Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a remote command via ssh, using Ruby, improved syntax?

Tags:

ssh

ruby

Currently I'm calling a remote script using the backtick method, it works, but it feels wrong and nasty...

`ssh user@host $(echo "~/bin/command \\\"#{parameter}\\\"")`

Can someone give me a better way of expressing this?

Many thanks.

like image 683
ocodo Avatar asked Oct 23 '25 02:10

ocodo


2 Answers

I would make it a little pretty, if that is what you are after:

#!/usr/bin/env ruby
# encoding: utf-8

home    = "/path/to/users/home/on/remote"
binary  = File.join(home, "bin", "command")
command = "#{binary} '#{parameter}'"
puts `ssh user@host #{command}`

Otherwise, you can use the net-ssh library, and do something like this:

#!/usr/bin/env ruby
# encoding: utf-8

require 'net/ssh'
Net::SSH.start('host', 'user', :password => "<your-password>") do
  home    = "/path/to/users/home/on/remote"
  binary  = File.join(home, "bin", "command")
  command = "#{binary} '#{parameter}'"
  output = ssh.exec!(command)
  puts output
end

There are, obviously, automated ways of capturing remote user's home directory path, but I skipped that part.

like image 113
Stoic Avatar answered Oct 25 '25 17:10

Stoic


Use net-ssh. It's just a wrapper.

require 'net/ssh'

Net::SSH.start('host', 'user', :password => "password") do |ssh|
  # capture all stderr and stdout output from a remote process
  output = ssh.exec!("~/bin/command '#{parameter}'")
end

puts output
like image 30
NARKOZ Avatar answered Oct 25 '25 17:10

NARKOZ