Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Created April 21, 2015 11:29
Show Gist options
  • Save Ivlyth/36692c1002aa83ea9666 to your computer and use it in GitHub Desktop.
Save Ivlyth/36692c1002aa83ea9666 to your computer and use it in GitHub Desktop.
pydig, wrap `dig` for ip information
myth@myth:~$ dig w.myth.ren
; <<>> DiG 9.9.5-3ubuntu0.2-Ubuntu <<>> w.myth.ren
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42119
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;w.myth.ren. IN A
;; ANSWER SECTION:
w.myth.ren. 19 IN A 101.231.200.10
;; Query time: 0 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Tue Apr 21 19:27:56 CST 2015
;; MSG SIZE rcvd: 55
myth@myth:~$ pydig w.myth.ren
; <<>> DiG 9.9.5-3ubuntu0.2-Ubuntu <<>> w.myth.ren
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12808
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;w.myth.ren. IN A
;; ANSWER SECTION:
w.myth.ren. 553 IN A 101.231.200.10(上海市上海市电信)
;; Query time: 364 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)()
;; WHEN: Tue Apr 21 19:28:32 CST 2015
;; MSG SIZE rcvd: 55
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Author : myth
Date : 15-4-21
Email : belongmyth at 163.com
'''
import urllib2
import json
import commands
import re
import sys
import os
reload(sys)
sys.setdefaultencoding(u'utf-8')
ip_re = re.compile(ur'.*?(?P<ip>\d+\.\d+\.\d+\.\d+).*?')
def get_ip_info(ip):
try:
response = urllib2.urlopen(u'http://ip.taobao.com/service/getIpInfo.php?ip=%s' % ip)
result = json.loads(response.read())
except Exception as e:
return u'UNKNOWN'
if result[u'code'] == 0:
info = result[u'data']
return u'%s%s%s'%(info[u'region'], info[u'city'], info[u'isp'])
return u'UNKNOWN'
dig_cmd = u'dig %s'%(' '.join(sys.argv[1:]))
status, output = commands.getstatusoutput(dig_cmd)
trans_output = []
for line in output.splitlines():
m = ip_re.match(line)
if not m:
trans_output.append(line)
continue
ip = m.groupdict().get(u'ip',None)
if not ip :
trans_output.append(line)
continue
ip_info = get_ip_info(ip)
new_line = u'%s(%s)'%(line, ip_info)
trans_output.append(new_line)
print os.linesep.join(trans_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment