Create a gist now

Instantly share code, notes, and snippets.

"ssh and su" automation sample with Ruby and except
# -*- coding: utf-8 -*-
require 'pty'
require 'expect'
=begin
ssh & su example for expect.rb
variables
c : config hash
cmd : command what you want to exec
(you can recieve with Highline.ask)
=end
def exec_as_root( cmd, c )
$expect_verbose = true
host = c['prompt_host']
PTY.spawn( ssh_cmdline( c ) ) { |r, w|
w.sync = true
# store host info ?
r.expect( /\(yes\/no\)\?/, 3 ) { |s|
w.puts "yes"
}
r.expect( /password: $/ ) {
w.puts c['pass']
sleep 2
}
r.expect( "#c['user']@#{host}" ) {
w.puts "su"
}
r.expect( /^Password: $/ ) {
w.puts c['root_pass']
}
r.expect( "root@#{host}" ) {
w.puts cmd
}
r.expect( "root@#{host}" ) {
w.puts "exit"
}
}
end
def ssh_cmdline( c )
return "ssh -p #{c['port']} #{c['user']}@#{c['host']}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment