【发布时间】:2018-12-29 18:14:28
【问题描述】:
我的嵌套循环有问题。我有 ipaddress 和 hostname 的列表,地址循环是正确的,而在 hostname 上循环是不正确的,它总是在中断后使用索引 0。
# list example:
ipaddress = ['192.168.1.1', '192.168.1.2']
nhostname = ['lab-sw01', 'lab-rtr02']
for i in ipaddress:
print ("Now accessing the device: ", i)
dev = i.strip()
tn = telnetlib.Telnet(dev)
print("Host: ",dev)
tn.read_until(b"Username:")
tn.write(user.encode("ascii") + b"\n")
for j in nhostname:
print ("Hostname :", j)
## hn = i.strip()
if password:
tn.read_until(b"Password: ")
tn.write(password.encode("ascii") + b"\n")
tn.write(b"conf t\r\n")
time.sleep(2)
tn.write(("hostname " + j + "\n").encode('ascii'))
time.sleep(2)
tn.write(b"exit \n")
tn.write(b"wr mem \n")
tn.close()
break
输出:
Now accessing the device: 192.168.137.50
Host: 192.168.137.50
Hostname **: lab-sw01**
Now accessing the device: 192.168.137.51
Host: 192.168.137.51
Hostname : **lab-sw01**
谢谢
【问题讨论】:
-
这个缩进是你原始代码的写法吗?你能在这里检查它是否正确吗?
-
我看不出
break没有被执行。此外,您的循环可能应该是for j in hostname(不是nhostname,此处未定义)。 -
另外,你真的想要一个嵌套循环吗?您可能想压缩两个列表并一起循环。
-
@ParitoshSingh,是的。那是原始的缩进。这是在不同论坛上发布的示例配置谢谢...python-forum.io/…
-
@busybear,在 j 的循环之后执行 break。还有一个打字错误..应该是nhostname(修改了帖子)。目前,我唯一知道的是嵌套循环,我不熟悉将列表循环在一起的 zip,但我会回顾一下。感谢分享
标签: python python-3.x loops for-loop network-programming