0

I wrote the script below to be able to connect to a remote server and get some data from the XML file. I added some error handling to be able to skip issues with some devices. For some reason whenever the script gets a 401 message back, it breaks the whole loop and I get the message "Could not properly read the csv file". I tried other ways of handling the exception and it would fail at other points. Any info on how to properly deal with this?

#!/usr/bin/python

import sys, re, csv, xmltodict
import requests, logging
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def version(ip, username, password):
    baseUrl = "https://" + ip
    session = requests.Session()
    session.verify = False
    session.timeout = 45

    print "Connecting to " + ip
    try:
        r = session.get(baseUrl + '/getxml?location=/Status', auth=(username, password))
        r.raise_for_status()
    except Exception as error:
        print err

    doc = xmltodict.parse(r.text)

    version  = str(doc['Status']['@version'])

def main():
    try:
        with open('list.csv', 'r') as file:
            reader = csv.DictReader(file)
            for row in reader:
                version(row['ip'], row['Username'], row['Password'])
    except Exception as error:
        print ValueError("Could not properly read the csv file \r")
        sys.exit(0)

if __name__ == "__main__":
   main()

1 Answer 1

1

The doc and version variables in def version are outside the try: catch: so when r is None due to exception, the next 2 operations also fail, raising some uncaught exception. Which surfaces in main. Can you try including doc and version within the try: catch: and see if it works.

A related suggestion: catch specific exceptions as this helps know more about why your code crashed. ex. Response.raise_for_status() raises requests.exceptions.HTTPError. Catch that, raise all other exceptions. xml might raise something else, catch that, instead of catching ALL.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought I had tried that, but I just redid it and it worked perfectly. 401 handling, no connection handling! thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.