Skip to content

Instantly share code, notes, and snippets.

@jjam3774
Last active November 16, 2018 20:07
Show Gist options
  • Save jjam3774/d2138b18cc9f9316abfd to your computer and use it in GitHub Desktop.
Save jjam3774/d2138b18cc9f9316abfd to your computer and use it in GitHub Desktop.
NET-SSH example using sudo to execute admin commands
#!/usr/bin/ruby
require 'rubygems'
require 'net/ssh'
host = "192.168.1.120"
user = "vagrant"
pass = "vagrant"
sudo_com = %Q{
echo "#{pass}" | sudo -S id
[ -f /usr/bin/apt ] && sudo apt-get -y install apache2 || yum groupinstall -y "Web Server"
echo "UPTIME"
uptime
echo "BUILD:"
getconf LONG_BIT
echo "HOSTNAME"
hostname
sudo dmidecode -t bios
uptime
hostname
}
Net::SSH.start( host, user, :password => pass, :paranoid => false ){|ssh|
begin
###########################################################
# Executing priv commands with sudo
###########################################################
ssh.open_channel{ |channel|
channel.request_pty{|ch, success|
# This is needed to start a sudo session on remote system
if success
puts "========================\npty session successfully obtained\n========================".upcase
puts "========================\nExecuting priv commands\n========================".upcase
ch.exec(sudo_com){|i, data|
i.on_data{ |step, info|
print info.upcase
}
}
else
puts "could not obtain pty".upcase
end
}
}
rescue Net::SSH::HostKeyMismatch => e
puts "remembering new key: #{e.fingerprint}"
e.remember_host!
retry
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment