Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a login prompt in Net::SFTP object in Ruby?

I'm trying to implement a Ruby script that would send an email notice if login prompt comes up when trying to logon to Net::SFTP. The point being that if a logon prompt comes up, there's something wrong with the logon scheme on the SFTP. The question is how do I capture this status in the object itself since the object doesn't actually get initialized unless there's a valid login. Hope this makes sense.

Here's the script I'm attempting:

 def logon 
    counter = 0
    begin
      counter += 1
      @@sftp = Net::SFTP.start('<address>', Rails.application.credentials[:username], password: Rails.application.credentials[:password] )
    rescue TimeOutError
      retry if counter <=3
      UserMailer.logon_error.deliver_now if counter == 3
    ensure     
      UserMailer.logon_alert.deliver_now 
    end
  end

So if try to create an instance in Rails console like @@sftp = Net::SFTP.start('moftp.mo.gov', Rails.application.credentials[:missouri_username], password: Rails.application.credentials[:missouri_password] )

and if there is a problem with password, I get the prompt:

User@sftp_address password:

I disguised the address's for privacy reasons.

like image 254
Demian Sims Avatar asked Oct 15 '25 20:10

Demian Sims


1 Answers

Net::SFTP uses Net::SSH behind the scenes. As it happens Net::SSH.start has an option :number_of_password_prompts, that tells Net::SSH how many password prompts to show before it issues an exception. If you set it to zero, Net::SSH will fail with Net::SSH::AuthenticationFailed if the password is missing or invalid.

:number_of_password_prompts => Number of prompts for the password authentication method defaults to 3 set to 0 to disable prompt for password auth method.

So, you could do:

begin
  Net::SSH.start(host, user, password: pass, number_of_password_prompts: 0)
rescue Net::SSH::AuthenticationFailed
  # Do something
end
like image 122
Casper Avatar answered Oct 18 '25 14:10

Casper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!