Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Xosmond
Forked from ainoya/remote_sudo.rb
Created December 8, 2017 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xosmond/8fbe25be46bb4bfae060c3755730086d to your computer and use it in GitHub Desktop.
Save Xosmond/8fbe25be46bb4bfae060c3755730086d to your computer and use it in GitHub Desktop.
Execute remote sudo command with net-ssh
#!/usr/bin/env ruby
require 'net/ssh'
require 'highline/import'
def get_password
ask( "Enter Password: " ) {|q| q.echo = '*'}
end
def remote_sudo host, ssh_user, command, opts={}
ssh = Net::SSH.start(host, ssh_user, opts)
sudo_prompt = "Enter Password: "
sudo_header = "sudo -p '#{sudo_prompt}'"
sudo_command = "#{sudo_header} #{command}"
ssh.exec!(sudo_command) do |ch, stream, data|
if data =~ /#{sudo_prompt}/
ch.send_data get_password + "\n"
else
puts "[remote exec][#{host}] : #{data}"
end
end
end
remote_sudo "localhost", "ssh-sudoable-username", "sudo-command"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment