简体   繁体   中英

How to run the commands in Ruby as a root

I am using net/ssh gem in Ruby. By the following code I can enter into the server from my local machine. But I want to execute the commands on the server by entering as a ROOT . Normally, I enter into the server as a ROOT by the command

sudo su -

Following is my code.

require 'rubygems'
require 'net/ssh'

list_of_servers = "servers.csv"
username="XYZ"
IO.readlines(list_of_servers).each do |line|
        line.chomp!
        server = line.split(',')[0]
        password = line.split(',')[1]
puts "---- " + server

Net::SSH.start(server, username, :password => password,:verbose => Logger::DEBUG) do |ssh|

result=ssh.exec!("sudo su -")
puts result
end
end

Output I get after entering into server.

D, [2015-11-21T21:48:26.005576 #56654] DEBUG -- io[3fce29cc9548]: received packet nr 15 type 97 len 12
I, [2015-11-21T21:48:26.005628 #56654]  INFO -- net.ssh.connection.session[3fce29ce9834]: channel_close: 0
D, [2015-11-21T21:48:26.005796 #56654] DEBUG -- io[3fce29cc9548]: queueing packet nr 11 type 97 len 28
sudo: no tty present and no askpass program specified

Note:

I can successfully log into the server from my local machine but I cannot run the ROOT command (sudo su -) .

You have to start tty for that

scenario = []
scenario << ""
scenario << "su" 

@session = Net::SSH.start(ip , user,
      :password => pass,
      :auth_methods => ['password'],
      :timeout => 10
    )



@session.open_channel do |channel|
  channel.request_pty do |ch, success|
    ch.send_channel_request("shell") do |shell, success|
      shell.on_data do |c, data|
        @output << data
      end
      scenario.each do |s|
         cmd = "#{s}\r\n"
         shell.send_data(cmd)
      end
    end
  end
end

According to man sudo , if you specify -S before the command, sudo takes the password from stdin .

I tried this both on a terminal and from ruby with success:

(insert your password, and the command you wish to run in the generic example below.)

echo "password" | sudo -S "command" 

works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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