Collecting Linux System Data with Python and Sending Automated Email Reports
This tutorial demonstrates how to use Python's platform module and /proc filesystem to gather Linux system and hardware information, format it into a report, extend the script to send the report via SMTP email, add timestamps, and schedule periodic execution with cron.
Linux commands can show current system status, but a single command only provides a limited view. By using Python modules we can collect detailed information and generate a useful system report for administrators.
The report is divided into two parts: general system information obtained with the built‑in platform module, and hardware resources such as CPU and memory read from /proc files.
First, import the platform module and use its methods to retrieve OS details:
import platform
system = platform.system()
print(system)The script can also call platform.uname() to get a structured tuple containing hostname, kernel version, machine architecture, etc.
import platform
from pprint import pprint
uname = platform.uname()
pprint(uname)To extract hardware data we read /proc/cpuinfo and /proc/meminfo. Helper functions check_feature() and get_value_from_string() are defined to search for specific keywords and key‑value pairs.
def check_feature(feature, string):
if feature in string.lower():
return True
else:
return False
def get_value_from_string(key, string):
value = "NONE"
for line in string.split("
"):
if key in line:
value = line.split(":")[1].strip()
return valueThe main part of the script reads the CPU information, counts processors, detects virtualization support, extracts model name, MHz, and appends these details to a list:
cpu_features = []
with open('/proc/cpuinfo') as cpus:
cpu_data = cpus.read()
num_of_cpus = cpu_data.count("processor")
cpu_features.append("Number of Processors: {0}".format(num_of_cpus))
one_processor_data = cpu_data.split("processor")[1]
if check_feature("vmx", one_processor_data):
cpu_features.append("CPU Virtualization: enabled")
if check_feature("cpu_meltdown", one_processor_data):
cpu_features.append("Known Bugs: CPU Meltdown")
model_name = get_value_from_string("model name ", one_processor_data)
cpu_features.append("Model Name: {0}".format(model_name))
cpu_mhz = get_value_from_string("cpu MHz", one_processor_data)
cpu_features.append("CPU MHz: {0}".format(cpu_mhz))Memory information is processed in a similar way:
memory_features = []
with open('/proc/meminfo') as memory:
memory_data = memory.read()
total_memory = get_value_from_string("MemTotal", memory_data).replace("kB", "")
free_memory = get_value_from_string("MemFree", memory_data).replace("kB", "")
swap_memory = get_value_from_string("SwapTotal", memory_data).replace("kB", "")
total_memory_in_gb = "Total Memory in GB: {0}".format(int(total_memory) / 1024)
free_memory_in_gb = "Free Memory in GB: {0}".format(int(free_memory) / 1024)
swap_memory_in_gb = "SWAP Memory in GB: {0}".format(int(swap_memory) / 1024)
memory_features = [total_memory_in_gb, free_memory_in_gb, swap_memory_in_gb]All collected data is formatted into a readable report and printed to the console:
print("============System Information============")
print("""
System Type: {0}
Hostname: {1}
Kernel Version: {2}
System Version: {3}
Machine Architecture: {4}
Python version: {5}
""".format(
platform.system(),
platform.uname()[1],
platform.uname()[2],
platform.version(),
platform.machine(),
platform.python_version()))
print("============CPU Information============")
print("
".join(cpu_features))
print("============Memory Information============")
print("
".join(memory_features))To make the report actionable for an Operations Center, the script is extended to send the report via email using the built‑in smtplib library. After importing smtplib and platform, the same data is concatenated into a string variable Data_Sent_in_Email and sent through Gmail's SMTP server.
import smtplib
import platform
# ... (data collection code) ...
Data_Sent_in_Email = Header
Data_Sent_in_Email += "============System Information============"
Data_Sent_in_Email += "System Type: {0}
Hostname: {1}
Kernel Version: {2}
System Version: {3}
Machine Architecture: {4}
Python version: {5}
".format(
platform.system(), platform.uname()[1], platform.uname()[2],
platform.version(), platform.machine(), platform.python_version())
Data_Sent_in_Email += "============CPU Information============
" + "
".join(cpu_features)
Data_Sent_in_Email += "
============Memory Information============
" + "
".join(memory_features)
fromaddr = '[email protected]'
toaddrs = '[email protected]'
username = '[email protected]'
password = 'your_password'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, Data_Sent_in_Email)
server.quit()To record the exact time the data was generated, the datetime module is imported and the current timestamp is added to the email body:
from datetime import datetime
time_now = datetime.now()
time_now_string = time_now.strftime("%Y-%m-%d %H:%M:%S")
Data_Sent_in_Email += "====Time Now is {0}====
".format(time_now_string)Finally, the script can be scheduled to run automatically using Linux cron. Example crontab entries show how to run the script daily at 07:30, every Friday at 21:00, or every 5 minutes.
# View current crontab
crontab -l
# Edit crontab
crontab -e
# Run every Friday at 21:00
0 21 * * 5 /path/to/command
# Run daily at midnight
0 0 * * * /path/to/command
# Run every 5 minutes
*/5 * * * * /path/to/command
# Run daily at 07:30
30 7 * * * /usr/bin/python /root/Send_Email.pyBy combining Python's system‑information capabilities, email automation, timestamping, and cron scheduling, administrators can build a lightweight monitoring solution that periodically collects data, formats it, and notifies the team without manual intervention.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
