Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:通过SSH(Paramiko)或TELNET(Telnetlib)从cisco交换机运行_config_Python_Paramiko_Cisco_Telnetlib - Fatal编程技术网

Python:通过SSH(Paramiko)或TELNET(Telnetlib)从cisco交换机运行_config

Python:通过SSH(Paramiko)或TELNET(Telnetlib)从cisco交换机运行_config,python,paramiko,cisco,telnetlib,Python,Paramiko,Cisco,Telnetlib,我需要一些关于Python脚本的帮助。它工作了几次,但我只是添加了一些time.sleep(),现在该脚本无法工作:它没有通过SSH或Telnet连接到交换机 我还需要一些技巧来优化它,因为我不专业,我想学习更多关于脚本的知识 谢谢大家! (抱歉的法语评论:/) 如果您的网络中有不同版本/型号的设备,则应该具有良好的错误处理机制。因此,我们将以下函数用于一些可能对您有所帮助的操作 代码(SSH连接): #通过SSH连接到设备(如果返回None,则不继续) def connectToCPESSH(

我需要一些关于Python脚本的帮助。它工作了几次,但我只是添加了一些time.sleep(),现在该脚本无法工作:它没有通过SSH或Telnet连接到交换机

我还需要一些技巧来优化它,因为我不专业,我想学习更多关于脚本的知识

谢谢大家!

(抱歉的法语评论:/)


如果您的网络中有不同版本/型号的设备,则应该具有良好的错误处理机制。因此,我们将以下函数用于一些可能对您有所帮助的操作

代码(SSH连接):

#通过SSH连接到设备(如果返回None,则不继续)
def connectToCPESSH(ip、uname、pin、CI_LOCAL_ID、CI_名称、CI_组织名称、runIDnull):
ip=ip.strip()
SSHCliente=None
尝试:
client=paramiko.SSHClient()
client.set\缺少\主机\密钥\策略(paramiko.AutoAddPolicy())
client.connect(ip,端口=22,用户名=uname,密码=pin,
超时=240,横幅超时=250,验证超时=500)
SSHCliente=client.invoke_shell()
返回SSHClient
除paramiko.ssh_exception.SSHException作为ssh1Err外:
返回“设备SSH版本错误:+str(ssh1Err)
如果isinstance(SSHCliente,paramiko.channel.channel):
SSHCliente.close()
sys.exit()
一无所获
例外情况除外,如e:
如果isinstance(SSHCliente,paramiko.channel.channel):
SSHCliente.close()
尝试:
tln=telnetlib.Telnet(ip)
打印(“使用Telnet访问”+str(e)+“###”+str(t))
除t以外的例外情况:
打印(“Crab!Telnet和SSH连接都失败!”+str(e)+“###”+str(t))
一无所获
因此,在上面的代码中,我们尝试通过SSH进行连接,如果我们得到关于SSHException的错误,我们将记录它,如果我们得到任何错误,请尝试Telnet(这是可选的,我们对一些旧设备使用Telnet)

代码(等待提示:仅HW和Cisco)

#等待第一次连接的提示
def waitForPrompt(cxn):
附录SCRNRSLT=“”
lastScrnRslt=“”
routerType=“”
outerLoop=True
timerx=0
当outerLoop==True时:
tempScrn=cxn.recv(65100).decode('ascii')
如果(lastscrnslt!=tempScrn):
附录SCRNRSLT+=临时SCRN
lastscrnslt=tempScrn
如果tempScrn中的“#”或tempScrn中的“>”或tempScrn中的“]”,则:
如果在tempScrn中使用“#”:
routerType=“Cisco”
如果((“”在tempScrn中)或(“[”在tempScrn中)和“]”在tempScrn中):
routerType=“华为”
打破
timerx+=1
如果(时间Rx>=100):
logging.warn(“Uppss!无连接”)
routerType=“不适用”
打破
返回路由类型
等待提示很奇怪,若您提前操作,您的命令将不会发送到设备,若您延迟操作,您的cxn可能会被终止。因此,只需检查提示符(HW:,Cisco:您的路由器名称#)就更好了

代码(发送和接收):

#发送命令并接收来自SQL的CIDATATA
def SENDCMDTOSH(cxn、cmd、路由类型、超时):
附录SCRNRSLT=“”
lastScrnRslt=“”
发送(字节(cmd+“\x0D”,“utf-8”))
时间。睡眠(2)
timery=time.perf_计数器()

while time.perf_counter()-timery您在
connect
之后添加了
sleep
调用,那么它如何阻止连接呢?你得到的确切错误是什么?你从哪里得到这个错误?空闲时没有错误,我只是对每个主机有一个结果:“Host ssh nok telnet nok erreur”我使用这些打印来知道是使用ssh还是telnet。所以我有一个空的配置为每个开关…谢谢你!所以我可以得到所有的例外?那我们走吧!有什么优化的建议吗?所以我放了一些例外以知道会发生什么,但我有一个错误,但我不知道它来自哪里。。。列表索引超出范围[WinError 10061]Aucune connexion n'a puètretable car l'Coordinator cible l'a express refusée 10.250.171.251:SSH NOK TELNET NOK ERREUR File“C:\Users\xxxxxxxxxx\Desktop\conf switch python\prog.py”,第26行,in time.sleep(1)谢谢你的帮助,我要看看你的代码,比我的代码好多了。
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)