Using Ruby to send commands over SSH
Doing a lot of work on remote Linux servers lately, lots of login in over SSH running commands logging out.
So wrote this simple script to use Ruby to send a single command or a file of commands to a Linux server over SSH. Needs some error trapping etc but functional at the moment.
It requires the Ruby Gem net-ssh installed.
#!/usr/bin/ruby
require 'rubygems'
require 'net/ssh'
require 'optparse'
opts = OptionParser.new
opts.on("-h HOSTNAME", "--hostname NAME", String, "Hostname of Server") { |v| @hostname = v }
opts.on("-u SSH USERNAME", "--username SSH USERNAME", String, "SSH Username of Server") { |v| @username = v }
opts.on("-p SSH PASSWORD", "--password SSH PASSWORD", String, "SSH Password of Server") { |v| @password = v }
opts.on("-c SHELL_COMMAND", "--command SHELL_COMMAND", String, "Shell Command to Execute") { |v| @cmd = v }
opts.on("-f FILE_COMMAND", "--command FILE_COMMAND", String, "File containing shell Commands to Execute") { |v| @fileCmd = v }
begin
opts.parse!(ARGV)
rescue OptionParser::ParseError => e
puts e
end
raise OptionParser::MissingArgument, "Hostname [-h]" if @hostname.nil?
raise OptionParser::MissingArgument, "SSH Username [-u]" if @username.nil?
raise OptionParser::MissingArgument, "SSH Password [-p]" if @password.nil?
raise OptionParser::MissingArgument, "Command to Execute [-c/-f]" if @cmd.nil? and @fileCmd.nil?
begin
ssh = Net::SSH.start(@hostname, @username, :password => @password)
if @cmd != nil then
ssh.exec!(@cmd) do |ch, stream, data|
if stream == :stderr
puts "ERROR: #{data}"
else
puts data
end
end
else
puts "Processing file #{@fileCmd}"
file = File.new(@fileCmd, "r")
file.each {|line|
ssh.exec!(line) do |ch, stream, data|
if stream == :stderr
puts "ERROR: #{data}"
else
puts data
end
end
}
file.close
end
ssh.close
rescue Exception => e
puts "Unable to connect to #{@hostname} using #{@username}/#{@password}"
puts e
end
Doodle's Geek Monkey by Alastair Montgomery