-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_detect.py
More file actions
66 lines (57 loc) · 1.4 KB
/
ip_detect.py
File metadata and controls
66 lines (57 loc) · 1.4 KB
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
# python ip_detect.py > /dev/null 2>&1
'''
Finds your IP address
'''
import requests
import socket
import yaml
from collections import Counter
from plumbum.cmd import git
def get_external_ip():
ips = {}
sites = ['http://www.icanhazip.com/', 'http://ipaddr.me',
'http://curlmyip.com/']
for s in sites:
try:
r = requests.get(s)
ip = r.text.strip()
if ip.startswith('<pre>') and ip.endswith('</pre>'):
ip = ip[5:-6]
ips[s] = ip
except:
pass
c = Counter([v for k, v in ips.items()])
return c.most_common(1)[0][0].encode('utf-8')
def get_local_ip(target):
ipaddr = ''
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((target, 8000))
ipaddr = s.getsockname()[0]
s.close()
except:
pass
return ipaddr
def get_ips():
res = {}
try:
res['local'] = get_local_ip('ya.ru')
except:
pass
try:
res['external'] = get_external_ip()
except:
pass
return res
def save_file(data):
name = 'rpi_ip.yaml'
with open(name, 'w') as f:
f.write(yaml.dump(data, default_flow_style=False))
if __name__ == "__main__":
try:
data = get_ips()
save_file(data)
git['commit', '-m', '"ip update"', 'rpi_ip.yaml']()
git['push']()
except:
pass