1

我有一个我编写的 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地址和旧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.'

最后,这是我添加到“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:
4

3 回答 3

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:

反而?

于 2012-12-28T14:31:52.690 回答
2

试试这个:

if newip == originip:
    print "there was an error, resetting..."
于 2012-12-28T14:32:23.910 回答
1
>if newip and originip == originip:

您正在测试“布尔”值,newip 然后您正在测试是否originip等于自身,这始终是正确的。

你可能的意思是:

if newip == originip:
于 2012-12-28T14:31:35.487 回答