Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Function to display the help menu
- show_help() {
- echo "Usage: $0 [IP_ADDRESS]"
- echo " Retrieves geolocation information for a given IP address."
- echo ""
- echo "Options:"
- echo " -h, --help Show this help message and exit."
- echo ""
- echo "Examples:"
- echo " $0 8.8.8.8"
- echo " $0" # Gets the public IP address of the machine
- }
- # Function to geolocate an IP address
- geolocate_ip() {
- local ip="$1"
- local api_url="http://ip-api.com/json/$ip"
- # Fetch and parse the JSON data using curl and jq
- local response=$(curl -s "$api_url")
- local status=$(echo "$response" | jq -r '.status')
- if [ "$status" == "success" ]; then
- local country=$(echo "$response" | jq -r '.country')
- local region=$(echo "$response" | jq -r '.regionName')
- local city=$(echo "$response" | jq -r '.city')
- local lat=$(echo "$response" | jq -r '.lat')
- local lon=$(echo "$response" | jq -r '.lon')
- local isp=$(echo "$response" | jq -r '.isp')
- echo "Geolocation Information for $ip:"
- echo " Country: $country"
- echo " Region: $region"
- echo " City: $city"
- echo " Latitude: $lat"
- echo " Longitude: $lon"
- echo " ISP: $isp"
- else
- echo "Error: Could not retrieve geolocation information for $ip."
- echo " Reason: $(echo "$response" | jq -r '.message')"
- fi
- }
- # Main script logic
- # Check for help option
- if [[ "$1" == "-h" || "$1" == "--help" ]]; then
- show_help
- exit 0
- fi
- # Determine the IP address
- if [ -z "$1" ]; then
- # If no IP address is provided, get the public IP address
- ip=$(curl -s ipinfo.io/ip)
- else
- # Use the provided IP address
- ip="$1"
- fi
- # Geolocate the IP address
- geolocate_ip "$ip"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement