get gip (server side)
#!/usr/bin/env python
import memcache
import time
import re
'''
on local side, pls add cronjob.
be noticed that the url is formatted. you may specify your own cgi path.
*/30 * * * * curl -s DOMAIN.com/1p/`curl -s ifconfig.me/ip` >/dev/null
'''
def timestr():
return time.strftime('%Y-%m-%d %X')
def validateIP(ip):
return re.match(r'^(?:\d{1,3}\.){3}\d{1,3}', ip)
class IP(object):
def __init__(self):
self.mc = memcache.Client(['127.0.0.1:11211'])
def get(self):
return (self.mc.get('ip'), self.mc.get('touched'), self.mc.get('updated'))
def set(self, ip):
(i, t, u)=self.get()
self._update_touched_time()
if ip!=i and validateIP(ip):
self._update_updated_time()
self.mc.set('ip', ip)
def _update_touched_time(self):
self.mc.set('touched', timestr())
def _update_updated_time(self):
self.mc.set('updated', timestr())
def get_v(p, regex=None):
"""return cgi GET parameter; strip white spaces at both ends if any;
if verify pattern provided, do match test; only return matched values.
Note: it uses re.match to check , not re.search.
"""
import cgi
form = cgi.FieldStorage()
value= form.getfirst(p)
if not value:
return None
value=value.strip()
if regex is not None:
import re
if re.match(regex+"$",value):
return value
else:
return None
else:
return value
def main():
print "content-type: text/plain\n"
i=IP()
ip=get_v("ip")
full=get_v('full')
if ip:
i.set(ip)
if full:
info=i.get()
head=('IP', 'Touched', 'Updated')
ret=zip(head, info)
for r in ret:
print "%s:\t%s" % (r[0], r[1])
else:
print i.get()[0]
if __name__=='__main__' :
main()