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
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(): try: line=i.strip() ls =line.split(",") p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) p.connect("%s"%ls,port =22, username = "%s"%ls, password="%s"%ls) stdin, stdout, stderr = p.exec_command("uname -a") opt = stdout.readlines() opt ="".join(opt) temp=open("%s.txt"%ls,"w") temp.write(opt) temp.close() except Exception as error: print(error) cred.close()
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.