1

Here's how at the moment I send commands to a remote server:

Net::SSH.start("1.2.3.4", keys: ["~/.ssh/id_rsa.pub"]) do |ssh|
  ssh.exec!(cmd_item)
end

How would I execute a command which requires root, that is "sudo apt-get install for example" which having me to type in the password each time?

2 Answers2

0

You need to know the root password for the remote machine. If that is known, the rest should be possible this way:

Net::SSH.start("1.2.3.4", keys: ["~/.ssh/id_rsa.pub"]) do |ssh|
   if not cmd_item["sudo "].nil? # if cmd_item string requires sudo access
       # sudo yourcommand  =>  echo -e "RemoteRootPassword\n" | sudo -S yourcommand
       cmd_item = "echo -e \"RemoteRootPassword\n\" | " + cmd_item.gsub(/sudo/, "sudo -S")
       ssh.exec!(cmd_item)
   else
       ssh.exec!(cmd_item)
   end
end

For some reference, you can check this question on how to use sudo with password as parameter.

Hope it helps : )

Community
  • 1
  • 1
Harsh Trivedi
  • 1,594
  • 14
  • 27
0

If you have root privileges on the remote server, I would set up sudoers to allow the user you use for ssh run passwordless sudo. You can be really specific about the commands you want to allow without password. In terms of security your ssh key should provide a better level of authentication than a password anyway.

If you not control the server and it would be a hassle to ask the admin to allow you to sudo without password, the Net::SSH documentation gives a neat example of how you can respond to the password prompt:

Net::SSH.start("host", "user") do |ssh|
  ssh.exec! "cp /some/file /another/location"
  hostname = ssh.exec!("hostname")

  ssh.open_channel do |ch|
    ch.exec "sudo -p 'sudo password: ' ls" do |ch, success|
      abort "could not execute sudo ls" unless success

      ch.on_data do |ch, data|
        print data
        if data =~ /sudo password: /
          ch.send_data("password\n")
        end
      end
    end
  end

  ssh.loop
end