SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Mar 2009
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Error Handling for SSH Connection

    Hello
    I'm trying to figure out how to handle exceptions brought up by starting an SSH connection that fails.

    For example, I have this code

    Code:
    $arrConnInfo.each do |strConnInfo|
      strConnInfo = strConnInfo.split(",")
      # Load connection variables
      strHostName = strConnInfo[0]
      strUserName = strConnInfo[1]
      strUserPwd = strConnInfo[2]
    
      begin
        Net::SSH.start( strHostName, strUserName, strUserPwd ) do |session|
          shell = session.shell.sync
          $a = LinuxSystem.new(shell)
        end
      rescue SocketError
        puts "Host name cannot be resolved."
        break
      end
    
      #work with SSH connection here if connection is successful....
    
    end
    This is stripped down version of it, but basically, it tries to SSH to a Linux box given the connection information from the array in the beginning, and if it cannot connect successfully (therefore raising the SocketError exception, for example), I want it to exit out of the current block of code (the EACH block), so the next iteration of $arrConnInfo is read in and processed.

    Right now, if the SocketError exception is brought up, it hits break and the program stops. How can I code it so it will simply move on to the next iteration? I don't find much information on the break method, so are there any alternatives?

    Thanks!

  2. #2
    SitePoint Member
    Join Date
    Mar 2009
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So just doing some brainstorming, I figured its quite easy to add in a variable to help steer where the code goes.

    Code:
    $arrConnInfo.each do |strConnInfo|
      strConnInfo = strConnInfo.split(",")
      # Load connection variables
      strHostName = strConnInfo[0]
      strUserName = strConnInfo[1]
      strUserPwd = strConnInfo[2]
    
      begin
        Net::SSH.start( strHostName, strUserName, strUserPwd ) do |session|
          shell = session.shell.sync
          $a = LinuxSystem.new(shell)
        end
        strBypass = false
      rescue SocketError
        puts "Host name cannot be resolved."
        strBypass = true
      end
    
      if strBypass != true
        #work with SSH connection here if connection is successful....
      end
    
    end
    Not exactly the route I wanted to take, but for my implementation it will work. Are there other options I can learn from?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •