I need some help for a script in Python. it works for few times, but I just added some time.sleep() and now the script won't work : It did not connect to switch by SSH or Telnet.
I also need some tips to optimize it, because i'm not pro and i would like to learn more on scripting.
Thank you !
(Sorry commentaries in french :/)
import paramiko, time, re, os
from ciscoconfparse import CiscoConfParse
import telnetlib
###cherche hotes depuis fichier hosts.txt###
with open("./hosts/hosts.txt","r") as f:
hosts = re.findall(r'(\d+.\d+.\d+.\d+)', f.read())
f.close()
###boucle pour chaque hotes###
for host in hosts:
state = ""
running_config = ""
try:
###Connexion SSH switch###
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username='admin', password='XXXXX')
###création shell interactif###
connection = client.invoke_shell()
###commande enable###
connection.send("enable\n")
time.sleep(1)
connection.send("XXXX\n")
###commande running-config###
connection.send("terminal length 0\n") ###Permet l'affichage de l'intégralité des commande###
time.sleep(1)
connection.send("show running-config\n")
###récupération commande running-config###
resp_run = connection.recv(10000).decode(encoding='utf-8')
###fermeture sessions SSH###
connection.close()
client.close()
###Traitement running-config###
regex = re.compile(r'(Current configuration : (.+\n)+end)')
res = re.findall (regex, resp_run)
running_config = res[0][0] ###aide appel variable
except:
###si fail SSH test telnet###
state = "SSH NOK "###Permet génération rapport###
try:
###connexion telnet si SSH NOK###
session = telnetlib.Telnet(host, 23)
session.write(b"admin\n")
session.read_until(b"Password: ")
session.write(b"XXXXXX\n")
time.sleep(1)
session.write(b"enable\n")
session.read_until(b"Password: ")
session.write(b"XXXXXX\n")
session.read_until(b"#")
session.write(b"term len 0\n")
session.write(b"show run\n")
res = session.read_until(b"\nend").decode('utf-8')
###fermeture session telnet###
session.close()
###récupération commande running-config###
regex = re.compile(r'(Current configuration : (.+\n)+end)')
res = re.findall(regex, res)
running_config = res[0][0] ###aide appel variable###
except:
state += "TELNET NOK"###Permet génération rapport###
###Création fichier running_config.txt + dir selon host###
newpath = ('./config_switch/'+host+'/')
if not os.path.exists(newpath):
os.makedirs(newpath)
f = open("./config_switch/"+host+"/running_config.txt", "w+")
f.write(running_config)
f.close()
###test ssh telnet pour rapport###
if not state:
print (host+" OK")
else:
print (host+" : "+state+" ERREUR")
###generation rapport###
f = open("./rapport.txt","a")
f.write(state)
f.close()
###arrêt de 2sec par sécurité###
time.sleep(2)