Source

woocode / sa-auto / sh / py / report_wan_ip.py

#!/usr/bin/env python
#coding:utf-8

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

from subprocess import Popen, PIPE

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

def get_wan_ip():
    pat = re.compile('(\d+\.\d+\.\d+\.\d+)')
    url = 'http://checkip.dyndns.org/'
    url = 'http://www.123cha.com/ip/'
    response = urllib2.urlopen(url)
    html = response.read()
    if pat.search(html):
        return pat.search(html).group(0)
    else:
        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:
                continue

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

def report():
    gateway_map = {'192.168.0.50': '002',
                   '192.168.0.1' : '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"
        sys.exit(1)

    url = 'http://stat.cdcn86.com/api/api.php?'
    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__":
    report()
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 ProjectModifiedEvent.java.
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.