我写了一个python脚本,将我连接到VPN。在它执行此操作之前,它会测试我的外部IP,并将输出记录为变量“originip”,然后它连接到我的vpn,然后再次运行测试。它显示我的originip,然后是我的newip,然后运行条件,如果测试origin ip和newip是否相同然后说有错误。我稍后会添加其他逻辑。目前,该程序工作正常,但它总是打印“有错误,重置”而不是去Else线和打印“你现在已成功连接”
我认为我的if逻辑出现了问题:
if newip and originip == originip:
print "there was an error, resetting..."
else:
print "You are now connected successfully"
所以我测试了上面的内容,当我的VPN连接正常时,它报告新的和旧的IP地址不同,然后打印“有错误,重置” 如果它连接,并同时显示newip和originip,它也会打印“出现错误,重置......”
我无法让它执行上述声明中的else部分。
这是程序的整个python端
#!/usr/bin/env python
import pexpect
import sys
import os
import time
import subprocess
secdelay = int(raw_input("How many seconds before resetting? "))
p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE)
originip = p.stdout.read()
print 'Public IP Address is', originip
child = pexpect.spawn ('./vpn.sh -arg1')
child.expect ('')
child.expect ('(?i)Enter Aut Username:')
child.sendline ('myusername')
child.expect ('(?i)Enter Auth Password:')
child.sendline ('mypassword')
print "Establishing connection..."
time.sleep(10)
p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE)
newip = p.stdout.read()
print "The New IP is ",newip
print "the old IP was ", originip
if newip and originip == originip:
print "there was an error, resetting..."
else:
print "You are now connected successfully"
print "sleeping for ",secdelay," seconds"
time.sleep(secdelay)
child.sendcontrol('c')
if child.isalive():
child.sendcontrol('c')
child.close()
if child.isalive():
print 'Child did not exit gracefully.'
else:
print 'Child exited gracefully.'
Finnaly,这是我添加到“checkmyip.sh”脚本中的代码。这只是一个简单的wget:
#!/usr/bin/env bash
wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'
所以脚本运行正常,只是这个错误检查逻辑令我感到困惑。为什么我的if x和y == x不能正常工作,当x和y都在我的if语句正上方的打印行中枚举不同的值时,我很困惑。
任何建议或帮助都将非常感激。谢谢你的阅读!
感谢大家的帮助!固定代码是这样的:
if newip and originip == originip:
已更改为
if newip == originip:
答案 0 :(得分:2)
是的,条件originip == originip
总是为真。
因此,如果newip
不为空,则整个表达式newip and originip == originip
也将为True:
>>> originip = 'foo'
>>> originip == originip
True
>>> newip = ''
>>> newip and originip == originip
False
>>> newip = 'bar'
>>> newip and originip == originip
True
你的意思是:
if newip and newip == originip:
代替?
答案 1 :(得分:2)
请改为尝试:
if newip == originip:
print "there was an error, resetting..."
答案 2 :(得分:1)
>if newip and originip == originip:
如果newip
等于自身,您正在测试originip
然后的“布尔”值,这总是正确的。
你可能意味着:
if newip == originip: