1. rsvp
  2. gists

Commits

rsvp  committed a410dba Draft

Add ip2geo.sh to get geographic coordinates.

  • Participants
  • Parent commits 9fd87e9
  • Branches default

Comments (0)

Files changed (2)

File README.rst

View file
  • Ignore whitespace
 README for gists
 ================
 
-Introduction :: last update : 2012-06-16
+Introduction :: last update : 2012-06-17
 ========================================
 
 "Gists" are useful code snippets or short scripts, where documentation
 Short descriptions below are in reverse chronological order:
 
 
+ip2geo.sh
+=========
+
+given IP argument: get latitude, longitude, country, region, and locality.
+
+
 jason.sh
 ========
 

File ip2geo.sh

View file
  • Ignore whitespace
+#!/usr/bin/env bash
+#              bash 4.1.5(1)     Linux Ubuntu 10.04           Date : 2012-06-17
+#
+# _______________|  ip2geo : given IP, get latitude/longitude, country, locality.
+#
+#           Usage:  ip2geo
+#
+#        Examples:  % ip2geo  130.12.1.34%2C67.169.73.113
+#                   #         Officially IP arguments are expected as a list.
+#                   #         Commas instead of %2C will also work.
+#
+#                   % ip2geo  130.12.1.34,67.169.73.113
+#                   130.12.1.34 44.2332992554 -76.4832992554 CA ON Kingston
+#                   67.169.73.113 37.75870132 -122.438102722 US CA San Francisco
+#
+#                   % ip2geo friendfeed.com
+#                   friendfeed.com 37.3762016296 -122.182601929 US CA Palo Alto
+#
+#                   % ip2geo  `digy`
+#                   #         locates oneself :-)
+#
+#    Dependencies:  Data Science Toolkit API (see first entry in Change Log)
+#                   curl
+#                   Python json module
+
+
+#  CHANGE LOG  LATEST version available:   https://bitbucket.org/rsvp/gists/src
+# 
+#  2012-06-17  Use Python to filter the json data.
+#  2012-06-15  First version. Documentation from
+#                 http://www.datasciencetoolkit.org/developerdocs
+#                 API uses data from http://www.maxmind.com
+#  
+#  This API takes either a single numerical IP address, a comma-separated list, 
+#  or a JSON-encoded array of addresses, and returns a JSON object with a key 
+#  for every IP. The value for each key is either null if no information was 
+#  found, or an object containing location information, including country, 
+#  region, city and latitude/longitude coordinates. 
+#  
+#  To call the API, you can make either a GET or a POST request to
+#  /ip2coordinates. If you make a GET request, then you need to pass 
+#  in the IP addresses in the suffix of the URL, e.g. 
+#  /ip2coordinates/130.12.1.34%2C67.169.73.113
+#  
+#  Using GET you can also pass in a callback parameter in the URL, making it
+#  possible to run this as a JSONP cross-domain request. You can see this method
+#  in action if you view source on the home page of this server.
+#  
+#  You can also make a POST request passing in the IP addresses in the body of
+#  the request. This is useful if you have very large arrays of IP addresses you
+#  need to process, since you won't hit any URL size limits.
+
+
+#           _____ PREAMBLE_v2: settings, variables, and error handling.
+#
+LC_ALL=POSIX
+#      locale means "ASCII, US English, no special rules, 
+#      output per ISO and RFC standards." 
+#      Esp. use ASCII encoding for glob and sorting characters. 
+shopt -s   extglob
+#     ^set extended glob for pattern matching.
+shopt -s   failglob
+#         ^failed pattern matching signals error.
+set -e
+#   ^errors checked: immediate exit if a command has non-zero status. 
+set -u
+#   ^unassigned variables shall be errors.
+#    Example of default VARIABLE ASSIGNMENT:  arg1=${1:-'foo'}
+
+arg1=${1:-'NULL'}
+
+program=${0##*/}   #  similar to using basename
+#  tmpf=$( mktemp     /tmp/88_${program}_tmp.XXXXXXXXXX )
+memf=$( mktemp /dev/shm/88_${program}_tmp.XXXXXXXXXX )
+
+
+cleanup () {
+     #  Delete temporary files, then optionally exit given status.
+     local status=${1:-'0'}
+     rm -f $memf ${memf}.pdf ${memf}.jpg ${memf}.png ${memf}.html
+     [ $status = '-1' ] ||  exit $status      #  thus -1 prevents exit.
+} #--------------------------------------------------------------------
+warn () {
+     #  Message with basename to stderr.          Usage: warn "message"
+     echo -e "\n !!  ${program}: $1 "  >&2
+} #--------------------------------------------------------------------
+die () {
+     #  Exit with status of most recent command or custom status, after
+     #  cleanup and warn.      Usage: command || die "message" [status]
+     local status=${2:-"$?"}
+     cleanup -1  &&   warn "$1"  &&  exit $status
+} #--------------------------------------------------------------------
+trap "die 'SIG disruption, but cleanup finished.' 114" 1 2 3 15
+#    Cleanup after INTERRUPT: 1=SIGHUP, 2=SIGINT, 3=SIGQUIT, 15=SIGTERM
+#
+# _______________     ::  BEGIN  Script ::::::::::::::::::::::::::::::::::::::::
+
+
+convertor='http://www.datasciencetoolkit.org/ip2coordinates'
+#         ^IP addresses are sent here for conversion.
+
+case "$arg1" in 
+     'NULL')  die "IP list like 130.12.1.34,67.169.73.113 required." 113 ;;
+
+          *)  curl "$convertor/$arg1" > $memf  2> /dev/null \
+                 ||  die "invalid argument: $arg1"           115         ;;
+esac 
+
+
+#  #     Try to make json output readable (else plain cat):
+#  jason $memf 2> /dev/null  ||  cat $memf
+
+     #  #    sample output with indent set at 5 before sed:
+     #  {
+     #       "130.12.1.34": {
+     #            "area_code": 0, 
+     #            "country_code": "CA", 
+     #            "country_code3": "CAN", 
+     #            "country_name": "Canada", 
+     #            "dma_code": 0, 
+     #            "latitude": 44.233299255371101, 
+     #            "locality": "Kingston", 
+     #            "longitude": -76.483299255371094, 
+     #            "postal_code": "", 
+     #            "region": "ON"
+     #       }, 
+     #       "67.169.73.113": {
+     #            "area_code": 415, 
+     #            "country_code": "US", 
+     #            "country_code3": "USA", 
+     #            "country_name": "United States", 
+     #            "dma_code": 807, 
+     #            "latitude": 37.758701324462898, 
+     #            "locality": "San Francisco", 
+     #            "longitude": -122.438102722168, 
+     #            "postal_code": "94114", 
+     #            "region": "CA"
+     #       }
+     #  }
+
+
+#  Process the data in json using Python json module:
+#      First convert to Python representation,
+#      then print geographic coordinates on a single line.
+#      
+{ python <<EOHereDoc
+import json
+
+with open( "$memf", 'rb' ) as f:
+     #                ^binary 
+     data = json.loads( f.read() )
+     #           ^convert json string into its Python representation.
+
+for ip in data:
+     #    ^now is a Python dictionary.
+     print ip, data[ip]['latitude'], data[ip]['longitude'],                  \
+           data[ip]['country_code'], data[ip]['region'], data[ip]['locality']
+
+EOHereDoc
+}  
+
+
+
+cleanup
+# _______________ EOS ::  END of Script ::::::::::::::::::::::::::::::::::::::::
+
+#  vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=sh :