ruby on rails ssh connection check validity
-
19-06-2021 - |
Вопрос
I'm making an ssh connection in my controller and displaying a view if the connection is established sucessfully. I need my action to redirect to 'denied_access' view if the connection is not established Here is my view where use enters his details:
<%= form_for :check_validity, :method => "get", :url => {:action => "check_validity"} do |f| %>
//enters user name and password here and submits
<% end%>
the check validity action in controller:
def check_validity
@USER = params[:check_validity][:username]
@PASS = params[:check_validity][:password]
@DOMAIN = params[:check_validity][:domain]
@HOST = 'hostname'
Net::SSH.start( @HOST, @USER, :password => @PASS ) do|ssh|
@result = ssh.exec!("/lclapps/oppen/http/ldap-group-list-2.4.3.py #{@DOMAIN} #{@USER} #{@PASS}")
end
respond_to do |format|
if(@result =~ /Informatica Developer/)
format.html{redirect_to display_command_list_path({:username => @USER})}
else
format.html{redirect_to denied_access_path}
end
end
end
Here the connection is established and is checking for Informatica Developer string in the resutl and redirecting to display_command_list_path
. But i want to check whether the connection is established or not even before checking this string and redirect to denied_access_path if the connection is not established.
How can i do that?
Решение
When attempting to connect with Net::SSH.start
you will get a Net::SSH::AuthenticationFailed
exception if the credentials are invalid.
begin
Net::SSH.start( @HOST, @USER, :password => @PASS ) do |ssh|
# ...
end
rescue Net::SSH::AuthenticationFailed => e
# redirect to denied_access_path
end
# your respond_to block ...
I should also mention, if the @HOST
is bad, it will raise a SocketError
. You could add a second rescue to the above code for that.