Skip to content

Instantly share code, notes, and snippets.

@ostechnix
Last active November 14, 2024 03:30
Show Gist options
  • Select an option

  • Save ostechnix/27276f43e980aa3a468c4b39680a68ee to your computer and use it in GitHub Desktop.

Select an option

Save ostechnix/27276f43e980aa3a468c4b39680a68ee to your computer and use it in GitHub Desktop.
Show IP Address - A Python Script to Show Private and Public IP Information in Linux and Unix.
#!/usr/bin/env python
# ------------------------------------------------------------------
# Script Name: showipaddr.py
# Description: A Python Script to display Private and
# Public IP address details in Linux and Unix.
# Website: https://gist.github.com/ostechnix
# Version: 1.0
# Usage: python showipaddr.py
# ------------------------------------------------------------------
import os
import requests
import subprocess
import sys
# Function to check if jq is installed
def check_jq_installed():
status = subprocess.call("type jq", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if status != 0:
os.system('clear')
print("It appears that 'jq' is not installed. Please install 'jq' package to run this script.\n")
print("You can usually install 'jq' using:\n")
print(" sudo apk add jq # On Alpine Linux")
print(" sudo pacman -S jq # On Arch Linux/EndeavourOS/Manjaro")
print(" sudo apt-get install jq # On Debian/Ubuntu")
print(" sudo yum install jq # On RedHat/CentOS")
print(" sudo dnf install jq # On Fedora")
print(" sudo zypper install jq # On SUSE/openSUSE")
print(" brew install jq # On macOS (with Homebrew)")
sys.exit()
# Function to get local IP and other details
def get_local_ip_details():
details = {
'Hostname': subprocess.getoutput("hostname"),
'Local IPv4 Address': subprocess.getoutput("hostname -I | awk '{print $1}'"),
'Local IPv6 Address': subprocess.getoutput("ip -6 addr show | grep 'inet6' | awk '{print $2}' | grep -v '^::1/' | head -n 1"),
'Router IP Address': subprocess.getoutput("ip route | grep default | awk '{print $3}'"),
'DNS Server': subprocess.getoutput("cat /etc/resolv.conf | grep nameserver | awk '{print $2}'")
}
return details
# Function to get public IP and details
def get_public_ip_details():
try:
response = requests.get('http://ip-api.com/json')
if response.status_code == 200:
return response.json()
else:
return None
except requests.RequestException:
return None
# Function to neatly format the IP information
def display_ip_info(local_ip_details, public_ip_info):
max_length = max(len(key) for key in local_ip_details.keys()) if local_ip_details else 0
max_length = max(max_length, 15) # Ensuring minimum length for public IP info labels
if local_ip_details:
print("Local IP Information:")
print('-' * (max_length + 30))
for key, value in local_ip_details.items():
print("{:<{width}} : {}".format(key, value, width=max_length))
print('-' * (max_length + 30))
if public_ip_info:
print("\nPublic IP Information:")
print('-' * (max_length + 30))
print("{:<{width}} : {}".format("IP Address", public_ip_info.get('query', 'N/A'), width=max_length))
print("{:<{width}} : {}".format("ISP", public_ip_info.get('isp', 'N/A'), width=max_length))
print("{:<{width}} : {}".format("City", public_ip_info.get('city', 'N/A'), width=max_length))
print("{:<{width}} : {}".format("Region", public_ip_info.get('regionName', 'N/A'), width=max_length))
print("{:<{width}} : {}".format("Country", public_ip_info.get('country', 'N/A'), width=max_length))
print("{:<{width}} : {}".format("Coordinates", f"{public_ip_info.get('lat', 'N/A')}, {public_ip_info.get('lon', 'N/A')}", width=max_length))
print('-' * (max_length + 30))
# Main function
def main():
check_jq_installed()
os.system('clear')
print("Select the information to display:")
print("1. Local IP")
print("2. Public IP")
print("3. Both Local and Public IP")
choice = input("Enter your choice (1/2/3): ")
local_ip_details = None
public_ip_info = None
if choice in ['1', '3']:
local_ip_details = get_local_ip_details()
if choice in ['2', '3']:
public_ip_info = get_public_ip_details()
display_ip_info(local_ip_details, public_ip_info)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment