Skip to content

Instantly share code, notes, and snippets.

@j6k4m8
Last active September 21, 2017 20:40
Show Gist options
  • Save j6k4m8/5f65ba374dffe7a7ab166b18b7be08c9 to your computer and use it in GitHub Desktop.
Save j6k4m8/5f65ba374dffe7a7ab166b18b7be08c9 to your computer and use it in GitHub Desktop.
Python: Get local, global, or router IP from the command line
#!/usr/bin/env python3
"""
Usage:
./ipinfo [router|local|global]
./ipinfo geo [ip]
For example, to get your OWN location:
./ipinfo geo $(ipinfo global)
"""
import sys
import subprocess
import json
import requests
if len(sys.argv) != 2 and sys.argv[1] != 'geo':
print("Usage: {} [router|local|global]".format(sys.argv[0]))
exit()
if sys.argv[1] == "router":
val = (subprocess.check_output(
"netstat -rn | grep default | awk -v N=2 '{print $N}'",
shell=True
)).decode("utf-8")
elif sys.argv[1] == "local":
val = (subprocess.check_output(
"ifconfig en0 | grep 'inet ' | awk -v N=2 '{print $N}'",
shell=True
)).decode("utf-8")
elif sys.argv[1] == "geo":
val = requests.get("https://freegeoip.net/json/{}".format(sys.argv[2])).json()
val = "{}: {} {}, {}".format(val['country_name'], val['city'], val['region_name'], val['zip_code'])
else:
val = json.loads(
subprocess.check_output(
"curl ipinfo.io -s", shell=True
).decode("utf-8")
)['ip']
print((val).strip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment