我正在尝试通过linux运行子进程来运行hma代理。我是Python的新手,所以也许我没有使用正确的方法。我需要它做的是在后台运行hma并让程序检查我的公共IP是否与程序启动前相同,以及是否每30分钟不重新运行hma程序。
基本上程序需要检查当前的IP然后连接到hma。如果第一个IP匹配第二个IP,即hma尚未连接,则打印等待。如果IP不匹配,则在30分钟内再次运行hma。这是我到目前为止的代码。
import os
import webbrowser
import time
import socket
import urllib2
import subprocess
response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
internal = response.read()
print "Internal IP Address is ", internal
hma = ['cd', '/Desktop/hma', ';', './hma-start', '-r']
subprocess.Popen(hma, shell=True)
response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
external = response.read()
while (internal == external):
time.sleep(1)
response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
external = response.read()
print 'waiting'
while (internal != external):
print 'It changed'
hma = ['cd', '/Desktop/hma', ';', './hma-start', '-r']
subprocess.Popen(hma, shell=True)
response = urllib2.urlopen("http://automation.whatismyip.com/n09230945.asp")
external = response.read()
print "External IP Address is ", external
我做错了什么?对不起,如果这是完全错误的。我是子进程模块的新手
答案 0 :(得分:0)
如果您使用shell=True
,您的命令行必须是字符串:
hma = 'cd /Desktop/hma; ./hma-start -r'
subprocess.Popen(hma, shell=True)
但您也可以在没有shell=True
的情况下执行此操作:
hma = ['/Desktop/hma/hma-start', '-r']
subprocess.Popen(hma)
如果您想等到该过程完成,请致电.communicate()
上的Popen-Object
。
答案 1 :(得分:0)
嗨所以我不熟悉hma,但这样的事情应该有用。 如果不是dav1d说确保hma-start在你的路径中。我不太清楚你为什么使用/ Desktop / hma?当你拥有高级私人时,它应该无关紧要。
import os
import webbrowser
import time
import socket
import urllib2
import subprocess
import socket
URL = "http://automation.whatismyip.com/n09230945.asp"
DIR = '/Desktop/hma'
HMA = ['./hma-start', '-r']
WAIT_TIME = 60 * 30 # 30 min
GET_IP = lambda: urllib2.urlopen(URL).read()
if __name__ == '__main__':
external = internal = GET_IP()
print "Internal IP Address is %s" % internal
try:
os.chdir(DIR)
except OSError:
print "%s not found" % DIR
print "External IP Address is ", external
while True:
external = GET_IP()
if external != internal:
print "Proxied"
time.sleep(WAIT_TIME)
else:
print "Not Proxied"
proc = subprocess.Popen(HMA)
proc.wait()