title: Using pexpect to automate IP validations
body: <p>My end goal is to log into a switch, get the CDP neighbor details written to a file. parse out the IP addresses and run pings on the IP address and output that to a file. I've searched the forums and found nothing really pertaining to switches. Mainly servers, and I've adapted from there. But Now I am stuck. </p>
  
  <p>I get as far as getting logged into a switch and my login prompts seem to be written to a file but nothing else. </p>
  
  <p>Please excuse errors in the code. Also, the second try block is a work in progress. I am new to python and learning as I go. I am open to any and all critiques and suggestions. I want to know what I have done incorrectly, fix it, and build from there. </p>
  
  <p>Thanks in advance!</p>
  
  <pre><code>import pexpect
  import getpass
  import sys
  import re
  import os
  import time
  
  
  try:
      switch = raw_input("Host: ")
      un = raw_input("Username: ")
      pw = getpass.getpass("Password: ")
  
      options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
      prompt = "#"
  
  
      connection_string = ("ssh %s@%s %s" % (un,switch,options))
  
  
      child = pexpect.spawn(connection_string, timeout=5)
      file_output = open('switch_output.txt','wb+')
      child.logfile = file_output
      rva12 = "";
  
      child.expect(re.escape("password:"))
      time.sleep(1)
      child.sendline(pw)
      time.sleep(1)
      child.expect(prompt)
      time.sleep(1)
      child.sendline("no page")
      time.sleep(1)
      child.expect(prompt)
      child.sendline("show cdp nei det")
      time.sleep(1)
      child.expect(prompt)
      child.before
  
      file_output.close()
  
  except Exception as e:
      print("Failed on login")
      print(sys.exc_info()[0].__name__,
            os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
            sys.exc_info()[2].tb_lineno)
      print(e)
  
  
  try:
      f = open('switch_output.txt', 'r')
      pattern_one = re.compile('.*A\d\n|\:\s\d{2,}\.\d{2,}\.\d{1,}.\d{1,}?')
  
      for line in f:
          matches = []
  
          if pattern_one.search(line):
          matches.append(line.split(':', 1)[-1].strip())
  
          mp = re.compile('\d{2,}\.\d{2,}\.\d{1,}.\d{1,}')
  
          with open('MDF1.txt', 'wb+') as file:
              for match in matches:
                  if mp.search(match):
                      file.write(match+'\n')
                      file.close()
  
          for line in open('MDF1.txt','r'):
              child.expect(prompt)
              child.sendline('ping '+ line)
              time.sleep(10)
  
  
  except Exception as e:
      print(sys.exc_info()[0].__name__,
          os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
          sys.exc_info()[2].tb_lineno)
      print(e)
  </code></pre>