Python Exscript Jun

2024-09-30 22:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试运行一个脚本来显示所有配置,并将它们写入juniper和CISCO路由器的文件中。 到目前为止,CISCO脚本正在正常工作,但问题在于juniper路由器。在

for ii in JUNIPER:
    print ii
    cmd2 = 'show configuration | display set'
    conn.connect(ii)
    conn.login(account1)
    conn.execute(cmd2)
    print conn.response
    #filerouter = open(ii, "w")
    #filerouter.write(conn.response)
    #filerouter.close()

在得到要查询的设备列表之后,我运行这个,但是它被卡住了,好像有一个缓冲区的限制。。。-在

如果我尝试执行其他命令:
("show configuration | display set | match destination ")
--我把输出写在文件或屏幕上。在

^{pr2}$

在=========== ===问题-如何让脚本运行并提供命令的输出:show configuration | display set第二个pic显示了我得到的错误,但是如果我将命令改为:show configuration | display set | match description我将得到请求的信息。我是否缺少在模块中添加一些内容,以便exscript/python避免超时?在


Tags: 文件命令脚本showdisplay路由器connconfiguration
3条回答

默认情况下,JunOS对任何命令返回的冗长输出进行分页。可能发生的情况是,您所连接到的Juniper设备正在对show configuration | display set命令的输出进行分页,而Exscript正在超时,因为该设备正在等待用户输入以继续对命令的输出进行分页,而不是返回Exscript识别的提示。在

我将作如下修改:

for ii in JUNIPER:
    print ii
    cmd2 = 'show configuration | display set | no-more'
    conn.connect(ii)
    conn.login(account1)
    conn.execute(cmd2)
    print conn.response

这将禁用该命令的输出分页,并应立即返回到提示并允许Exscript将输出返回给您。此外,我还为我的命令添加了回车键,即:

^{pr2}$

但是做上述操作的有用性是值得商榷的,好像我正确地记得execute()方法应该为您这样做。在

我使用这个脚本使用PyEZ和JSON来使用多个IP地址。在

from jnpr.junos import Device
from lxml import etree
import json


config_file = open('config.json')
config = json.load(config_file)
config_file.close()


for host in config['ip']:

    dev = Device(host=host, user=config['username'], 
    password=config['password'], port=22)
    dev.open()
    data = dev.rpc.get_config(options={'format':'set'})
    file_name = dev.facts['fqdn']
    print(etree.tostring(data))
    dev.close()

    f = open(file_name + '.txt', 'w')
    f.write(etree.tostring(data))
    f.close()

JSON文件如下所示:

^{pr2}$

对于使用python处理Junos设备,我建议您使用PyEZ-https://github.com/Juniper/py-junos-eznc

from jnpr.junos import Device
from lxml import etree

dev = Device('hostname', user='username', password='Password123')
dev.open()

cnf = dev.rpc.get_config()    # similar to 'show configuration | no-more' on cli
print (etree.tounicode(cnf))

dev.close()

相关问题 更多 >