-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocation.py
executable file
·72 lines (61 loc) · 1.81 KB
/
location.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
#!/usr/bin/env python3
import ipaddress
import os.path
import requests
import sys
EXIT={
"arguments": 4,
"ip": 5,
"keyfile": 11,
"keyformat": 12,
}
URLBASE="http://api.ipstack.com/"
KEYFILE=".ipstack_key"
def checkIP(ip):
try:
ipaddress.ip_address(ip).is_global
except ValueError:
return False
else:
return ipaddress.ip_address(ip).is_global
def checkKeyFile(f):
if not os.path.isfile(KEYFILE):
return False
else:
return True
def getResponse(ip, test=False):
url = f"{URLBASE}/{ip}"
if not test:
with open(KEYFILE) as f:
access_key=f.readline().strip("\n")
if access_key.isalnum() and access_key.islower():
secret={'access_key': access_key}
else:
print ("The format of the access key is wrong")
sys.exit(EXIT["keyformat"])
else:
secret={}
r = requests.get(url, params=secret)
return dict(r.json())
def tuneOutput(response):
important=["latitude", "longitude"]
returns = []
for i in important:
returns.append(float(response[i]))
return returns
def printOutput(output):
print ("{lat:>12.6f} {long:>12.6f}".format(lat=output[0], long=output[1]))
if __name__ == "__main__":
if len(sys.argv) != 2:
print ("Exactly one argument is required.")
sys.exit (EXIT["arguments"])
ipAddress = sys.argv[1]
if not checkIP(ipAddress):
print ("Argument is not a valid, global IP address.")
sys.exit(EXIT["ip"])
if not checkKeyFile(KEYFILE):
print ("The access_key for the IPStack is missing. Should be: %s" %KEYFILE)
sys.exit(EXIT["keyfile"])
response = getResponse(ipAddress)
important = tuneOutput(response)
printOutput(important)