Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problem in skiping a line in the text file

I have a code which takes backup from my cisco switches. It reads a text file containing switches’ IPs line by line, connect to each IP and takes backup from that switch. Here is the code:

import sys
import time
import paramiko 
import os
import cmd
import datetime

now = datetime.datetime.now()
user = input("Enter username:")
password = input("Enter Paswd:")
enable_password = input("Enter enable pswd:")
port=22
f0 = open('myswitches.txt')
for ip in f0.readlines():
       ip = ip.strip()
       filename_prefix ='/Users/apple/Documents' + ip 
       ssh = paramiko.SSHClient()
       ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh.connect(ip,port, user, password, look_for_keys=False)
       chan = ssh.invoke_shell()
       time.sleep(2)
       chan.send('enable\n')
       chan.send(enable_password +'\n')
       time.sleep(1)
       chan.send('term len 0\n')
       time.sleep(1)
       chan.send('sh run\n')
       time.sleep(20)
       output = chan.recv(999999)
       filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip,now.year,now.month,now.day,now.hour,now.minute,now.second)
       f1 = open(filename, 'a')
       f1.write(output.decode("utf-8") )
       f1.close()
       ssh.close() 
       f0.close()

The problem is that if the credentials of a switch is different, I receive this error and the program terminates. Here is the error:

paramiko.ssh_exception.AuthenticationException: Authentication failed.

How can I change this code so that in case the credentials of a switch is different, skip that line of the text file and try the next switch.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use try-except clause, like this:

from paramiko.ssh_exception import AuthenticationException

for ip in f0.readlines():
    try:
        ip = ip.strip()
        # The rest of the code
        # ...
    except AuthenticationException:
        print("Skipped")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading