Вложен для циклической выдачи, всегда используя индекс 0 - PullRequest
0 голосов
/ 29 декабря 2018

У меня проблема с моим вложенным циклом.У меня есть список ipaddress и имя хоста, зацикливание адреса правильное, а зацикливание на имени хоста нет, он всегда использует индекс 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**

Спасибо

Ответы [ 3 ]

0 голосов
/ 29 декабря 2018

Вы ставите оператор break в конце цикла nhostname, что означает, что вложенный цикл разрывается после первой итерации и возвращается к циклу ipadress.

Удаляет оператор break в концевложенный цикл и он должен работать.

0 голосов
/ 29 декабря 2018

Вам нужно что-то вроде

ipaddress = ['192.168.1.1', '192.168.1.2']
nhostname = ['lab-sw01', 'lab-rtr02']
for i,j in zip(ipaddress,nhostname):
    print ("Now accessing the device: ", i)
    dev = i.strip()
    print("Host: ",dev)
    print("hostname " + j + "\n")

Вывод:

Now accessing the device:  192.168.1.1
Host:  192.168.1.1
hostname lab-sw01

Now accessing the device:  192.168.1.2
Host:  192.168.1.2
hostname lab-rtr02

Ваш внутренний цикл разрывается, но во втором цикле внешнего цикла for он начинается заново,Вот почему ваше имя хоста никогда не меняется.

ipaddress = ['192.168.1.1', '192.168.1.2']
nhostname = ['lab-sw01', 'lab-rtr02']
for i in ipaddress:
    print ("Now accessing the device: ", i)
    print("Host: ",dev)
    for j in nhostname: #In every looping of the outer loop it will access the first element of the nhostname
        print ("Hostname :", j)
        break

Я думаю, ваш код должен быть -

ipaddress = ['192.168.1.1', '192.168.1.2']
nhostname = ['lab-sw01', 'lab-rtr02']
for i,j in zip(ipaddress,nhostname):
    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")
    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()
0 голосов
/ 29 декабря 2018

Вам не нужен вложенный цикл:

for i in range(0,len(ipaddress)):
    print ("Now accessing the device: ",ipaddress[i])
    dev = ipaddress[i].strip()
    tn = telnetlib.Telnet(dev)
    print("Host: ",dev)
    tn.read_until(b"Username:")
    tn.write(user.encode("ascii") + b"\n")

    print ("Hostname :", hostname[i])
    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 " + hostname[i] + "\n").encode('ascii'))
    time.sleep(2)
    tn.write(b"exit \n")
    tn.write(b"wr mem \n")
    tn.close()
...