Net :: SSH:你必须有一个TTY才能运行sudo

时间:2017-01-27 08:08:09

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

使用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:抱歉,你必须有一个tty来运行sudo \ n”

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

sudo -iu admin /folder/script.sh

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

如何使用TTY在Ruby脚本中运行此sudo命令?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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中的结果不同