Playbooks

Python Script Example for System Administrators

Here’s a Python script to monitor disk usage on a system and send an email alert if the usage exceeds a threshold.

import psutil
import smtplib
from email.mime.text import MIMEText

# Set threshold for disk usage (in %)
threshold = 80

# Get disk usage statistics using psutil
disk_usage = psutil.disk_usage('/')

# Check if usage exceeds threshold
if disk_usage.percent >= threshold:
    # Send email alert
    msg = MIMEText("Disk usage on the system has exceeded {}%.".format(threshold))
    msg['Subject'] = "Disk Usage Alert"
    msg['From'] = "system-admin@example.com"
    msg['To'] = "admin@example.com"

    s = smtplib.SMTP('localhost')
    s.send_message(msg)
    s.quit()

This script uses the psutil library to retrieve disk usage statistics, and the smtplib library to send an email via the local SMTP server. The MIMEText class from the email library is used to construct the email message.

Here’s another example of a Python script for system administrators, this one logs system performance statistics to a file:

import time
import psutil

# Set the log file path
log_file = "/var/log/system_stats.log"

# Open the log file for writing
with open(log_file, "a") as f:
    while True:
        # Get system performance statistics using psutil
        cpu_percent = psutil.cpu_percent(interval=1)
        memory_usage = psutil.virtual_memory().percent
        disk_io_counters = psutil.disk_io_counters()
        network_io_counters = psutil.net_io_counters()
        
        # Write the statistics to the log file
        f.write("{}: CPU: {}%, Memory: {}%, Disk Reads: {}, Disk Writes: {}, Network Sent: {}, Network Received: {}\n".format(
            time.strftime("%Y-%m-%d %H:%M:%S"),
            cpu_percent,
            memory_usage,
            disk_io_counters.read_count,
            disk_io_counters.write_count,
            network_io_counters.bytes_sent,
            network_io_counters.bytes_recv
        ))
        f.flush()
        
        # Sleep for 1 minute before getting the next set of statistics
        time.sleep(60)

This script uses the psutil library to retrieve system performance statistics and logs them to a file at regular intervals. The statistics logged include CPU usage, memory usage, disk I/O, and network I/O. The time library is used to format the current time and to add a sleep between logging intervals.

Here’s another example of a Python script for system administrators, this one is a script to monitor the availability of a remote website:

import requests
import smtplib
from email.mime.text import MIMEText

# Set the URL to monitor
url = "https://www.example.com"

# Set the email addresses for sending the alert
from_address = "system-admin@example.com"
to_address = "admin@example.com"

while True:
    try:
        # Make a request to the URL
        response = requests.get(url, timeout=10)
        
        # Check if the response is successful (status code 200)
        if response.status_code != 200:
            raise Exception("Website returned a non-200 status code: {}".format(response.status_code))
    except Exception as e:
        # If the request fails, send an email alert
        msg = MIMEText("The website {} is down. Error: {}".format(url, str(e)))
        msg['Subject'] = "Website Down Alert"
        msg['From'] = from_address
        msg['To'] = to_address

        s = smtplib.SMTP('localhost')
        s.send_message(msg)
        s.quit()
        
    # Sleep for 1 minute before checking the website again
    time.sleep(60)

This script uses the requests library to make a request to a specified URL and check if the response is successful. If the request fails or the response status code is not 200, the script sends an email alert via the local SMTP server, indicating that the website is down. The time library is used to add a sleep between checks.

Here’s another example of a Python script for system administrators, this one is a script to monitor the uptime of a remote server:

import paramiko
import smtplib
from email.mime.text import MIMEText

# Set the server information
server_hostname = "example.com"
server_username = "admin"
server_password = "secret"

# Set the email addresses for sending the alert
from_address = "system-admin@example.com"
to_address = "admin@example.com"

while True:
    try:
        # Connect to the remote server using SSH
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(server_hostname, username=server_username, password=server_password)
        
        # Execute the uptime command on the remote server
        stdin, stdout, stderr = ssh.exec_command("uptime")
        
        # Read the output of the command
        uptime = stdout.read().strip().decode("utf-8")
        
        # Check if the uptime is less than 10 minutes
        if "min" in uptime and int(uptime.split(" ")[-2].strip(",")) < 10:
            raise Exception("Uptime is less than 10 minutes: {}".format(uptime))
    except Exception as e:
        # If the connection fails or the uptime is less than 10 minutes, send an email alert
        msg = MIMEText("The server {} is down. Error: {}".format(server_hostname, str(e)))
        msg['Subject'] = "Server Down Alert"
        msg['From'] = from_address
        msg['To'] = to_address

        s = smtplib.SMTP('localhost')
        s.send_message(msg)
        s.quit()
        
    # Sleep for 1 minute before checking the server again
    time.sleep(60)

This script uses the paramiko library to connect to a remote server via SSH and execute the uptime command. The output of the command is parsed to check if the uptime is less than 10 minutes. If the connection fails or the uptime is less than 10 minutes, an email alert is sent via the local SMTP server, indicating that the server is down. The time library is used to add a sleep between checks.

PyJoy

Recent Posts

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic. import psutil def monitor_network(): #…

2 years ago

Python Script for Web Scraping

Here's a basic example of web scraping in Python using the requests and BeautifulSoup libraries:…

2 years ago

Python Script to SSH and Run Commands

Here's an example of how you can use Python to SSH into a remote server…

2 years ago

Python Code Example with Classes

Here's an example of a Python class that represents a rectangle: class Rectangle: def __init__(self,…

2 years ago

Python Script Example with Main Method in Active Directory

Here is a simple Python script that interacts with Active Directory (AD) using the pyad…

2 years ago

How to Run a Python Script on Mac

Running a Python script on a Mac is a relatively straightforward process that can be…

2 years ago