pep-mklive/pmostools/peptools/pfetch.py

431 lines
15 KiB
Python

"""
* Author: "PeppermintOS Team(peppermintosteam@proton.me)
*
* License: SPDX-License-Identifier: GPL-3.0-or-later
*
* This is a neo / screen fetch type tool written for python
"""
import platform
import os
import socket
import subprocess
import psutil
def get_mem_info():
""" Get the Memory information """
try:
free_output = subprocess.check_output(['free', '-m'],
universal_newlines=True)
lines = free_output.split('\n')
total_memory = int(lines[1].split()[1])
used_memory = int(lines[1].split()[2])
memory_info = f"{used_memory}MiB / {total_memory}MiB"
return memory_info
except subprocess.CalledProcessError:
memory_info = 'Memory information not available'
return memory_info
def get_cpu_info():
""" Get the CPU INformation """
try:
lscpu_output= subprocess.check_output(['lscpu'],
universal_newlines=True)
cpu_info = ([line.split(":")[1].strip()
for line in lscpu_output.split("\n")
if "Model name" in line][0]
)
return cpu_info
except subprocess.CalledProcessError:
cpu_info = 'CPU information not available'
return cpu_info
def get_uptime_info():
""" This will get the Uptime of the system """
try:
with open('/proc/uptime', 'r', encoding='utf-8') as _:
uptime_seconds = float(_.readline().split()[0])
uptime_days = int(uptime_seconds // (24 * 3600))
uptime_seconds %= (24 * 3600)
uptime_hours = int(uptime_seconds // 3600)
uptime_seconds %= 3600
uptime_minutes = int(uptime_seconds // 60)
uptime_str = (
f"{uptime_days} days, "
f"{uptime_hours} hours, "
f"{uptime_minutes} mins"
)
return uptime_str
except FileNotFoundError:
uptime_str = 'Uptime information not available'
return uptime_str
def get_os_info():
""" Get the OS Information """
if os_name == 'Linux':
try:
with open('/etc/os-release', encoding='utf-8') as file:
for line in file:
if line.startswith('PRETTY_NAME'):
os_pretty_name = (
line.strip().split('=')[1].strip('"')
)
return os_pretty_name
return 'Unknown Linux Distribution'
except FileNotFoundError:
return 'Unknown Linux Distribution'
else:
return os_name
def get_package_info():
""" Get the package Information """
try:
package_count = subprocess.check_output(['dpkg', '--list'],
universal_newlines=True).count('\n')
package_count -= 5 # Adjust for header lines in the dpkg output
package_info = f"{package_count} packages installed"
return package_info
except subprocess.CalledProcessError:
return 'Failed to get package information (dpkg command failed)'
except FileNotFoundError:
return 'dpkg command not found'
except OSError as _:
return f'OS error: {_}'
def get_shell_info():
""" Get the Shell Information """
try:
version_output = subprocess.check_output(['bash', '--version'],
universal_newlines=True)
lines = version_output.split('\n')
for line in lines:
if line.startswith('GNU bash'):
version_parts = line.split()
if len(version_parts) >= 4:
shell_version = version_parts[3]
return shell_version
return 'Version not found'
except subprocess.CalledProcessError:
return 'Failed to get shell information (bash command failed)'
except FileNotFoundError:
return 'bash command not found'
except OSError as _:
return f'OS error: {_}'
def get_display_info():
""" Get the Display Resolution """
try:
xdpyinfo_output = subprocess.check_output(['xdpyinfo'],
universal_newlines=True)
resolutions = []
for line in xdpyinfo_output.split('\n'):
if 'dimensions:' in line:
parts = line.split()
if len(parts) >= 2:
resolution = parts[1]
resolutions.append(resolution)
resolution_info = ', '.join(resolutions)
return resolution_info
except subprocess.CalledProcessError:
return 'Failed to get display information (xdpyinfo command failed)'
except FileNotFoundError:
return 'xdpyinfo command not found'
except OSError as _:
return f'OS error: {_}'
def get_terminal_emulator():
""" Find the terminal being used """
current_process = psutil.Process(os.getpid())
while current_process:
parent = current_process.parent()
if parent is None:
break
current_process = parent
name = current_process.name().lower()
if any(term in name for term in ["gnome-terminal", "konsole",
"xterm", "xfce4-terminal", "lxterminal", "mate-terminal",
"tilix", "terminator", "alacritty", "kitty"]):
return current_process.name()
return "Terminal emulator not found"
def get_gpu_info():
try:
result = subprocess.run(['lspci', '-nnk', '|', 'grep', '-i', 'vga', '-A3'], capture_output=True, text=True, shell=True)
if result.returncode == 0:
gpu_info = ""
lines = result.stdout.split('\n')
for line in lines:
if 'VGA' in line:
gpu_info = line.split(':')[2].strip()
break
return gpu_info
except Exception as e:
return f"Erro: {e}"
return "Desconhecido"
def get_memory_info():
memory_info = {}
try:
mem = psutil.virtual_memory()
memory_info['Total'] = f"{mem.total / (1024 ** 3):.2f} GB"
memory_info['Available'] = f"{mem.available / (1024 ** 3):.2f} GB"
memory_info['Used'] = f"{mem.used / (1024 ** 3):.2f} GB"
memory_info['Free'] = f"{mem.free / (1024 ** 3):.2f} GB"
except Exception as e:
return f"Erro: {e}"
return memory_info
# Function to get the desktop environment
def get_desktop_environment():
try:
de = os.getenv('XDG_CURRENT_DESKTOP') or os.getenv('DESKTOP_SESSION') or 'Unknown'
return de.lower()
except Exception as e:
return f"DE info not available ({e})"
# Function to get the version of the desktop environment
def get_version(d_e):
commands = {
"gnome": ["gnome-shell", "--version"],
"kde-plasma": ["plasmashell", "--version"],
"xfce": ["xfce4-session", "--version"],
"lxde": ["lxpanel", "--version"],
"lxqt": ["lxqt-session", "--version"],
"cinnamon": ["cinnamon", "--version"],
"mate": ["mate-session", "--version"],
"unity": ["unity", "--version"],
"deepin": ["deepin", "--version"],
"pantheon": ["pantheon-session", "--version"],
"i3": ["i3", "--version"]
}
try:
output = subprocess.check_output(commands.get(d_e, ['echo', 'unknown version']), universal_newlines=True)
return output.strip().split('\n')[0].split()[-1] if d_e != 'xfce' else get_xfce_version()
except Exception as e:
return f"DE version info not available ({e})"
# Function to get XFCE version
def get_xfce_version():
try:
xfce_version = subprocess.check_output(['xfce4-session', '--version'], universal_newlines=True)
return xfce_version.split()[1]
except Exception as e:
return f"XFCE version info not available ({e})"
def get_xfce_version():
""" Get the xfce information """
components = ["xfce4-session", "xfwm4", "xfce4-panel",
"xfce4-settings"]
for component in components:
try:
output = subprocess.check_output([component, "--version"],
universal_newlines=True)
lines = output.strip().split("\n")
if lines:
version = lines[0].split()[-1]
version = version.strip('()')
return version
except (subprocess.CalledProcessError, FileNotFoundError):
continue
return "unknown version"
def get_window_manager():
""" Get the windows manager information """
try:
output = subprocess.check_output(['xprop', '-root',
'_NET_SUPPORTING_WM_CHECK'], universal_newlines=True)
if '_NET_SUPPORTING_WM_CHECK(WINDOW):' in output:
window_id = output.split()[-1]
wm_name_output = subprocess.check_output(['xprop', '-id',
window_id, '_NET_WM_NAME'], universal_newlines=True)
if '_NET_WM_NAME(UTF8_STRING)' in wm_name_output:
wm_name = wm_name_output.split('"')[1]
return wm_name
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "Unknown"
def get_xfwm4_theme():
""" Get the session theme """
try:
config_path = os.path.expanduser(
"~/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml"
)
if os.path.exists(config_path):
with open(config_path, 'r', encoding='utf-8') as file:
for line in file:
if 'name="theme"' in line:
theme = line.split('value="')[1].split('"')[0]
return theme
except FileNotFoundError:
pass
except OSError as _:
print(f"OS error: {_}")
return "Default"
def get_gnome_desktop_theme():
""" Get the gnome themse """
try:
output = subprocess.check_output(['gsettings', 'get',
'org.gnome.desktop.interface', 'gtk-theme'],
universal_newlines=True)
theme = output.strip().strip("'")
return theme
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "Unknown"
def get_gnome_icon_theme():
""" Get the icon theme """
try:
output = subprocess.check_output(['gsettings', 'get',
'org.gnome.desktop.interface', 'icon-theme'],
universal_newlines=True)
theme = output.strip().strip("'")
return theme
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "Unknown"
def get_xfce_icon_theme():
""" Get the icon theme """
try:
output = subprocess.check_output(['xfconf-query', '-c',
'xfce4-desktop', '-p', '/icons/icon-theme'],
universal_newlines=True)
theme = output.strip()
return theme
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "Unknown"
def get_kde_icon_theme():
""" Get the icon theme """
try:
output = subprocess.check_output(['kreadconfig5', '--get',
'kdeglobals', 'Icons'], universal_newlines=True)
theme = output.strip()
return theme
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "Unknown"
def print_user_and_hostname():
""" Get and print the host name """
username = os.getenv('USER')
# Get the hostname
hostname = os.uname().nodename
# Print the user and hostname
print(" ###-No system fetch application installed!-###")
print(" Peppermint's System Informtion Tool Will Be Used")
print("-" * len(f"{username}@{hostname}"))
print(f"{username}@{hostname}")
print("-" * len(f"{username}@{hostname}"))
def get_storage_info():
storage_info = {}
try:
disk = psutil.disk_usage('/')
storage_info['Total'] = f"{disk.total / (1024 ** 3):.2f} GB"
storage_info['Used'] = f"{disk.used / (1024 ** 3):.2f} GB"
storage_info['Free'] = f"{disk.free / (1024 ** 3):.2f} GB"
except Exception as e:
return f"Erro: {e}"
return storage_info
# These are the variables that run the functions
os_name = platform.system()
architecture = platform.machine()
hostname_information = socket.gethostname()
kernel_version = platform.release()
kernel_information = f"Kernel: {kernel_version}"
terminal_emulator = get_terminal_emulator()
desktop_environment = get_desktop_environment()
version_informtaion = get_version(desktop_environment)
window_manager_information = get_window_manager()
wm_theme = get_xfwm4_theme()
desktop_theme = get_gnome_desktop_theme()
desktop_environment = get_desktop_environment()
gpu_information = get_gpu_info()
mem_information = get_mem_info()
cpu_information = get_cpu_info()
uptime_string = get_uptime_info()
os_pretty = get_os_info()
os_full_information = f"{os_pretty} ({architecture})"
package_information = get_package_info()
shell_information = get_shell_info()
RESOLUTION_INFORMATION = get_display_info()
storage_information = get_storage_info()
# Determmine what Desktop evironment is being used
if desktop_environment == "gnome":
ICON_THEME = get_gnome_icon_theme()
elif desktop_environment == "xfce":
ICON_THEME = get_xfce_icon_theme()
elif desktop_environment == "kde-plasma":
ICON_THEME = get_kde_icon_theme()
else:
ICON_THEME = "Unknown"
#return ICON_THEME
# Setup the visual formats.
BOLD_START = "\033[1m"
BOLD_END = "\033[0m"
bold_os_text = f"{BOLD_START}OS{BOLD_END}:"
bold_host_text = f"{BOLD_START}Host:{BOLD_END}"
bold_kernel_text = f"{BOLD_START}Kernel:{BOLD_END}"
bold_uptime_text = f"{BOLD_START}Uptime:{BOLD_END}"
bold_packages_text = f"{BOLD_START}Packages:{BOLD_END}"
bold_shell_text = f"{BOLD_START}Shell:{BOLD_END}"
bold_resolution_text = f"{BOLD_START}Resolution:{BOLD_END}"
bold_cpu_text = f"{BOLD_START}CPU:{BOLD_END}"
bold_mem_text = f"{BOLD_START}Memory:{BOLD_END}"
bold_term_text = f"{BOLD_START}Terminal:{BOLD_END}"
bold_de_text = f"{BOLD_START}DE:{BOLD_END}"
bold_wm_text = f"{BOLD_START}WM:{BOLD_END}"
bold_wt_text = f"{BOLD_START}WM Theme:{BOLD_END}"
bold_dt_text = f"{BOLD_START}Theme:{BOLD_END}"
bold_ic_text = f"{BOLD_START}Icons:{BOLD_END}"
bold_gpu_text = f"{BOLD_START}GPU:{BOLD_END}"
bold_storage_text = f"{BOLD_START}Storage:{BOLD_END}"
# Print the OS name and architecture
print_user_and_hostname()
print(f"{bold_os_text} {os_full_information}")
print(f"{bold_host_text} {hostname_information}")
print(f"{bold_kernel_text} {kernel_information}")
print(f"{bold_uptime_text} {uptime_string}")
print(f"{bold_packages_text} {package_information}")
print(f"{bold_shell_text} {shell_information}")
print(f"{bold_resolution_text} {RESOLUTION_INFORMATION}")
print(f"{bold_de_text} {desktop_environment} {version_informtaion}")
print(f"{bold_wm_text} {window_manager_information}")
print(f"{bold_wt_text} {wm_theme}")
print(f"{bold_dt_text} {desktop_theme}")
print(f"{bold_ic_text} {ICON_THEME}")
print(f"{bold_term_text} {terminal_emulator}")
print(f"{bold_cpu_text} {cpu_information}")
print(f"{bold_gpu_text} {gpu_information}")
print(f"{bold_mem_text} {mem_information}")
print(f"{bold_storage_text} {storage_information}")