Search code examples
rubynet-ssh

Ruby/NetSSH try username and password only once?


Is there a way to fail immediately after trying a username and password sequence with Net::SSH.start()? I am looking to test to see if credentials work then stop afterwards, here is the code that I have

output = 0
Net::SSH.start('host', 'user', :password => "pass") do |ssh|
   output = ssh.exec! 'echo "1"'
end
puts output

Solution

  • This should restrict authentication to password only, and no prompts or retries:

    Net::SSH.start('host', 'user',  
                   :password     => 'pass', 
                   :auth_methods => [ 'password' ],
                   :number_of_password_prompts => 0)
    

    :auth_methods restricts SSH to only try those authentication methods which are listed in the array. In this case we only want to try password authentication.

    :number_of_password_prompts only works with the password auth method, and if you set it to zero it will never prompt for a password, even if the authentication fails.