Last active
March 12, 2019 14:03
-
-
Save jjam3774/ab7dbcaba28881ba8cd2 to your computer and use it in GitHub Desktop.
net-ssh using sudo pty sessions and regular session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'rubygems' | |
require 'net/ssh' | |
user = "vagrant" | |
pass = "vagrant" | |
host = "192.168.1.120" | |
### | |
# Commands without elevated privileges | |
### | |
commands = %Q{ | |
hostname | |
uptime | |
id | |
} | |
### | |
# Commands that are ran with elevated privileges | |
### | |
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 | |
} | |
### | |
# All of the magic is done here for non-elevated priv commands | |
# This all that is needed if logging on as root is allowed | |
### | |
Net::SSH.start( host, user, :password => pass, :paranoid => false ){|ssh| | |
begin | |
########################################################### | |
# Executing non-priv commands | |
########################################################### | |
puts "========================\nDoing non-priv commands\n========================\n".upcase | |
result = ssh.exec!(commands) | |
########################################################### | |
# 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 | |
} | |
} | |
puts result.upcase | |
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