5 Life-Changing Python Scripts for Automation Bliss-Part 1
Attention all lazy people and efficiency junkies! Are you tired of wasting time on tedious tasks? Do you dream of a world where your computer does all the work for you? Look no further, because we have 5 Python scripts that will revolutionize your life and turn you into an automation superhero (or supervillain, depending on your motives). Get ready to say goodbye to manual labor and hello to infinite free time (or at least a few more hours in the day to procrastinate). Let the automation begin!
"Automation is not the enemy of the human worker, it is the ally. Automation liberates the worker from drudgery, giving him the opportunity to do more creative and rewarding work." - Robert Noyce
After reading this article, you will have a better understanding of many kind of python scripts which you can use to automate your daily boring tasks.
Python is a powerful language that is widely used for automating various tasks. Whether you’re a developer, system administrator, or just someone who wants to save time by automating mundane tasks, Python has you covered.
Here are 5 Python scripts that can help you automate various tasks:
Photo by Takahiro Sakamoto on Unsplash
1). File transfer script:
A file transfer script in Python is a set of instructions or a program that is written in the Python programming language and is used to automate the process of transferring files over a network or between computers.
Python provides several libraries and modules that can be used to create a file transfer script, such as socket, ftplib, smtplib, and paramiko, etc.
Here is an example of a simple file transfer script in Python that uses the socket module to transfer a file over the network:
import socket # create socket s = socket.socket() # bind socket to a address and port s.bind(('localhost', 12345)) # put the socket into listening mode s.listen(5) print('Server listening...') # forever loop to keep server running while True: # establish connection with client client, addr = s.accept() print(f'Got connection from {addr}') # receive the file name file_name = client.recv(1024).decode() try: # open the file for reading in binary with open(file_name, 'rb') as file: # read the file in chunks while True: chunk = file.read(1024) if not chunk: break # send the chunk to the client client.sendall(chunk) print(f'File {file_name} sent successfully') except FileNotFoundError: # if file not found, send appropriate message client.sendall(b'File not found') print(f'File {file_name} not found') # close the client connection client.close()
This script runs a server that listens for incoming connections on address localhost and port 12345. When a client connects, the server receives the file name from the client and then reads and sends the contents of the file in chunks to the client. If the file is not found, the server sends an appropriate message to the client.
As mentioned above, there are other libraries and modules that can be used to create file transfer script in python, such as ftplib to connect and transfer file using ftp protocol and paramiko for SFTP (SSH File Transfer Protocol) transfer.
The script can be tailored to match with specific requirement or scenario.
2). System monitoring script:
A system monitoring script is a type of Python script that is used to monitor the performance and status of a computer or network. The script can be used to track various metrics, such as CPU usage, memory usage, disk space, network traffic, and system uptime. The script can also be used to monitor certain events or conditions, such as the occurrence of an error or the availability of a specific service. For example:
import psutil # Get the current CPU usage cpu_usage = psutil.cpu_percent() # Get the current memory usage memory_usage = psutil.virtual_memory().percent # Get the current disk usage disk_usage = psutil.disk_usage("/").percent # Get the network activity # Get the current input/output data rates for each network interface io_counters = psutil.net_io_counters(pernic=True) for interface, counters in io_counters.items(): print(f"Interface {interface}:") print(f" bytes sent: {counters.bytes_sent}") print(f" bytes received: {counters.bytes_recv}") # Get a list of active connections connections = psutil.net_connections() for connection in connections: print(f"{connection.laddr} <-> {connection.raddr} ({connection.status})") # Print the collected data print(f"CPU usage: {cpu_usage}%") print(f"Memory usage: {memory_usage}%") print(f"Disk usage: {disk_usage}%")
This script uses the cpu_percent, virtual_memory, and disk_usage functions from the psutil module to retrieve the current CPU usage, memory usage, and disk usage, respectively. The virtual_memory function returns an object with various properties, such as the total amount of memory and the amount of used and free memory. The disk_usage function takes a path as an argument and returns an object with properties such as the total amount of space on the disk and the amount of used and free space.
3). Web scraping script (the most used):
This script can be used to extract data from websites and store it in a structured format, such as a spreadsheet or database. This can be useful for gathering data for analysis or for keeping track of changes on a website. For example:
import requests from bs4 import BeautifulSoup # Fetch a web page page = requests.get("http://www.example.com") # Parse the HTML content soup = BeautifulSoup(page.content, "html.parser") # Find all the links on the page links = soup.find_all("a") # Print the links for link in links: print(link.get("href"))
Here, you can see the powers of BeautifulSoup package. You can find any kind of dom objects using this package as I have shown how you can find all the links on the page. You can modify the script to scrape other types of data, or to navigate to different pages of the site. You can also use the find method to find a specific element, or the find_all method with additional arguments to filter the results.
4). Email automation script:
This script can be used to send emails automatically based on certain conditions. For example, you could use this script to send a daily report to your team or to send a reminder to yourself when an important deadline is approaching. Here’s an example of how to send an email using Python:
import smtplib from email.mime.text import MIMEText # Set the SMTP server and login credentials smtp_server = "smtp.gmail.com" smtp_port = 587 username = "your@email.com" password = "yourpassword" # Set the email parameters recipient = "recipient@email.com" subject = "Test email from Python" body = "This is a test email sent from Python." # Create the email message msg = MIMEText(body) msg["Subject"] = subject msg["To"] = recipient msg["From"] = username # Send the email server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(username, password) server.send_message(msg) server.quit()
This script uses the smtplib and email modules to send an email using the Simple Mail Transfer Protocol (SMTP). The SMTP class from the smtplib module is used to create an SMTP client, and the starttls and login methods are used to establish a secure connection and the MIMEText class from the email module is used to create an email message in the Multipurpose Internet Mail Extensions (MIME) format. The MIMEText constructor takes the body of the email as an argument, and you can use the __setitem__ method to set the subject, recipients, and sender of the email.
Once the email message is created, the send_message method of the SMTP object is used to send the email. The quit method is then called to close the connection to the SMTP server.
5). Password Manager script:
A password manager script is a type of Python script that is used to securely store and manage passwords. The script typically includes functions for generating random passwords, storing hashed passwords in a secure location (such as a database or file), and retrieving passwords when needed.
import secrets import string # Generate a random password def generate_password(length=16): characters = string.ascii_letters + string.digits + string.punctuation password = "".join(secrets.choice(characters) for i in range(length)) return password # Store a password in a secure way def store_password(service, username, password): # Use a secure hashing function to store the password hashed_password = hash_function(password) # Store the hashed password in a database or file with open("password_database.txt", "a") as f: f.write(f"{service},{username},{hashed_password}\n") # Retrieve a password def get_password(service, username): # Look up the hashed password in the database or file with open("password_database.txt") as f: for line in f: service_, username_, hashed_password_ = line.strip().split(",") if service == service_ and username == username_: # Use a secure hashing function to compare the stored password with the provided password if hash_function(password) == hashed_password_: return password return None
The generate_password function in the above example script generates a random password of a specified length, using a combination of letters, digits, and punctuation characters. The store_password function takes a service (such as a website or application), a username, and a password as inputs, and stores the hashed password in a secure location. The get_password function takes a service and a username as inputs, and retrieves the corresponding password if it is found in the secure storage location.
Conclusion
And there you have it, folks: 5 Python scripts to automate your life and become a productivity machine! Just make sure not to automate yourself out of a job, or you might end up spending all your time playing Minesweeper and eating Cheetos while your computer does all the work. Happy coding!