1

I have problem with running the sudo command over a SSH connection using Ruby:

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

The result I see next: "sudo: sorry, you must have a tty to run sudo\n"

But when I run this command:

sudo -iu admin /folder/script.sh

in PUTTY with connect to server 'myserver.com' with password 'pass'. In this case the sudo command runs successfully and completes.

How I can run this sudo command in a Ruby script with TTY?

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Misha1991
  • 63
  • 1
  • 8
  • I think you can request a terminal if you want with [`request_pty`](https://net-ssh.github.io/ssh/v2/api/classes/Net/SSH/Connection/Channel.html#M000055) – tadman Jan 27 '17 at 08:22
  • I don't think this is an exact duplicate: In that question, SSH hangs. In this question, the result is "You must have a TTY to run sudo". – Wayne Conrad Jan 27 '17 at 13:06

2 Answers2

1

This worked for me:

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
Fer
  • 3,247
  • 1
  • 22
  • 33
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

Strange thing. When I run this code it is complete without errors but in fact not successful. Result in PUTTY and in Ruby is different

Misha1991
  • 63
  • 1
  • 8