Search code examples
pythonsubprocesspopen

python subprocess with hma


I am trying to get subprocess to run an hma proxy through linux. I'm new to Python so maybe I'm not using the right approach. What I need it to do is run hma in the background and have the program check whether or not my public IP is the same as before the program was launched and if it isn't re-run the hma program every 30 minutes.

Basically the program needs to check current IP then connect to hma. If first IP matches second IP, i.e. hma hasn't connected, then print waiting. If the IP doesn't match then run hma again in 30 minutes. Here is the code I have so far.

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

What am I doing wrong? Sorry if this is completely wrong. I'm new to the subprocess module


Solution

  • Hi so I'm not familiar with hma, but something like this should work. If not dav1d said make sure hma-start is in your path. I'm not quite sure why your using /Desktop/hma? It shouldn't matter where it is when you have elevated privs.

    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()