我是一个Java/C编程人员,正在努力学习Python。(我在Linux机器上用Python2.4.3编写)我有一个简单的程序,可以远程登录到Cisco路由器,登录,然后捕获配置。路由器的配置存储在名为“output”的变量中:
#!/usr/bin/python
import telnetlib
import datetime
import sys
def telnetFunction( host ):
print("Telnetting to device "+host+"...\n")
tn = telnetlib.Telnet(host)
# ...use tn.read_until() and tn.write() to log into the router... ...this works...
tn.write("terminal length 0"+"\n")
tn.write("show run"+"\n")
tn.write("exit"+"\n")
output=tn.read_all() # router config stored as "output"
return output
host = "192.168.102.133"
output=telnetFunction( host )
以上代码有效。通过使用一堆不同的print()语句,我可以看到路由器的配置都在“output”中,我假设它是一个以换行符结尾的字符串数组。。。。?对此并不完全确定;telnetlib文档没有指定。在
我现在的问题是我需要我的程序再次单步执行输出,一次提取一个字符串。我需要这样的东西:
^{pr2}$如果输出是这样的:
Current configuration : 34211 bytes\n!\nversion 12.3\nno service pad\n...etc...
我需要tmpString在上面循环的每个迭代中等于follow:
tmpString = "Current configuration : 34211 bytes"
tmpString = "!"
tmpString = "version 12.3"
tmpString = "no service pad"
我已经在谷歌上搜索了几个小时,但我被难住了。(部分问题是我不清楚“output”是否确实是一个数组。可能是一根绳子吗?)我玩过split()和使用[]的,但到目前为止还没有运气。有人知道我哪里错了吗?谢谢,-罗亚
如您在示例中所述,假设输出定义为
下一步是将字符串拆分为\n
^{pr2}$这将生成以下列表
然后您可以迭代这个列表。在
把它们绑在一起
你的变量tn,我假设,被当作一个文件句柄来处理。因此,当您读取此“文件”一次时,指针位于文件末尾,需要重置:
在执行第二个循环之前调用它。在
或者,可以迭代输出,如下所示:
^{pr2}$相关问题 更多 >
编程相关推荐