Like net-ssh sudo su in Ruby

I am trying to figure out how the chain of sending multiple net-ssh commands after sudo su - #{su_user} in Ruby.

My current code is below and hangs with the sudo su command, even after send_data "#{password}\n" .

Meanwhile, in the system, manual execution of sudo su - admin2 does not require a password.

Any help would be appreciated!


 require 'rubygems' require 'net/ssh' host = 'hostA' user = 'admin' password = 'hostA_pwd' su_user = 'Admin2' Net::SSH.start(host, user, :password => password) do |ssh| ssh.open_channel do |channel| channel.request_pty do |c, success| raise "could not request pty" unless success channel.exec "pwd; whoami; sudo su - #{su_user} ; pwd ; whoami" channel.on_data do |c_, data| if data =~ /\[sudo\]/ || data =~ /Password/i channel.send_data "#{password}\n" else result << data end end puts result end end ssh.loop end 
+6
source share
1 answer

sudo supports the -c option, which passes the command to the sub-shell. Here are some of the sudo flags you might find useful:

 -c, --command=COMMAND pass a single COMMAND to the shell with -c --session-command=COMMAND pass a single COMMAND to the shell with -c and do not create a new session -m, --preserve-environment do not reset environment variables -s, --shell=SHELL run SHELL if /etc/shells allows it 

So, using something like sudo su someuser -c 'ls;date' , you will run the ls and date someuser as someuser . Try a command line on this host to understand what you can do, and then apply it to an SSH session.

See man sudo more details.

As well as a hint for coding, you can reduce:

 if data =~ /\[sudo\]/ || data =~ /Password/i 

in

 if (data[/\[sudo\]|Password/i]) 
+3
source

All Articles