Welcome to this tutorial that will describe how to SSH to a Linux, Windows, etc. server using Ruby. This post will give you a complete code example to get you up and running right away! The code below will connect to the server specific and run the ls -al command. Be sure to change the values in the example of @hostname, @username, @password, and @cmd to your own values.
Ruby Syntax
require 'rubygems' require 'net/ssh' @hostname = "localhost" @username = "root" @password = "password" @cmd = "ls -al" begin ssh = Net::SSH.start(@hostname, @username, :password => @password) res = ssh.exec!(@cmd) ssh.close puts res rescue puts "Unable to connect to #{@hostname} using #{@username}/#{@password}" end
Now we will expand on the first example by allowing you to specify the server connection information and the command to execute as command-line parameters. This will allow you to use the same script to connect to a variety of servers and execute any command without modifying the script over and over.
Ruby Syntax
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 } 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]" if @cmd.nil? begin ssh = Net::SSH.start(@hostname, @username, :password => @password) res = ssh.exec!(@cmd) ssh.close puts res rescue puts "Unable to connect to #{@hostname} using #{@username}/#{@password}" end
Example of how to execute the script
ruby script_name.rb -h localhost -u root -p password -c "ls -al"
As you can see, the hostname, username, password, and command are all parameters passed in to the script. All of these parameters are required, so if you forget one, it will spit out an error. Give it a try!
Excelent!!
Can you show me how to connect to windows sever?
it is giving me badfile descriptor error