You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

206 lines
7.5 KiB

import operator
import os
import platform
import socket
import subprocess
import psutil
import matplotlib.pyplot as plt
from numpy.distutils import cpuinfo
import platform
import cpuinfo
threads_por_nucleo = psutil.cpu_count(logical=False)
memoria = psutil.virtual_memory()
def display_horizontal_bar(label, value, max_value=100, bar_length=20, color='\033[0m'):
percentage = (value / max_value) * 100
bar_fill_length = int(bar_length * (percentage / 100))
bar = f"{color}|" + '=' * bar_fill_length + ' ' * (bar_length - bar_fill_length) + f'{color}|'
print(f"{label} {bar} {percentage:.2f}%\033[0m")
def get_process_states():
# Get a list of all running processes
processes = psutil.process_iter(['pid', 'name', 'status'])
# Initialize counters for different process states
running_count = 0
sleeping_count = 0
other_count = 0
# Iterate through processes and count their states
for process in processes:
status = process.info['status'].lower()
if 'running' in status:
running_count += 1
elif 'sleeping' in status:
sleeping_count += 1
else:
other_count += 1
return running_count, sleeping_count, other_count
def get_container_info():
container_info = []
# Iterate through all running processes
for process in psutil.process_iter(['pid', 'name', 'cpu_percent']):
try:
# Extract information for each process
pid = process.info['pid']
name = process.info['name']
cpu_percent = process.info['cpu_percent']
# Append the information to the list
container_info.append({'pid': pid, 'name': name, 'cpu_percent': cpu_percent})
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return container_info
def display_top_containers(container_info, n=3):
# Sort the container_info list based on CPU percent
sorted_containers = sorted(container_info, key=operator.itemgetter('cpu_percent'), reverse=True)
# Display information for the top N containers
print(f"Top {n} containers by CPU usage:")
for i, container in enumerate(sorted_containers[:n], 1):
print(f"{i}. PID: {container['pid']}, Name: {container['name']}, CPU Usage: {container['cpu_percent']:.2f}%")
def get_running_processes():
# Using list comprehension to get information about all running processes
return [proc.info for proc in psutil.process_iter(['pid', 'name', 'username'])]
def get_tcp_connections():
connections = psutil.net_connections(kind='inet')
return connections
def get_cpu_info():
cpu_info = {}
# Get generic information about the CPU using platform
cpu_info['architecture'] = platform.architecture()
cpu_info['machine'] = platform.machine()
cpu_info['processor'] = platform.processor()
# Get detailed CPU information using cpuinfo
cpu_info.update(cpuinfo.get_cpu_info())
return cpu_info
def display_cpu_info(cpu_info):
print("CPU Information:")
print(f"Architecture: {cpu_info.get('architecture', 'N/A')}")
print(f"Machine: {cpu_info.get('machine', 'N/A')}")
print(f"Processor: {cpu_info.get('processor', 'N/A')}")
print(f"Brand: {cpu_info.get('brand_raw', 'N/A')}")
print(
f"Model: {cpu_info.get('brand_raw', 'N/A')} {cpu_info.get('family', 'N/A')} {cpu_info.get('model', 'N/A')} ({cpu_info.get('arch', 'N/A')})")
# Check if the key 'hz_advertised_raw' exists before accessing it
if 'hz_advertised_raw' in cpu_info:
clock_speed_ghz = cpu_info['hz_advertised_raw'][0] / 1e6
print(f"Clock Speed: {clock_speed_ghz:.2f} GHz")
else:
print("Clock Speed: N/A")
print(f"Cores: {cpu_info.get('count', 'N/A')}")
def procesesRunning():
# Get and print information about all running processes
running_processes = get_running_processes()
# Print the information without a separate loop
print("\n".join([f"PID: {process['pid']}, Name: {process['name']}, User: {process['username']}" for process in running_processes]))
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = str(battery.percent)
plugged = "Plugged In" if plugged else "Not Plugged In"
ans=True
while ans:
print("""
1. Hilos por nucleo
2. Memoria Total, Memoria Diponible y Porcentaje de memoria utilizada
3. Modulo OS
4. Informacion sobre drives en el sistema
5. El estado de bateria
6. Procesos activados
7. El uso del CPU, memoria y swap
8. Lista de connecciones TPC
9. Temperatura
10. Socket info
11. Modulo de plataforma
12. Numero de precesos activos,dormidos y otros
13. Mostar Contenedores sorteados por CPU
14. Informacion del CPU
0.Salir
""")
ans=input("Elige que tipo de informacio deseas saber:")
if ans=="1":
print(f"Tu procesador tiene {threads_por_nucleo} hilos por núcleo.")
elif ans=="2":
print(f"Memoria total: {memoria.total} bytes")
print(f"Memoria disponible: {memoria.available} bytes")
print(f"Porcentaje de memoria utilizada: {memoria.percent}%")
elif ans=="3":
cpu_count = os.cpu_count()
print(f"CPU Count: {cpu_count}")
current_directory = os.getcwd()
print(f"Current Directory: {current_directory}")
elif ans == "4":
result = subprocess.run(['powershell', 'Get-PSDrive'], stdout=subprocess.PIPE, text=True)
print(result.stdout)
elif ans == "5":
print(percent+'% | '+plugged)
elif ans == "6":
procesesRunning()
elif ans == "7":
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
swap_info = psutil.swap_memory()
display_horizontal_bar('CPU', cpu_usage, color='\033[91m')
display_horizontal_bar('Memoria', memory_info.percent, color='\033[94m')
display_horizontal_bar('Swap', swap_info.percent, color='\033[92m')
elif ans =="8":
if __name__ == "__main__":
tcp_connections = get_tcp_connections()
for connection in tcp_connections:
print(f"Local Address: {connection.laddr}")
print(f"Remote Address: {connection.raddr}")
print(f"Status: {connection.status}")
print("-----------------------------------")
elif ans=="9":
try:
temperatures = psutil.sensors_temperatures()
print("Temperatura:")
for name, entries in temperatures.items():
for entry in entries:
print(f"{name}: {entry.label} - {entry.current}°C")
except AttributeError:
print("la informacion sobre temeratura no esta disponible ens ete sitema")
elif ans == "10":
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
elif ans == "11":
system_info = platform.system()
release_info = platform.release()
print(f"System: {system_info}")
print(f"Release: {release_info}")
elif ans == "12":
running, sleeping, other = get_process_states()
print(f"Processos activos: {running}")
print(f"procesos dormiendo: {sleeping}")
print(f"Otros procesos: {other}")
elif ans =="13":
container_info = get_container_info()
display_top_containers(container_info)
elif ans =="14":
cpu_info = get_cpu_info()
display_cpu_info(cpu_info)
elif ans =="0":
print("\n Adios")
ans = None
else:
print("\n no es una pocion valida")

Powered by INFORMATICA.FP.EDU.ES.