简体   繁体   English

Ruby Net / ssh脚本未关闭

[英]Ruby net/ssh script not closing

I have a ruby script where I'm using net/ssh to ssh into a server, sudo -s, su - user, run a script and answer the questions to that script. 我有一个ruby脚本,我在其中使用net / ssh将ssh SSH到服务器,sudo -s,su-用户,运行脚本并回答该脚本的问题。 So far I'm able to do everything, login, do all of the su/sudo stuff, run the script and answer its questions but the channel I create won't close and end the script, it seems. 到目前为止,我已经能够完成所有操作,登录,完成所有su / sudo内容,运行脚本并回答其问题,但是看来,我创建的通道不会关闭并结束脚本。 It all runs but then hangs after the script runs. 它全部运行,但是在脚本运行后挂起。 What am I doing wrong? 我究竟做错了什么? I'm a noob at ruby so I'm not totally sure what's going on. 我是ruby的菜鸟,所以我不太确定发生了什么。 Thanks for any help! 谢谢你的帮助!

Below is what I've got: 以下是我所拥有的:

Net::SSH.start("server01", 'user') do |ssh|
  ssh.open_channel do |channel|
    channel.on_request "exit-status" do |channel, data|
      $exit_status = data.read_long
    end

    channel.on_data do |channel, data|
      data
    end

    channel.request_pty do |channel, data|
      channel.send_data("sudo -s\n")
      channel.send_data("su - user2\n")
      sleep 0.5

      channel.send_data("/opt/scripts/test\n")
      sleep 10

      channel.send_data("answer1\n")
      sleep 5

      channel.send_data("answer2\n")
      sleep 5

      channel.send_data("answer3\n")
      sleep 10
    end

    channel.wait
    puts "SUCCESS" if $exit_status == 0
  end
end

Actually in testing you need to send exit\\n or else you will hang. 实际上,在测试中,您需要发送exit\\n ,否则将挂起。

so try adding it after your sleep (do you really need the sleep 10? ) 因此,请在睡眠后尝试添加它(您真的需要睡眠10吗?)

 channel.send_data("answer3\n")
 sleep 10
 channel..send_data("exit\n")

also sudo -u user2 -H /opt/scripts/test will make it so that you only have to exit the one shell. sudo -u user2 -H /opt/scripts/test也会使其生效,因此您只需要退出一个shell。 as your script as it stands starts 3 shells. 按照您的脚本原样启动3个shell。 1 when you login and request a PTY, one when you run the root shell (sudo -s), and then another when you su over to user2. 登录并请求PTY时返回1,运行根shell(sudo -s)时返回一个,而当用户切换到user2时返回另一个。

so the block would look something like this. 所以块看起来像这样

channel.request_pty do |channel, data|
  channel.send_data("sudo -u user2 -H /opt/scripts/test")
  sleep 10

  channel.send_data("answer1\n")
  sleep 5

  channel.send_data("answer2\n")
  sleep 5

  channel.send_data("answer3\n")
  sleep 10
  channel.send_data("exit\n")

end

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

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