【问题标题】:Net::SSH: You must have a TTY to run sudo [duplicate]Net::SSH:您必须有一个 TTY 才能运行 sudo [重复]
【发布时间】:2017-01-27 08:08:08
【问题描述】:

我在使用 Ruby 通过 SSH 连接运行 sudo 命令时遇到问题:

require 'net/ssh'
Net::SSH.start("myserver.com", "login", :password => "pass")  do |ssh|
test = ssh.exec! 'sudo -iu admin /folder/script.sh'
puts test

接下来看到的结果:“sudo: sorry, you must have a tty to run sudo\n”

但是当我运行这个命令时:

sudo -iu admin /folder/script.sh

在 PUTTY 中,使用密码“pass”连接到服务器“myserver.com”。在这种情况下,sudo 命令运行成功并完成。

如何在带有 TTY 的 Ruby 脚本中运行这个 sudo 命令?

【问题讨论】:

  • 我想你可以通过request_pty申请终端
  • 我不认为这是完全重复的:在那个问题中,SSH 挂起。在这个问题中,结果是“You must have a TTY to run sudo”。

标签: ruby-on-rails ruby ssh putty tty


【解决方案1】:

这对我有用:

require 'net/ssh'
host = "your.host.com"
user = "user"
password = "your pass"

command = "ls"

Net::SSH.start(host, user, password) do |session|

  session.open_channel do |channel|
    channel.on_data do |ch, data|
      puts "data received: #{data}"
    end

    channel.request_pty do |ch, success|
      if success
        puts "pty successfully obtained"
        ch.exec(command)
      else
        puts "could not obtain pty"
      end
    end

  end

  session.loop
end

【讨论】:

    【解决方案2】:
    require 'net/ssh'
    
      cmd = 'sudo -iu admin /folder/script.sh'
    
      Net::SSH.start("myserver.com", "login", "pass")  do |ssh|
    
        ssh.open_channel do |channel|
          channel.request_pty
     channel.exec(cmd);
    
        end
      end
    

    奇怪的东西。当我运行此代码时,它是完整的,没有错误,但实际上并不成功。 PUTTY 和 Ruby 中的结果不同

    【讨论】:

    • AFAIK 你需要等待channel.exec(cmd) 停止。
    • 查看重复链接了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2022-10-15
    • 2015-06-29
    • 2022-01-01
    相关资源
    最近更新 更多