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 Script for Web Scraping

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

import requests
from bs4 import BeautifulSoup

# Make a request to the website
url = "https://www.example.com"
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.content, "html.parser")

# Find all the elements with a specific tag
elements = soup.find_all("tag_name")

# Extract the desired information from the elements
for element in elements:
    info = element.text
    print(info)

This script makes a GET request to the specified URL using the requests.get() function, then parses the HTML content of the page using the BeautifulSoup library. The soup.find_all() method is used to search for all elements with a specific tag name, and the desired information can be extracted from these elements using the element.text property.

Note that this is just a basic example, and the actual code will vary depending on the website and the information you want to extract.

Here’s another example of web scraping in Python using the requests and BeautifulSoup libraries:

import requests
from bs4 import BeautifulSoup

# Make a request to the website
url = "https://www.example.com/products"
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.content, "html.parser")

# Find all the product elements
products = soup.find_all("div", class_="product")

# Extract the desired information from the products
for product in products:
    name = product.find("h3").text
    price = product.find("span", class_="price").text
    rating = product.find("span", class_="rating").text

    # Print the information
    print(f"Name: {name}")
    print(f"Price: {price}")
    print(f"Rating: {rating}")

In this example, the script makes a GET request to a URL that lists products and parses the HTML content to extract information about each product. The soup.find_all() method is used to search for all elements within the class product, and the product.find() method is used to search for specific elements within each product (e.g., the product name, price, and rating). The extracted information is then printed to the console.

Posted on Leave a comment

Python Script to SSH and Run Commands

Here’s an example of how you can use Python to SSH into a remote server and run commands.

import paramiko

# create an SSH client object
ssh = paramiko.SSHClient()

# automatically add the remote server's SSH key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect to the remote server
ssh.connect(hostname='hostname', username='username', password='password')

# run a command on the remote server
stdin, stdout, stderr = ssh.exec_command('ls')

# print the output of the command
print(stdout.read().decode())

# close the SSH connection
ssh.close()

This code uses the paramiko library to handle the SSH connection. The paramiko.SSHClient object is created to handle the connection, and the set_missing_host_key_policy method is used to automatically add the remote server’s SSH key to the client’s known_hosts file. The connect method is used to connect to the remote server, and the exec_command method is used to run a command on the remote server. The output of the command is printed using the stdout.read().decode() method. Finally, the close method is used to close the SSH connection.

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 with Main Method in Active Directory

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

import pyad

def main():
    # Connect to the local Active Directory
    pyad.set_defaults(ldap_server="localhost")

    # Search for a user with the username "john.doe"
    user = pyad.aduser.ADUser.from_cn("john.doe")

    # Print the user's distinguished name (DN)
    print("User DN:", user.dn)

    # Print the user's email address
    print("Email:", user.get_attribute("mail"))

if __name__ == "__main__":
    main()

Note that in this example, the pyad library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install pyad

Here is another example of a Python script that interacts with Active Directory (AD) using the ldap3 library:

from ldap3 import Server, Connection, ALL

def main():
    # Connect to the local Active Directory server
    server = Server("localhost", get_info=ALL)
    connection = Connection(server, auto_bind=True)

    # Search for a user with the username "john.doe"
    connection.search("dc=example,dc=com", "(cn=john.doe)", attributes=["dn", "mail"])

    # Get the search results
    results = connection.response

    # Print the user's distinguished name (DN) and email address
    if results:
        user = results[0]
        print("User DN:", user["dn"])
        print("Email:", user["attributes"]["mail"])
    else:
        print("User not found.")

if __name__ == "__main__":
    main()

Note that in this example, the ldap3 library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install ldap3
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.

Posted on Leave a comment

How to Run a Python Script on Mac

Running a Python script on a Mac is a relatively straightforward process that can be accomplished in several ways. In this article, we will explore the different methods of running a Python script on a Mac, including using the terminal, the Python launcher, and running the script through an IDE.

  1. Running a Python script in the terminal: A terminal is a powerful tool that provides access to the underlying Unix system that powers a Mac. To run a Python script in the terminal, follow these steps:
  • Open the terminal by searching for it in Spotlight (press Cmd + Space) or by going to the Applications folder and selecting Utilities then Terminal.
  • Change to the directory where your script is located using the cd command. For example, if your script is located in the Documents folder, you would type cd ~/Documents.
  • To run your script, simply type python3 followed by the name of your script, for example, python3 myscript.py. The script will then run and produce any output it generates.
  1. Running a Python script using the Python launcher: The Python launcher is a tool that provides an easy way to run Python scripts on a Mac. To run a Python script using the Python launcher, follow these steps:
  • Right-click on your script file in the Finder and select Open With then Python Launcher.
  • The Python launcher will automatically run your script and produce any output it generates.
  1. Running a Python script through an IDE: An Integrated Development Environment (IDE) is a software application that provides a comprehensive environment for developing and running Python scripts. There are several popular IDEs available for Python on the Mac, including PyCharm, Spyder, and Visual Studio Code. To run a Python script through an IDE, follow these steps:
  • Launch your IDE and open the script file.
  • Depending on the IDE you are using, you may need to set the interpreter for your script by going to the Preferences or Settings menu and selecting Python Interpreter.
  • To run your script, use the Run or Execute command in the IDE, or press the Cmd + R keyboard shortcut. The script will then run and produce any output it generates.

In conclusion, running a Python script on a Mac can be done in several ways, including using the terminal, the Python launcher, or an IDE. Each method has its own advantages, so you may want to experiment with each one to see which works best for you. Whether you’re a beginner or an experienced Python developer, running your scripts on a Mac is a simple and straightforward process that provides a wealth of opportunities for exploring the power of Python.

Posted on Leave a comment

How to Make Python Script Executable

Making a Python script executable allows you to run it directly from the terminal or command line without having to invoke the Python interpreter. This is a useful feature for distributing your scripts to others, or for making your scripts easier to run without having to remember the commands necessary to invoke the interpreter.

To make a Python script executable, you need to add a shebang line at the beginning of your script, specify the file permissions to be executable, and then make the script file itself executable.

Here are the steps in detail:

  1. Add a shebang line: A shebang line is a special line at the beginning of a script that specifies the location of the interpreter for the script. In the case of Python, the shebang line should be as follows:
#!/usr/bin/env python3

This shebang line specifies that the script should be run with the Python interpreter located at /usr/bin/env python3. Note that the shebang line should be the first line in your script file, with no leading whitespace.

  1. Make the script file executable: After adding the shebang line, you need to make the script file itself executable by changing its file permissions. To do this, use the chmod command in the terminal, followed by the desired permissions and the name of the file. For example:
$ chmod +x script_file.py

This command sets the execute permission for the script file, allowing it to be executed as a standalone program.

  1. Run the script: Now that the script file is executable, you can run it from the terminal by simply typing its name, followed by any arguments that you need to pass to it. For example:
$ ./script_file.py

This will run the script and produce any output it generates. Note that you may need to use ./ in front of the script name if it is not located in one of the directories listed in your PATH environment variable.

It’s important to note that making a script file executable does not make it run faster, but it does make it easier to run and distribute. You should also be careful when making a script file executable, especially if it contains sensitive information or system commands, as executing it can have unintended consequences.

In conclusion, making a Python script executable involves adding a shebang line at the beginning of the script, specifying the file permissions to be executable, and then making the script file itself executable. This process makes it easier to run and distribute Python scripts and can be done with a few simple steps.

Posted on Leave a comment

How to Run Python Code in Terminal

To run Python code in the terminal, follow these steps.

  1. Open your terminal.
  2. Type python or python3 to start the Python interpreter.
  3. Type your Python code in the terminal and press Enter to run it.

For example, to print “Hello, World!” in Python, type the following in the terminal:

python3
>>> print("Hello, World!")
Hello, World!

Alternatively, you can also run a Python script saved in a file by typing python3 file_name.py in the terminal, where file_name.py is the name of the Python file you want to run.

Here is an example of executing Python on the command line to start the Python interpreter:

$ python3
Python 3.9.0 (default, Oct  5 2021, 14:01:47) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

In this example, $ represents the terminal prompt and python3 is the command to start the Python interpreter. After you run this command, you’ll see the Python prompt (>>>) indicating that the interpreter is ready to accept your commands.

You can type Python code at the prompt and press Enter to run it. For example:

>>> print("Hello, World!")
Hello, World!
>>> 

You can exit the Python interpreter by typing exit() or quit() at the prompt, or by pressing Ctrl + D.

Posted on Leave a comment

Python Script that shows how to use a Hash

Here is a simple example of how to use a hash in Python. This is useful when parsing large amounts of data.

# Define a hash table
hash_table = {}

# Add key-value pairs to the hash table
hash_table["key1"] = "value1"
hash_table["key2"] = "value2"
hash_table["key3"] = "value3"

# Access values in the hash table using keys
print(hash_table["key1"]) # Output: value1
print(hash_table["key2"]) # Output: value2
print(hash_table["key3"]) # Output: value3

# Check if a key is in the hash table
if "key1" in hash_table:
    print("key1 is in the hash table") # Output: key1 is in the hash table

# Delete a key-value pair from the hash table
del hash_table["key1"]

# Check if a key is in the hash table
if "key1" not in hash_table:
    print("key1 is not in the hash table") # Output: key1 is not in the hash table