woocode / sa-auto / sh / py /

#!/usr/bin/env python

定时上报 WAN 口地址
import sys
import re
import socket, struct
import urllib
import base64
import urllib2

from subprocess import Popen, PIPE

# 调用shell命令 curl
def _get_wan_ip():
    cmd = 'curl'
    p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    if stderr:
        print >> sys.stderr, stderr
        return ''
    ret =
    return ret

def get_wan_ip():
    pat = re.compile('(\d+\.\d+\.\d+\.\d+)')
    url = ''
    url = ''
    response = urllib2.urlopen(url)
    html =
        return ''

def get_default_gateway_linux():
    """Read the default gateway directly from /proc."""
    with open("/proc/net/route") as fh:
        for line in fh:
            fields = line.strip().split()
            if fields[1] != '00000000' or not int(fields[3], 16) & 2:

    return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))

def report():
    gateway_map = {'': '002',
                   '' : '001',
    wan_ip = get_wan_ip()
    gateway = get_default_gateway_linux()
    if not (wan_ip and gateway):
        print >> sys.stderr, "Could not get default gateway or wan_ip"

    url = ''
    query = {'c': gateway_map[gateway],
             'd': wan_ip}

    params = urllib.urlencode(query)
    url_args = 'm=%s' % base64.encodestring(params)

    req = urllib2.Request(url + url_args)
    response = urllib2.urlopen(req)
    del response

if __name__ == "__main__":
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.