Python Try and Except Error Handling

In this script, we will see how we can implement error handling in python scripting. We will use the try and except method. Sometimes if there is an error in the script or in the remote device where you are trying to connect then the script will break and stop working.

Error handling using the try-and-except method deals with these kinds of situations. If you are using any particular python library, then check the documentation to see available exception errors.

Python Try and Except Error Handling

Python Try and Except Error Handling

Below is the script which we have used for error handling. Check out the link for email sending script in python. Full tutorial for python scripting for videos for storage admin.

import paramiko
p = paramiko.SSHClient()
cred = open("cred.csv","r")
for i in cred.readlines():
        ls =line.split(",")
        p.connect("%s"%ls[0],port =22, username = "%s"%ls[1], password="%s"%ls[2])
        stdin, stdout, stderr = p.exec_command("uname -a")
        opt = stdout.readlines()
        opt ="".join(opt)
    except Exception as error:

Watch the video for a full explanation and subscribe to the channel for more such videos.


The given example is simple, you can use this method in various scenarios to catch errors and save them into a log file for further checks. While using this method, the script will continue to run, even if the errors are critical.