Skip to content

Instantly share code, notes, and snippets.

@ainoya
Created June 13, 2013 00:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ainoya/5770350 to your computer and use it in GitHub Desktop.
Save ainoya/5770350 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