-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.py
127 lines (99 loc) · 2.66 KB
/
query.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python
# coding=utf-8
import os
import re
import sys
import json
import urllib
import urllib.request
import socket
import struct
import fcntl
from alfred.feedback import *
# Taobao restful query api
API = 'http://ip.taobao.com/service'
# Regular expression for a valid ip address
REGEXP_IP = r'(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)'
def query_ip(ip = None):
'''Query the ip information with the taobao api.'''
if ip is None: # Query the local ip instead
url = API + '/getIpInfo2.php?ip=myip'
else:
url = '%s/getIpInfo.php?ip=%s' % (API, ip)
try:
res = urllib.request.urlopen(url).read()
res = res.decode('utf-8')
return json.loads(res)
except Exception as e:
err(e, '调用接口失败,请重试!')
def generate_feedback_results(ip_query):
'''Generate the feedback results.'''
fb = Feedback()
if ip_query:
ip_list = re.findall(REGEXP_IP, ip_query)
else:
ip_list = [None]
for ip in ip_list:
info = query_ip(ip)
#print ip, info
if info['code'] == 1: # query failed
kwargs = {
'title': u'查询 IP 地址失败',
'subtitle': u'错误原因: %s' % info['data'],
'valid': False
}
else: # query success
data = info['data']
title = u'%s 位于 %s %s %s' % (data['ip'], data['country'],
data['region'], data['city'])
if data['isp']:
subtitle = u'运营商: %s %s' % (data['area'], data['isp'])
else:
subtitle = ''#None
kwargs = {
'title': title,
'subtitle': subtitle,
'arg': '%s\n%s' % (title, subtitle)
}
fb.addItem(**kwargs)
#wifi_ip = local_ip('eth0')
#kwargs = {
# 'title': 'asdasd',
# 'subtitle': 'subtitle',
# 'arg': 'argsssss'
#}
#fb.addItem(**kwargs)
fb.output()
def local_ip(ifname):
ip_address = socket.gethostbyname(socket.gethostname())
return ip_address
#s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#return socket.inet_ntoa(fcntl.ioctl(
# s.fileno(),
# 0x8915, # SIOCGIFADDR
# struct.pack('256s', ifname[:15])
#)[20:24])
def ip2long(ip):
return struct.unpack("!I", socket.inet_aton(ipstr))[0]
def long2ip(ip):
return socket.inet_ntoa(struct.pack("!I", ip))
def err(e, str):
fb = Feedback()
kwargs = {
'title': '!!!发生错误!!!',
'subtitle': str,
'arg': '发生异常'
}
fb.addItem(**kwargs)
fb.output()
def main():
'''The main entry.'''
# Note: do not use single quote here, because Alfred doesn't give choice to
# escape a single quote.
# localip = local_ip('en4')
# print (localip)
# print (socket.gethostbyname_ex('localhost'))
# ip_query = "{query}"
# generate_feedback_results(ip_query)
if __name__ == '__main__':
main()