Python 是一種功能強(qiáng)大的語(yǔ)言,廣泛用于自動(dòng)執(zhí)行各種任務(wù)。無(wú)論您是開(kāi)發(fā)人員、系統(tǒng)管理員,還是只是想通過(guò)自動(dòng)化日常任務(wù)來(lái)節(jié)省時(shí)間的人,Python 都能滿足您的需求。
這里有 5 個(gè) Python 腳本,可以幫助您自動(dòng)執(zhí)行各種任務(wù)。
1.文件傳輸腳本
Python 中的文件傳輸腳本是一組指令或用 Python 編程語(yǔ)言編寫的程序,用于自動(dòng)化通過(guò)網(wǎng)絡(luò)或在計(jì)算機(jī)之間傳輸文件的過(guò)程。
Python 提供了幾個(gè)可用于創(chuàng)建文件傳輸腳本的庫(kù)和模塊,例如 socket、ftplib、smtplib和paramiko 等。
下面是一個(gè)簡(jiǎn)單的 Python 文件傳輸腳本示例,它使用 socket 模塊通過(guò)網(wǎng)絡(luò)傳輸文件:
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()
該腳本運(yùn)行一個(gè)服務(wù)器,該服務(wù)器偵聽(tīng)地址 localhost 和端口12345上的傳入連接。當(dāng)客戶端連接時(shí),服務(wù)器從客戶端接收文件名,然后讀取文件的內(nèi)容并將其以塊的形式發(fā)送給客戶端。如果找不到該文件,服務(wù)器將向客戶端發(fā)送適當(dāng)?shù)南ⅰ?/p>
如上所述,還有其他庫(kù)和模塊可用于在 python 中創(chuàng)建文件傳輸腳本,例如使用 ftp 協(xié)議連接和傳輸文件的ftplib和用于 SFTP(SSH 文件傳輸協(xié)議)傳輸?shù)膒aramiko 。
可以定制腳本以匹配特定要求或場(chǎng)景。
2.系統(tǒng)監(jiān)控腳本:
系統(tǒng)監(jiān)控是一種 Python 腳本,用于監(jiān)控計(jì)算機(jī)或網(wǎng)絡(luò)的性能和狀態(tài)。該腳本可用于跟蹤各種指標(biāo),例如 CPU 使用率、內(nèi)存使用率、磁盤空間、網(wǎng)絡(luò)流量和系統(tǒng)正常運(yùn)行時(shí)間。該腳本還可用于監(jiān)視某些事件或條件,例如錯(cuò)誤的發(fā)生或特定服務(wù)的可用性。例如:
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: 1.15MB%")
print(f"Disk usage: {disk_usage}%")
該腳本使用 psutil 模塊中的 cpu_percent、virtual_memory 和 disk_usage 函數(shù)分別檢索當(dāng)前的 CPU 使用率、內(nèi)存使用率和磁盤使用率。virtual_memory 函數(shù)返回一個(gè)具有各種屬性的對(duì)象,例如內(nèi)存總量以及已用和空閑內(nèi)存量。disk_usage 函數(shù)將路徑作為參數(shù)并返回一個(gè)對(duì)象,該對(duì)象具有諸如磁盤上的總空間量以及已用和可用空間量等屬性。
3.Web 抓取腳本(最常用)
此腳本可用于從網(wǎng)站提取數(shù)據(jù)并將其存儲(chǔ)在結(jié)構(gòu)化格式中,例如電子表格或數(shù)據(jù)庫(kù)。這對(duì)于收集數(shù)據(jù)進(jìn)行分析或跟蹤網(wǎng)站上的更改很有用。例如:
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"))
在這里,您可以看到 BeautifulSoup 包的強(qiáng)大功能。你可以使用這個(gè)包找到任何類型的 dom 對(duì)象,因?yàn)槲乙呀?jīng)展示了如何找到頁(yè)面上的所有鏈接。您可以修改腳本以抓取其他類型的數(shù)據(jù),或?qū)Ш降秸军c(diǎn)的不同頁(yè)面。
您還可以使用 find 方法查找特定元素,或使用帶有附加參數(shù)的 find_all 方法來(lái)過(guò)濾結(jié)果。
4.電子郵件自動(dòng)化腳本
此腳本可用于根據(jù)特定條件自動(dòng)發(fā)送電子郵件。例如,您可以使用此腳本向您的團(tuán)隊(duì)發(fā)送每日?qǐng)?bào)告,或者在重要的截止日期臨近時(shí)向您自己發(fā)送提醒。以下是如何使用 Python 發(fā)送電子郵件的示例:
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"
pd = "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()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"
pd = "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()
此腳本使用 smtplib 和電子郵件模塊,通過(guò)簡(jiǎn)單郵件傳輸協(xié)議 (SMTP) 發(fā)送電子郵件。smtplib 模塊中的 SMTP 類用于創(chuàng)建 SMTP 客戶端,starttls 和登錄方法用于建立安全連接,電子郵件模塊中的 MIMEText 類用于在多用途 Internet 郵件擴(kuò)展中創(chuàng)建電子郵件消息( MIME) 格式。MIMEText 構(gòu)造函數(shù)將電子郵件正文作為參數(shù),您可以使用 __setitem__ 方法設(shè)置電子郵件的主題、收件人和發(fā)件人。
創(chuàng)建電子郵件消息后,將使用 SMTP 對(duì)象的 send_message 方法發(fā)送電子郵件。然后調(diào)用 quit 方法關(guān)閉與 SMTP 服務(wù)器的連接。
5. 密碼管理器腳本
密碼管理器腳本是一種用于安全存儲(chǔ)和管理密碼的 Python 腳本。該腳本通常包括用于生成隨機(jī)密碼、將散列密碼存儲(chǔ)在安全位置(例如數(shù)據(jù)庫(kù)或文件)以及在需要時(shí)檢索密碼的功能。
import secrets
import string
# Generate a random password
def generate_password(length=16):
characters = string.ascii_letters + string.digits + string.punctuation
pd = "".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
上述示例腳本中的 generate_password 函數(shù)使用字母、數(shù)字和標(biāo)點(diǎn)符號(hào)的組合生成指定長(zhǎng)度的隨機(jī)密碼。store_password 函數(shù)將服務(wù)(例如網(wǎng)站或應(yīng)用程序)、用戶名和密碼作為輸入,并將哈希后的密碼存儲(chǔ)在安全位置。get_password 函數(shù)將服務(wù)和用戶名作為輸入,如果在安全存儲(chǔ)位置找到相應(yīng)的密碼,則檢索相應(yīng)的密碼。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-619610.html
結(jié)論
5 個(gè) Python 腳本來(lái)自動(dòng)化你的生活并成為一臺(tái)生產(chǎn)力機(jī)器!只要確保不要讓自己失業(yè),你就可能會(huì)把所有的時(shí)間都花在其他事情上,而你的電腦卻在做所有的工作。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-619610.html
到了這里,關(guān)于5個(gè)實(shí)用的自動(dòng)化Python腳本的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!