2012-07-26 76 views
0

我想让子进程通过linux来运行hma代理。我是Python的新手,所以也许我没有使用正确的方法。我需要做的是在后台运行hma,并让程序检查我的公共IP是否与启动程序前相同,并且是否每30分钟不重新运行hma程序。hma的python子进程

基本上程序需要检查当前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

指定您想要加入的目录。嗨,我不熟悉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() 
+0

这可以工作,但HMA完成连接后,它不会执行time.sleep(WAIT_TIME)。 – 2012-07-27 21:07:55

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

+0

如何使用Popen-Object? 当我使用 hma = ['/ Desktop/hma/hma-start','-r'] subprocess.Popen(hma) 我收到错误 – 2012-07-26 22:47:15

+0

哪个错误?通常你会这样做:'p = Popen(...,stdout = PIPE,stderr = PIPE);'stdout,stderr = p.communicate()' – dav1d 2012-07-26 22:52:01

+0

我需要使用子进程的全部原因是因为一旦启动hma,不要让其后的任何其他命令执行。 – 2012-07-26 22:53:57

0

尝试subprocess.Popen('./hma-start -r', cwd='/root/Desktop/hma')如果在流程直接运行时不需要执行任何操作,则可以使用subprocess.call代替。 Popen返回一个对象。调用将调用子进程,然后您的python程序将等待进程完成,然后再继续。
使用cd和子进程不能像在bash脚本中那样工作。您需要使用cwd(当前工作目录)关键字