I have a Thread module that will call a function to ssh on a devices
ssh_conenction.py module
import paramiko
import os.path
import time
import sys
import re
# ask the user to input the path of the credential file
user_file = input("\n* Enter user file path and name (e.g. D:\\MyFiles\\file.txt): ")
# check if the file is exist or not
if os.path.isfile(user_file):
print("\n* username and password file is valid :)\n")
# if not exist then the program will exit
else:
print("the username/password file is not valid :( Please check it and try again.")
sys.exit()
# now check if the command file exist or not
command_file = input("\n Enter the command file path (e.g. D:\\MyFiles\\file.txt): ")
if os.path.isfile(command_file):
print("\n* Command file is valid:)")
else:
print("\n* command file is not valid please check it and try again.")
def ssh_connection(ip):
global user_file
global command_file
try:
# we will read the user/pass file and extract the username and password
selected_user_file = open(user_file, 'r')
selected_user_file.seek(0)
# print(selected_user_file.readlines()[0]) admin,python
# we are reading lines and get a list with each line as an element of that list
# then we will strip with the delimiter ',' and get the first index and rstrip the \n in case it's exist
# i was using strip instead of split which will remove the ','
username = selected_user_file.readlines()[0].split(',')[0].rstrip('\n')
# you need to start again from the start of the line
selected_user_file.seek(0)
password = selected_user_file.readlines()[0].split(',')[1].rstrip('\n')
# invoke the ssh client class from paramiko
session = paramiko.SSHClient()
# the below is used in testing environment that will accept any host key
# in production it must be RejectPolicy and accepting only the Keys you know
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to a device using it's username and password
session.connect(ip.rstrip(','), username=username, password=password)
# start an interactive session on the router
connection = session.invoke_shell()
# setting the terminal length for entire output - disable pagination
connection.send("enable\n")
connection.send("terminal length 0\n")
time.sleep(1)
# enter the global configuration mode
connection.send("\n")
connection.send("configure terminal\n")
time.sleep(1)
# Open command file for reading
selected_cmd_file = open(command_file, 'r')
selected_cmd_file.seek(0)
# writing each line to the device
for each_line in selected_cmd_file:
connection.send(each_line + '\n')
time.sleep(2)
# closing the user and cmd file
selected_user_file.close()
selected_cmd_file.close()
# checking the command output for any syntax error
router_output = connection.recv(65535)
if re.search(b"% Invalid input", router_output):
print("There was at least one IOS syntax error on device with IP {} :(".format(ip))
else:
print("\nDone for device with IP {} :)".format(ip))
# Test for reading the command output
print(str(router_output) + "\n")
# closing the connection
session.close()
except paramiko.AuthenticationException:
print("\nInvalid username or password :( \n* Please check the username/password and try again")
print("* Closing program...bye ")
and the threading module
import threading
# creating threads
def create_threads(iplist, function):
threads = []
for ip in iplist:
th = threading.Thread(target=function, args=(ip,))
# args is a tuple with a single element
th.start()
threads.append(th)
for th in threads:
th.join()
and in the app script i called the thread to ssh on all devices
# importing the necessary modules
import sys
from ip_file_valid import ip_file_valid
from ip_addr_valid import ip_addr_valid
from ip_reach import ip_reach
from ssh_connection import ssh_connection
from create_threads import create_threads
# Saving the list of IP addresses in ip.txt to avariable
ip_list = ip_file_valid()
# verifying the validity of each IP address in the list
try:
ip_addr_valid(ip_list)
except KeyboardInterrupt:
print("\n\n* Program aborted by user. Exiting...\n")
sys.exit()
# verifying reachability for each ip in the list
try:
ip_reach(ip_list)
except KeyboardInterrupt:
print("\n\n* Program aborted by user.Exiting....\n")
sys.exit()
# calling threads creation function for one or multiple SSH connections
create_threads(ip_list, ssh_connection)
# End of the program
but i am getting this exception
* 10.10.10.2 is reachable
* 10.10.10.3 is reachable
* 10.10.10.4 is reachable
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "D:\D\Cloud Learning\Python\R W Device Conf\ssh_connection.py", line 49, in ssh_connection
session.connect(ip.rstrip(','), username=username, password=password)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\client.py", line 340, in connect
self._target(*self._args, **self._kwargs)
File "D:\D\Cloud Learning\Python\R W Device Conf\ssh_connection.py", line 49, in ssh_connection
to_try = list(self._families_and_addresses(hostname, port))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\client.py", line 203, in _families_and_addresses
session.connect(ip.rstrip(','), username=username, password=password)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\client.py", line 340, in connect
addrinfos = socket.getaddrinfo(
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\socket.py", line 953, in getaddrinfo
to_try = list(self._families_and_addresses(hostname, port))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\client.py", line 203, in _families_and_addresses
addrinfos = socket.getaddrinfo(
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\socket.py", line 953, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
Done for device with IP 10.10.10.4 :)
b'Last login: Sat Mar 6 13:31:23 2021 from 10.10.10.1\r\r\nenable\r\nterminal length 0\r\nenable\nterminal length 0\nlocalhost>enable\r\nlocalhost#terminal length 0\r\nPagination disabled.\r\nlocalhost#\r\nconfigure terminal\r\nlocalhost#configure terminal\r\nlocalhost(config)#show interfaces loopback 0\r\nLoopback0 is up, line protocol is up (connected)\r\n Hardware is Loopback\r\n Internet address is 3.3.3.3/24\r\n Broadcast address is 255.255.255.255\r\n IP MTU 65535 bytes\r\n Up 24 minutes, 40 seconds\r\nlocalhost(config)#'
It gives me the output of the last device but not the two at the beginning, What could make this exception occur ?