Python:如何让else语句运行x次?

时间:2016-07-05 06:37:12

标签: python telnet ping cisco

我有一个telnet路由器的脚本,如果它不能ping 8.8.8.8重启路由器,但我不希望它连续三次重启路由器。 如果它在三次之后无法ping 8.8.8.8我希望它继续ping 8.8.8.8直到它再次恢复并重新开始。

import subprocess
output = subprocess.call('ping 8.8.8.8', shell=True)
while output == 0:
output = subprocess.call('ping 8.8.8.8', shell=True)
else:
import telnetlib
import datetime

now = datetime.datetime.now()

host = "912.168.1.1" # your router ip
username = "name" # the username
password = "password"
filename_prefix = "cisco-backup"

tn = telnetlib.Telnet(host)
tn.read_until("Username:")
tn.write(username+"\n")
tn.read_until("Password:")
tn.write(password+"\n")
tn.write("reload"+"\n")
tn.write("y"+"\n")
enter code here

我只是新手而且我不知道如何让else语句连续重复三次。

2 个答案:

答案 0 :(得分:0)

你缺少缩进词,所以我希望我的逻辑是正确的,无论如何,以下内容应该做你想要的。

在你的情况下,使用else语句几乎没有意义,因为这只会让你处于必须创建另一个while循环的位置。另一个修复是将output = subprocess.call...行移动到while循环的末尾,在路由器重置之后(如果你进入循环,如果没有响应则清除路由器,没有理由在重启之前再试一次)。

我添加了retries变量来跟踪路由器重置的次数,并将其作为条件添加到while循环中。如果重试次数超过3次,则循环将中断。

import subprocess
retries = 0
output = subprocess.call('ping 8.8.8.8', shell=True)
while (output == 0 and retries < 3):
    import telnetlib
    import datetime

    now = datetime.datetime.now()

    host = "912.168.1.1" # your router ip
    username = "name" # the username
    password = "password"
    filename_prefix = "cisco-backup"

    tn = telnetlib.Telnet(host)
    tn.read_until("Username:")
    tn.write(username+"\n")
    tn.read_until("Password:")
    tn.write(password+"\n")
    tn.write("reload"+"\n")
    tn.write("y"+"\n")
    output = subprocess.call('ping 8.8.8.8', shell=True)
    retries += 1

if (retries == 3):
    print ("Couldnt restore router")

答案 1 :(得分:0)

你可以尝试这样做:

如果我理解正确,你要做的是制作一个脚本,将继续尝试ping 8.8.8.8,如果失败,它将重启路由器(最多3次),如果重新启动没有&#39;帮助脚本应该ping 8.8.8.8直到它成功。之后,脚本将重新开始

import subprocess
output = 0
while output == 0:
    output = subprocess.call('ping 8.8.8.8', shell=True)

    for i in xrange(3): #will restart the router until ping works OR at most 3 times

        if output == 0:  # if the ping succeeded don't restart the router
            break

        import telnetlib
        import datetime

        now = datetime.datetime.now()

        host = "912.168.1.1" # your router ip
        username = "name" # the username
        password = "password"
        filename_prefix = "cisco-backup"

        tn = telnetlib.Telnet(host)
        tn.read_until("Username:")
        tn.write(username+"\n")
        tn.read_until("Password:")
        tn.write(password+"\n")
        tn.write("reload"+"\n")
        tn.write("y"+"\n")

        output = subprocess.call('ping 8.8.8.8', shell=True) #after restarting the router check the ping again

    #after the loop
    while output != 0: output = subprocess.call('ping 8.8.8.8', shell=True)  #will ping until the ping work