From 29a5d0875daa29d76bc863bf661d8028441673b8 Mon Sep 17 00:00:00 2001
From: Kent Eitzmann <keitzmann@nebraska.edu>
Date: Mon, 10 Apr 2023 09:40:26 -0500
Subject: [PATCH] adding threading to findfails-mt.py

---
 findfails-mt.py | 143 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 143 insertions(+)
 create mode 100644 findfails-mt.py

diff --git a/findfails-mt.py b/findfails-mt.py
new file mode 100644
index 0000000..d869c1a
--- /dev/null
+++ b/findfails-mt.py
@@ -0,0 +1,143 @@
+from netmiko import (ConnectHandler,NetmikoTimeoutException)
+from getpass import getpass
+import requests
+import urllib3
+import re 
+import time
+import getpass
+from threading import Thread, currentThread, Lock
+from queue import Queue
+import datetime
+
+urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+
+#
+# This script will look to see which ports are in a "failed" state and try to reathenticate the port.
+#     
+#  2023-04-10 - Added Multi-threading support. Adapted from example found at 
+#  https://oznetnerd.com/2020/06/28/multithreading-with-python-netmiko/
+
+###########################################################################
+print(" 1 = UNL-City \n 2 = UNL-East \n 3 = UNO \n 4 = UNK \n Select Campus:")
+campus = input()
+print(f"Campus Selected: {campus}")
+print("----------------------------------")
+print("----------------------------------")
+print(" 1  = Find Failed ports \n Select Role:")
+role = input()
+if campus == "1":
+    file = [line.strip() for line in open("unlCitySwitches-cx.txt", 'r')]
+if campus == "2":
+    file = [line.strip() for line in open("unlEastSwitches-cx.txt", 'r')]
+if campus == "3":
+    file = [line.strip() for line in open("unoSwitches-cx.txt", 'r')]
+if campus == "4":
+    file = [line.strip() for line in open("unkSwitches-cx.txt", 'r')]
+    #print(file[])
+    #file.close()
+
+if role == "1":
+    policyrole = "Fail"
+##########################################################################
+print("Enter Username:")
+Ausername = input()
+print("Enter Password:")
+Apassword = getpass.getpass()
+creds = {"username": {Ausername}, "password": {Apassword}}
+
+# Threading setup
+# NUM_THREADS is number of concurrent connections you want.
+# (You can experiment with values)
+NUM_THREADS = 20 
+PRINT_LOCK = Lock()
+
+def main():
+
+    
+    start_time = datetime.datetime.now()
+
+    device_queue = Queue(maxsize=0)
+
+    # Loop through list of switch IP's, add to queue
+    for selectIP in file:
+        device_queue.put(selectIP)
+
+    # Pass the Queue and length to MultiThread function
+    numdev = len(file)
+    run_mt(mt_function=check_fail, q=device_queue, devs=numdev)
+
+    # Show how long script took
+    print("\nElapsed time: " + str(datetime.datetime.now() - start_time))
+
+def check_fail (q, kwargs):
+
+    while True:
+        
+        thread_name = currentThread().getName()
+
+        if q.empty():
+            mt_print(f"{thread_name}: Closing as there's no jobs left in the queue.")
+            return
+
+        ip_add = q.get()
+        print(f"Connecting to .. {ip_add}")
+
+        try:
+            net_connect = ConnectHandler(
+                        device_type="aruba_procurve",
+                        host=ip_add,
+                        username=Ausername,
+                        password=Apassword,
+            )
+
+
+            ###############################################################################
+            output = net_connect.send_command(f"show port-access clients")
+            to1 = output.split("\n")
+            print(f"Ports that have role: {policyrole}:")
+
+            for to in to1 :
+                to = to.lstrip()
+                #print(to)
+                if policyrole in to:
+                    print(to)
+                    to3 = to.split(" ")[0]
+                    output2 = net_connect.send_command(f"port-access reauthenticate interface {to3}")
+                    print(f"{to3} Reauthentication initiated.")
+
+                    #output1 = [f"interface {to3}","shut","no power"]
+                    #net_connect.send_config_set(output1)
+                    #time.sleep(1)
+                    #output2 = [f"interface {to3}","no shut","power"]
+                    #net_connect.send_config_set(output2)
+
+                to = to.split(" ")[0]
+
+            net_connect.disconnect()
+        except (NetmikoTimeoutException) as error:
+            print("Switch is not responding----->  " + ip_add)
+            print("Switch is not responding----->  " + ip_add)
+            print("Switch is not responding----->  " + ip_add)
+
+        q.task_done()
+
+# For helping prevent overlapping print statements
+# between different queues.
+def mt_print(msg):
+    with PRINT_LOCK:
+        print(msg)
+
+# Main function used for MultiThreading
+def run_mt(mt_function, q, **kwargs):
+    devs = kwargs['devs']
+    num_threads = min(NUM_THREADS, devs)
+
+    for i in range(num_threads):
+        thread_name = f'Thread-{i}'
+        worker = Thread(name=thread_name, target=mt_function, args=(q, kwargs))
+        worker.start()
+        
+    q.join()
+
+if __name__ == "__main__":
+    main()
-- 
GitLab