Python Forum
How to make the script ignore down devices.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make the script ignore down devices.
#1
Hello, I have a script that get the bkp config from devices listed on a file.
The script run ok until find a down node, when a down node is present on devices list the script stops and an error appear on the screen.

My goal is to make the script ignore the unresponsive device and run agains the next IP on the list.


My script is this:
*********************************************************************************************
import sys
import os
import cmd
import datetime
import paramiko
import time

from keyboard import press
from getpass import getpass
now = datetime.datetime.now()


username = "secret"
password = "secret"


#start FOR ...in
f = open('fortigate_list')
for ip in f.readlines():
ip = ip.strip()

filename_prefix ='bkp_fortigate_' + ip

SESSION = paramiko.SSHClient()
SESSION.set_missing_host_key_policy(paramiko.AutoAddPolicy())
SESSION.connect(ip,port=9922,
username=username,
password=password,
look_for_keys=False,
allow_agent=False)

DEVICE_ACCESS = SESSION.invoke_shell()
DEVICE_ACCESS.send(b'config system console\n')
time.sleep(1)
DEVICE_ACCESS.send(b'set output standard\n')
time.sleep(1)
DEVICE_ACCESS.send(b'end\n')
time.sleep(1)
DEVICE_ACCESS.send(b'show full-configuration\n')
time.sleep(10)
DEVICE_ACCESS.send(b'show system global\n')
time.sleep(1)
output = DEVICE_ACCESS.recv(9999999)

print output
filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)
ff = open(filename, 'a')
ff.write(output)
ff.close()


DEVICE_ACCESS.close()

print ip
f.close()
**********************************************************************************************
The error is:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Traceback (most recent call last):
File "ignoraerro", line 30, in <module>
allow_agent=False)
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 349, in connect
retry_on_signal(lambda: sock.connect(addr))
File "/usr/local/lib/python2.7/dist-packages/paramiko/util.py", line 283, in retry_on_signal
return function()
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 349, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 11] Resource temporarily unavailable
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Can you please help me to improve the script so it can skip the error and keep running the script against the next devices?
Reply
#2
Read about exceptions. It is really common for python to raise an exception when something the program is trying to do fails. Programs should be written to capture these exceptions and perform a corrective action.

Your program is getting a "socket.error" exception. This is happening in line 30 of your program.

30 allow_agent=False)

But I'm pretty sure it is the SESSION.connect that causes the error.

To prevent this from crashing your program you can surround dangerous command with tr/except

try:
    SESSION.connect(ip,port=9922,
        username=username,
        password=password,
        look_for_keys=False,
        allow_agent=False)
    # other code you would run if connection was successful

except socket.error:
    print('Connection failed for', ip, port)
The try tells python "I am going to be watching for you to mess up". The "except sock.error" says "I know what to do if someone raised a sock.error exception". The code below the "except sock.error" only gets executed when an exception occurs. Your exception handler is easy to write because all you want to do is move along to the next device. I added a print command to notify you that a device did not accept your connect request.
Reply
#3
Dear mr Deanhystad, thank you so much for you help.


I placed the try as you suggest, I now that problably it due to a very simple mistake in my code,
but is my first try to deploy a script, so if you can please help me again...

here is my code

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

from keyboard import press
from getpass import getpass
now = datetime.datetime.now()


username = "*"
password = "*"


#start FOR ...in
f = open('fortigate_list')
for ip in f.readlines():
        ip = ip.strip()
        #prefix files for backup
        filename_prefix ='bkp_fortigate_' + ip

        SESSION = paramiko.SSHClient()
        SESSION.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            SESSION.connect(ip,port=9922,
                    username=username,
                    password=password,
                    look_for_keys=False,
                    allow_agent=False)

            DEVICE_ACCESS = SESSION.invoke_shell()
            DEVICE_ACCESS.send(b'config system console\n')
            time.sleep(1)
            DEVICE_ACCESS.send(b'set output standard\n')
            time.sleep(1)
            DEVICE_ACCESS.send(b'end\n')
            time.sleep(1)
            time.sleep(1)
            DEVICE_ACCESS.send(b'show full-configuration\n')
            time.sleep(10)
            DEVICE_ACCESS.send(b'show system global\n')
            time.sleep(1)
            output = DEVICE_ACCESS.recv(9999999)


            print output
            filename = "%s_%.2i-%.2i-%i_%.2i-%.2i-%.2i" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)
            ff = open(filename, 'a')
            ff.write(output)
            ff.close()
            print ip
            f.close()
        #close ssh session

        except socket.error:
            print('Connection failed for', ip, port)

            DEVICE_ACCESS.close()
Error:
Traceback (most recent call last): File "4", line 57, in <module> except socket.error: NameError: name 'socket' is not defined
Reply
#4
Sorry about that. It is looking for a package named socket. You are using socket indirectly through paramiko. I think socket.error is being depreciated and you are supposed to use OSError. You can also ignore the exception type and catch them all. Though generally frowned upon it may be a good fit for your problem.
try:
    # Code goes here
except Exception as ex:
    print('An exception occurred.  Details', ex)
You probably want to call DEVICE_ACCESS.close() at the end of the program. Right now it is part of the exception handler. Watch that indentation!
Reply
#5
Thank you, it is working perfect now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Make entire script run again every 45 mo NDillard 0 317 Jan-23-2024, 09:40 PM
Last Post: NDillard
  Trying to make a board with turtle, nothing happens when running script Quascia 3 657 Nov-01-2023, 03:11 PM
Last Post: deanhystad
  Make console show after script was built with Pyinstaller --NOCONSOLE? H84Gabor 0 1,208 May-05-2022, 12:32 PM
Last Post: H84Gabor
  Ignore WakeWord after it's said Extra 2 1,174 Apr-01-2022, 12:32 AM
Last Post: Extra
  How to ignore "Retrying (Retry(total=2, connect=2, read=5, redirect=5, status=None))" const 3 2,694 Mar-26-2022, 08:55 AM
Last Post: ndc85430
  Make my py script work only on 1 compter tomtom 14 3,823 Feb-20-2022, 06:19 PM
Last Post: DPaul
  Make the script read from any directory falahfakhri 2 2,159 Jun-15-2020, 02:18 PM
Last Post: falahfakhri
  Ignore first few letters of a line when reading file. ShakeyPakey 16 6,341 May-30-2020, 02:17 PM
Last Post: BitPythoner
  How to ignore empty columns from DB? Winfried 1 2,274 May-15-2020, 08:35 PM
Last Post: menator01
  Best way to iterate through output to get the status of devices idkwhatimdoing 0 1,445 Apr-22-2020, 02:05 AM
Last Post: idkwhatimdoing

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020