Last active
August 29, 2015 14:24
-
-
Save dimfeld/983d48d9963cab4b7563 to your computer and use it in GitHub Desktop.
Linode IP Lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
import os | |
import os.path | |
import argparse | |
import json | |
import linode.api | |
key = None | |
def getArgs(): | |
parser = argparse.ArgumentParser(prog=sys.argv[0]) | |
parser.add_argument('--refresh', action='store_true', help="Contact the server to refresh the list") | |
parser.add_argument('-a', '--all', action='store_true', help="Print all hosts in the list") | |
parser.add_argument('-l', action='store_true', help="Display the host names along with the IPs") | |
parser.add_argument('names', nargs='*') | |
return parser.parse_args() | |
def getList(listPath, forceRefresh): | |
if not os.path.exists(listPath) or forceRefresh: | |
sys.stderr.write("Refreshing data...\n") | |
api = linode.api.Api(key=key) | |
nodeList = api.linode_list() | |
ipList = api.linode_ip_list() | |
rawIps = { x["LINODEID"]: x["IPADDRESS"] for x in ipList if x["ISPUBLIC"] } | |
ips = { x["LABEL"]: rawIps[x["LINODEID"]] for x in nodeList } | |
with open(listPath, "w") as f: | |
json.dump(ips, f) | |
else: | |
with open(listPath, "r") as f: | |
ips = json.load(f) | |
return ips | |
def printVerboseData(host, ip): | |
print "{0}\t{1}".format(host, ip) | |
def printSimpleData(host, ip): | |
print ip | |
def main(): | |
args = getArgs() | |
dataPath = os.path.expanduser('~/.lip.cache') | |
data = getList(dataPath, args.refresh) | |
if args.l: | |
printFunc = printVerboseData | |
else: | |
printFunc = printSimpleData | |
if args.all or len(args.names) == 0: | |
for host in sorted(data.iterkeys()): | |
printFunc(host, data[host]) | |
else: | |
for host in args.names: | |
printFunc(host, data[host]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment