Posted on Leave a comment

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic.

import psutil

def monitor_network():
    # Get the network I/O statistics for all interfaces
    net_io_counters = psutil.net_io_counters(pernic=True)

    # Loop through each interface
    for interface, info in net_io_counters.items():
        print(f"Interface: {interface}")
        print(f"Bytes sent: {info.bytes_sent}")
        print(f"Bytes received: {info.bytes_recv}")
        print("\n")

# Continuously monitor network traffic every second
while True:
    monitor_network()
    time.sleep(1)

This script uses the psutil library to get the network I/O statistics for all network interfaces. It then loops through each interface and prints the number of bytes sent and received. The script continuously monitors the network traffic every second by using an infinite loop and the time.sleep function.

Posted on Leave a comment

Python Code Example with Classes

Here’s an example of a Python class that represents a rectangle:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

# Create a Rectangle object
rect = Rectangle(10, 20)

# Print the area and perimeter of the rectangle
print("Area:", rect.area())
print("Perimeter:", rect.perimeter())

In this example, the Rectangle class has two attributes width and height which are passed as arguments to the __init__ method when a new Rectangle object is created. The class also has two methods area and perimeter that return the area and perimeter of the rectangle, respectively.Regenerate response

Here’s another example of a Python class that represents a dog:

class Dog:
    def __init__(self, name, breed, age):
        self.name = name
        self.breed = breed
        self.age = age
    
    def bark(self):
        print("Woof!")
    
    def info(self):
        print("Name:", self.name)
        print("Breed:", self.breed)
        print("Age:", self.age)

# Create a Dog object
dog = Dog("Buddy", "Labrador", 5)

# Print the dog's information and make it bark
dog.info()
dog.bark()

In this example, the Dog class has three attributes name, breed, and age which are passed as arguments to the __init__ method when a new Dog object is created. The class also has two methods bark and info that make the dog bark and print its information, respectively.

Posted on Leave a comment

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.