get the information from the remote system using sudo command by using net::ssh in ruby

635 views Asked by At

I have a situation as i have to login to remote system and get the their hardware information. I logged in to their system i have used ssh for this i am using net-ssh gem. here is my code where i logged into and get the info

Net::SSH.start('host','user', :password => 'xxxxxx') do |ssh|
    ssh.exec!("echo 'xxxxxx' | sudo -S dmidecode -s system-serial-number")
end 

for getting the information I have used sudo -S dmidecode -s system-serial-number command it is giving the output with password for user as password for user 1.0.0 how can i remove that message?

Ihave refer this link but i also implemented it but it will taking to much time for loading how is their any other way to do this?

    result = nil
    session.exec!("sudo -S dmidecode -s system-serial-number") do |channel, stream, data|
    if data =~ /^\[sudo\] password for user:/
        channel.send_data 'your_sudo_password'
    else
        result << data
    end
    result

d

2

There are 2 answers

0
Casper On

Not exactly sure what the problem is, but perhaps you want to try and use the -p switch to change the password prompt to an empty string:

ssh.exec!("echo 'xxxxxx' | sudo -p '' -S dmidecode -s system-serial-number")
-p  The -p (prompt) option allows you to override the default password
    prompt and use a custom one.
1
kernelsmith On

sudo intentionally tries to prevent this to increase security. The ideal solution is to add a NOPASSWD option in the sudoers file, for the commands you need, to the username being used to create the ssh connection. e.g.: THESSHUSER ALL = NOPASSWD: dmidecode, system-serial-number

However, replace the commands w/their full absolute paths. Also, don't just give the ssh user NOPASSWD for all commands, restrict it to the commands you want to run, otherwise you are lowering the system's security. The sudoers file is usually in /etc/sudoers and is edited w/a special command on many machines, that command is visudo, which you must run as root (i.e. with sudo ;). Once you have edited the sudoers file you can run these commands w/o being prompted for a password.