5個Python殺手級的自動化腳本分享
Python 是一種功能強大的語言,廣泛用于自動執(zhí)行各種任務。無論您是開發(fā)人員、系統(tǒng)管理員,還是只是想通過自動化日常任務來節(jié)省時間的人,Python 都能滿足您的需求。
這里有 5 個 Python 腳本,可以幫助您自動執(zhí)行各種任務
1.文件傳輸腳本
Python 中的文件傳輸腳本是一組指令或用 Python 編程語言編寫的程序,用于自動化通過網(wǎng)絡或在計算機之間傳輸文件的過程。
Python 提供了幾個可用于創(chuàng)建文件傳輸腳本的庫和模塊,例如 socket、ftplib、smtplib和paramiko 等。
下面是一個簡單的 Python 文件傳輸腳本示例,它使用 socket 模塊通過網(wǎng)絡傳輸文件:
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()
該腳本運行一個服務器,該服務器偵聽地址 localhost 和端口12345上的傳入連接。當客戶端連接時,服務器從客戶端接收文件名,然后讀取文件的內(nèi)容并將其以塊的形式發(fā)送給客戶端。如果找不到該文件,服務器將向客戶端發(fā)送適當?shù)南ⅰ?/p>
如上所述,還有其他庫和模塊可用于在 python 中創(chuàng)建文件傳輸腳本,例如使用 ftp 協(xié)議連接和傳輸文件的ftplib和用于 SFTP(SSH 文件傳輸協(xié)議)傳輸?shù)膒aramiko 。
可以定制腳本以匹配特定要求或場景。
2.系統(tǒng)監(jiān)控腳本
系統(tǒng)監(jiān)控是一種 Python 腳本,用于監(jiān)控計算機或網(wǎng)絡的性能和狀態(tài)。該腳本可用于跟蹤各種指標,例如 CPU 使用率、內(nèi)存使用率、磁盤空間、網(wǎng)絡流量和系統(tǒng)正常運行時間。該腳本還可用于監(jiān)視某些事件或條件,例如錯誤的發(fā)生或特定服務的可用性。例如:
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}%")
該腳本使用 psutil 模塊中的 cpu_percent、virtual_memory 和 disk_usage 函數(shù)分別檢索當前的 CPU 使用率、內(nèi)存使用率和磁盤使用率。virtual_memory 函數(shù)返回一個具有各種屬性的對象,例如內(nèi)存總量以及已用和空閑內(nèi)存量。disk_usage 函數(shù)將路徑作為參數(shù)并返回一個對象,該對象具有諸如磁盤上的總空間量以及已用和可用空間量等屬性。
3.Web 抓取腳本(最常用)
此腳本可用于從網(wǎng)站提取數(shù)據(jù)并將其存儲在結(jié)構(gòu)化格式中,例如電子表格或數(shù)據(jù)庫。這對于收集數(shù)據(jù)進行分析或跟蹤網(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 包的強大功能。你可以使用這個包找到任何類型的 dom 對象,因為我已經(jīng)展示了如何找到頁面上的所有鏈接。您可以修改腳本以抓取其他類型的數(shù)據(jù),或?qū)Ш降秸军c的不同頁面。
您還可以使用 find 方法查找特定元素,或使用帶有附加參數(shù)的 find_all 方法來過濾結(jié)果。
4.電子郵件自動化腳本
此腳本可用于根據(jù)特定條件自動發(fā)送電子郵件。例如,您可以使用此腳本向您的團隊發(fā)送每日報告,或者在重要的截止日期臨近時向您自己發(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 和電子郵件模塊,通過簡單郵件傳輸協(xié)議 (SMTP) 發(fā)送電子郵件。smtplib 模塊中的 SMTP 類用于創(chuàng)建 SMTP 客戶端,starttls 和登錄方法用于建立安全連接,電子郵件模塊中的 MIMEText 類用于在多用途 Internet 郵件擴展中創(chuàng)建電子郵件消息( MIME) 格式。MIMEText 構(gòu)造函數(shù)將電子郵件正文作為參數(shù),您可以使用 __setitem__ 方法設置電子郵件的主題、收件人和發(fā)件人。
創(chuàng)建電子郵件消息后,將使用 SMTP 對象的 send_message 方法發(fā)送電子郵件。然后調(diào)用 quit 方法關(guān)閉與 SMTP 服務器的連接。
5. 密碼管理器腳本
密碼管理器腳本是一種用于安全存儲和管理密碼的 Python 腳本。該腳本通常包括用于生成隨機密碼、將散列密碼存儲在安全位置(例如數(shù)據(jù)庫或文件)以及在需要時檢索密碼的功能。
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ù)字和標點符號的組合生成指定長度的隨機密碼。store_password 函數(shù)將服務(例如網(wǎng)站或應用程序)、用戶名和密碼作為輸入,并將哈希后的密碼存儲在安全位置。get_password 函數(shù)將服務和用戶名作為輸入,如果在安全存儲位置找到相應的密碼,則檢索相應的密碼。
到此這篇關(guān)于5個Python殺手級的自動化腳本分享的文章就介紹到這了,更多相關(guān)Python自動化腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch sampler對數(shù)據(jù)進行采樣的實現(xiàn)
今天小編就為大家分享一篇pytorch sampler對數(shù)據(jù)進行采樣的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12關(guān)于多種方式完美解決Python pip命令下載第三方庫的問題
這篇文章主要介紹了多種方式完美解決python pip命令下載第三方庫的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12django框架實現(xiàn)模板中獲取request 的各種信息示例
這篇文章主要介紹了django框架實現(xiàn)模板中獲取request 的各種信息,結(jié)合實例形式分析了Django框架模板直接獲取request信息的相關(guān)配置與操作技巧,需要的朋友可以參考下2019-07-07