ipinfo.sh 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/bin/bash
  2. #
  3. # Credit to http://ipinfo.io for providing the IP address info service. This script is a wrapper around their service, for convenience.
  4. #
  5. # Created by Niklas Berglund <niklas.berglund@gmail.com>
  6. # https://github.com/niklasberglund/ipinfo
  7. url="ipinfo.io"
  8. usage() {
  9. echo "Usage: $0 [-f field] [IP address]" 1>&2
  10. echo " -f field Only output specified field's info. Run script without -f to see available fields." 1>&2
  11. echo " -h Show this help text." 1>&2
  12. }
  13. while getopts "f:h" o; do
  14. case "${o}" in
  15. f)
  16. f=${OPTARG}
  17. ;;
  18. h)
  19. usage
  20. exit 0
  21. ;;
  22. *)
  23. usage
  24. exit 1
  25. ;;
  26. esac
  27. done
  28. shift $((OPTIND-1))
  29. # Simple IPv4/IPv6 check. Creds to http://stackoverflow.com/a/20423004/257577
  30. function is_valid_ip_address {
  31. echo $(echo "$*" | grep -Ec '^(([0-9a-f]{0,4}:){1,7}[0-9a-f]{1,4}|([0-9]{1,3}\.){3}[0-9]{1,3})$')
  32. }
  33. # Specified IP address
  34. if [ ! -z "$*" ]; then
  35. if [ $(is_valid_ip_address $*) -eq 0 ]; then
  36. echo "Error: The IP address must be in IPv4 or IPv6 format" 1>&2
  37. exit 1
  38. fi
  39. url="$url/$*"
  40. fi
  41. # Specified field
  42. if [ ! -z "$f" ]; then
  43. url="$url/$f"
  44. fi
  45. the_info=$(curl -s $url)
  46. if [[ $the_info == *"502 Bad Gateway"* || $the_info == "undefined" ]]; then
  47. echo "Error: Invalid endpoint. Perhaps you specified a non-existing field?"
  48. usage
  49. exit 1
  50. fi
  51. echo "$the_info" | sed -e '/[{}]/d' | sed 's/\"//g' | sed 's/ //g' | sed 's/,$//'