Pexpect - 登录到Cisco设备,只从配置中获取主机名。

时间:2015-06-30 16:40:49

标签: python expect cisco

我正在运行一个使用pexpect将命令发送到cisco设备的python脚本。在此过程中,我需要获取设备的主机名。我有IP,但需要主机名。有两种方法可以检索它;首先,它出现在#符号(即DEVICE-01#)之前的提示符下,或者通过"显示运行主机名"等命令出现。输出"主机名DEVICE-01"。

我可以将整个配置拉入文件并使用ciscoconfparse解析它,但这看起来有点沉重。我可以用什么方法来获取主机名?

我登录后,我已尝试过:

c = pexpect.spawn('connection stuff')
#login happening here
c.expect('#')
c.sendline('show run hostname')
hostname = c.before 
#use hostname for use in later commands
etc etc 

这个c.before声明并没有给我我正在寻找的东西。我认为这是一个时间问题,当我使用它时,但对于我需要连接的设备数量不会起作用。

关于好方法的想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我把它整理好了。正在使用:

c = pexpect.spawn('connection stuff')
#login happening here
c.expect('#')
hostname = c.before 
print "Connected to " + hostname

但由于某种原因,这会打破剧本。所以我在期望获得新提示之前添加了一个新行:

c = pexpect.spawn('connection stuff')
#login happening here
c.expect('#')
c.sendline('\n')
c.expect('#')
hostname = c.before 
print "Connected to " + hostname

给了我这个:

Connected to 
DEVICE01

然后我想我可以找到一种方法再次删除该新行:

c = pexpect.spawn('connection stuff')
#login happening here
c.expect('#')
c.sendline('\n')
c.expect('#')
h = c.before 
hostname = h.lstrip()
print "Connected to " + hostname

导致:

Connected to DEVICE-01

我想要的。

相关问题