简体   繁体   English

Sudo via net :: ssh in ruby

[英]Sudo via net::ssh in ruby

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? 我如何执行一个需要root的命令,即“sudo apt-get install例如”让我每次都输入密码?

You need to know the root password for the remote machine. 您需要知道远程计算机的root密码。 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. 对于一些参考,您可以检查如何为参数使用sudo与密码提示问题。

Hope it helps : ) 希望能帮助到你 : )

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. 如果您在远程服务器上拥有root权限,我会设置sudoers以允许您用于ssh的用户运行无密码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. 在安全性方面,您的ssh密钥应提供比密码更好的身份验证级别。

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: 如果您不控制服务器并且要求管理员允许您在没有密码的情况下sudo将是一件麻烦事, Net :: SSH文档提供了一个如何响应密码提示的简洁示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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