简体   繁体   English

如何在Ruby中使用net-ssh sudo su

[英]How to net-ssh sudo su in Ruby

I'm trying to figure out how to a send chain of multiple net-ssh commands after a sudo su - #{su_user} in Ruby. 我试图弄清楚如何在Ruby中使用sudo su - #{su_user}之后发送多个net-ssh命令的链。

My current code is below, and hangs with the sudo su command, even after the send_data "#{password}\\n" . 我的当前代码如下所示,即使在send_data "#{password}\\n"之后,也会挂起sudo su命令。

Meanwhile, on the system, a manual execution of sudo su - admin2 does not require a password entry. 同时,在系统上,手动执行sudo su - admin2不需要输入密码。

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

sudo supports the -c option, which passes a command to the sub-shell. sudo支持-c选项,它将命令传递给子shell。 Here are some of the sudo flags that might be useful to you: 以下是一些可能对您有用的sudo标志:

-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'll execute the commands ls and date as someuser . 所以,使用类似sudo su someuser -c 'ls;date' ,你将执行命令lsdate作为someuser Give it a try at the command-line on that host to get a feel for what you can do, then apply it to your SSH session. 尝试在该主机上的命令行中了解您可以执行的操作,然后将其应用于SSH会话。

See man sudo for more information. 有关更多信息,请参阅man sudo

Also, just as a coding tip, you can reduce: 此外,作为编码提示,您可以减少:

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

to: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM