Skip to content

Instantly share code, notes, and snippets.

@jjam3774
Last active March 12, 2019 14:03
Show Gist options
  • Save jjam3774/ab7dbcaba28881ba8cd2 to your computer and use it in GitHub Desktop.
Save jjam3774/ab7dbcaba28881ba8cd2 to your computer and use it in GitHub Desktop.
net-ssh using sudo pty sessions and regular session
#!/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