Last active
February 21, 2025 03:41
-
-
Save why-not/94108baece094f4b91dbe76fb1f62ae1 to your computer and use it in GitHub Desktop.
get system config (linux aws ec2)
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
import boto3 | |
import requests | |
import psutil | |
import subprocess | |
from tabulate import tabulate | |
from colorama import Fore, Style, init | |
# Initialize colorama for colored headers | |
init(autoreset=True) | |
# AWS Metadata Service IP | |
METADATA_SERVICE_IP = "http://169.254.169.254" | |
def get_instance_metadata(path): | |
"""Fetch metadata from AWS Metadata Service.""" | |
try: | |
response = requests.get(f"{METADATA_SERVICE_IP}/latest/meta-data/{path}", timeout=2) | |
return response.text | |
except requests.exceptions.RequestException: | |
return "Unavailable" | |
def get_instance_details(): | |
"""Retrieve instance ID, type, security groups, and region from metadata.""" | |
instance_id = get_instance_metadata("instance-id") | |
instance_type = get_instance_metadata("instance-type") | |
security_groups = get_instance_metadata("security-groups") | |
region = get_instance_metadata("placement/region") # Fetching region | |
return instance_id, instance_type, security_groups, region | |
def get_security_group_info(): | |
"""Fetch security group inbound (ingress) & outbound (egress) rules using AWS EC2 API.""" | |
try: | |
instance_id, _, _, region = get_instance_details() | |
if region == "Unavailable": | |
return [["Error Fetching Data", "Region could not be determined", "-", "-", "-"]], \ | |
[["Error Fetching Data", "Region could not be determined", "-", "-", "-"]] | |
ec2 = boto3.client("ec2", region_name=region) # Use the auto-detected region | |
# Get security groups attached to the instance | |
instance_details = ec2.describe_instances(InstanceIds=[instance_id]) | |
security_group_ids = [sg['GroupId'] for res in instance_details['Reservations'] for ins in res['Instances'] for sg in ins['SecurityGroups']] | |
# Fetch security group rules | |
security_groups = ec2.describe_security_groups(GroupIds=security_group_ids) | |
ingress_rules, egress_rules = [], [] | |
for sg in security_groups['SecurityGroups']: | |
sg_name = sg["GroupName"] | |
# Inbound (Ingress) rules | |
for rule in sg.get("IpPermissions", []): | |
protocol = rule.get("IpProtocol", "ALL") | |
from_port = rule.get("FromPort", "ALL") if "FromPort" in rule else "ALL" | |
to_port = rule.get("ToPort", "ALL") if "ToPort" in rule else "ALL" | |
for ip_range in rule.get("IpRanges", []): | |
ingress_rules.append([sg_name, protocol, from_port, to_port, ip_range["CidrIp"]]) | |
# Outbound (Egress) rules | |
for rule in sg.get("IpPermissionsEgress", []): | |
protocol = rule.get("IpProtocol", "ALL") | |
from_port = rule.get("FromPort", "ALL") if "FromPort" in rule else "ALL" | |
to_port = rule.get("ToPort", "ALL") if "ToPort" in rule else "ALL" | |
for ip_range in rule.get("IpRanges", []): | |
egress_rules.append([sg_name, protocol, from_port, to_port, ip_range["CidrIp"]]) | |
return ingress_rules if ingress_rules else [["No Inbound Rules Found", "-", "-", "-", "-"]], \ | |
egress_rules if egress_rules else [["No Outbound Rules Found", "-", "-", "-", "-"]] | |
except Exception as e: | |
return [["Error Fetching Data", str(e), "-", "-", "-"]], [["Error Fetching Data", str(e), "-", "-", "-"]] | |
def get_cpu_info(): | |
"""Get CPU details.""" | |
return { | |
"Physical Cores": psutil.cpu_count(logical=False), | |
"Total Cores": psutil.cpu_count(logical=True), | |
"Max Frequency (MHz)": psutil.cpu_freq().max, | |
"Current Frequency (MHz)": psutil.cpu_freq().current, | |
"CPU Usage (%)": psutil.cpu_percent(interval=1) | |
} | |
def get_memory_info(): | |
"""Get RAM details.""" | |
mem = psutil.virtual_memory() | |
return { | |
"Total Memory (MB)": mem.total // (1024 * 1024), | |
"Available Memory (MB)": mem.available // (1024 * 1024), | |
"Used Memory (MB)": mem.used // (1024 * 1024), | |
"Memory Usage (%)": mem.percent | |
} | |
def get_disk_info(): | |
"""Get Disk Space details.""" | |
disk = psutil.disk_usage('/') | |
return { | |
"Total Disk Space (GB)": disk.total // (1024 ** 3), | |
"Used Disk Space (GB)": disk.used // (1024 ** 3), | |
"Free Disk Space (GB)": disk.free // (1024 ** 3), | |
"Disk Usage (%)": disk.percent | |
} | |
def get_gpu_info(): | |
"""Get GPU details using nvidia-smi.""" | |
try: | |
result = subprocess.run(['nvidia-smi', '--query-gpu=name,memory.total,memory.used,memory.free', '--format=csv,noheader,nounits'], capture_output=True, text=True) | |
gpus = result.stdout.strip().split("\n") | |
return [gpu.split(", ") for gpu in gpus] if gpus else [["No GPU Found", "-", "-", "-"]] | |
except Exception: | |
return [["GPU Info Unavailable", "-", "-", "-"]] | |
def print_colored_title(title): | |
"""Print a colored title bar for better readability.""" | |
bar = "=" * (len(title) + 8) | |
print(Fore.CYAN + Style.BRIGHT + f"\n{bar}\n {title} \n{bar}" + Style.RESET_ALL) | |
def print_system_info(): | |
"""Print system information including CPU, Memory, Disk, GPU, and Security Groups.""" | |
instance_id, instance_type, security_groups, region = get_instance_details() | |
cpu_info = get_cpu_info() | |
memory_info = get_memory_info() | |
disk_info = get_disk_info() | |
gpu_info = get_gpu_info() | |
ingress_rules, egress_rules = get_security_group_info() | |
print_colored_title("System Information") | |
print(tabulate([ | |
["Instance ID", instance_id], | |
["Instance Type", instance_type], | |
["Region", region], | |
["Security Groups", security_groups] | |
], headers=["Metric", "Value"], tablefmt="grid")) | |
print_colored_title("CPU Information") | |
print(tabulate(cpu_info.items(), headers=["Metric", "Value"], tablefmt="grid")) | |
print_colored_title("Memory Information") | |
print(tabulate(memory_info.items(), headers=["Metric", "Value"], tablefmt="grid")) | |
print_colored_title("Disk Information") | |
print(tabulate(disk_info.items(), headers=["Metric", "Value"], tablefmt="grid")) | |
print_colored_title("GPU Information") | |
print(tabulate(gpu_info, headers=["GPU Name", "Total Memory (MB)", "Used Memory (MB)", "Free Memory (MB)"], tablefmt="grid")) | |
print_colored_title("Inbound Security Group Rules (Ingress)") | |
print(tabulate(ingress_rules, headers=["Security Group", "Protocol", "From Port", "To Port", "Allowed IP"], tablefmt="grid")) | |
print_colored_title("Outbound Security Group Rules (Egress)") | |
print(tabulate(egress_rules, headers=["Security Group", "Protocol", "From Port", "To Port", "Allowed IP"], tablefmt="grid")) | |
if __name__ == "__main__": | |
print_system_info() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment