5個(gè)Python殺手級的自動化腳本分享
Python 是一種功能強(qiáng)大的語言,廣泛用于自動執(zhí)行各種任務(wù)。無論您是開發(fā)人員、系統(tǒng)管理員,還是只是想通過自動化日常任務(wù)來節(jié)省時(shí)間的人,Python 都能滿足您的需求。
這里有 5 個(gè) Python 腳本,可以幫助您自動執(zhí)行各種任務(wù)
1.文件傳輸腳本
Python 中的文件傳輸腳本是一組指令或用 Python 編程語言編寫的程序,用于自動化通過網(wǎng)絡(luò)或在計(jì)算機(jī)之間傳輸文件的過程。
Python 提供了幾個(gè)可用于創(chuàng)建文件傳輸腳本的庫和模塊,例如 socket、ftplib、smtplib和paramiko 等。
下面是一個(gè)簡單的 Python 文件傳輸腳本示例,它使用 socket 模塊通過網(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ù)器偵聽地址 localhost 和端口12345上的傳入連接。當(dāng)客戶端連接時(shí),服務(wù)器從客戶端接收文件名,然后讀取文件的內(nèi)容并將其以塊的形式發(fā)送給客戶端。如果找不到該文件,服務(wù)器將向客戶端發(fā)送適當(dāng)?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)控計(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: {memory_usage}%") print(f"Disk usage: {disk_usage}%")
該腳本使用 psutil 模塊中的 cpu_percent、virtual_memory 和 disk_usage 函數(shù)分別檢索當(dāng)前的 CPU 使用率、內(nèi)存使用率和磁盤使用率。virtual_memory 函數(shù)返回一個(gè)具有各種屬性的對象,例如內(nèi)存總量以及已用和空閑內(nèi)存量。disk_usage 函數(shù)將路徑作為參數(shù)并返回一個(gè)對象,該對象具有諸如磁盤上的總空間量以及已用和可用空間量等屬性。
3.Web 抓取腳本(最常用)
此腳本可用于從網(wǎng)站提取數(shù)據(jù)并將其存儲在結(jié)構(gòu)化格式中,例如電子表格或數(shù)據(jù)庫。這對于收集數(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 對象,因?yàn)槲乙呀?jīng)展示了如何找到頁面上的所有鏈接。您可以修改腳本以抓取其他類型的數(shù)據(jù),或?qū)Ш降秸军c(diǎn)的不同頁面。
您還可以使用 find 方法查找特定元素,或使用帶有附加參數(shù)的 find_all 方法來過濾結(jié)果。
4.電子郵件自動化腳本
此腳本可用于根據(jù)特定條件自動發(fā)送電子郵件。例如,您可以使用此腳本向您的團(tuán)隊(duì)發(fā)送每日報(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 和電子郵件模塊,通過簡單郵件傳輸協(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 對象的 send_message 方法發(fā)送電子郵件。然后調(diào)用 quit 方法關(guān)閉與 SMTP 服務(wù)器的連接。
5. 密碼管理器腳本
密碼管理器腳本是一種用于安全存儲和管理密碼的 Python 腳本。該腳本通常包括用于生成隨機(jī)密碼、將散列密碼存儲在安全位置(例如數(shù)據(jù)庫或文件)以及在需要時(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)符號的組合生成指定長度的隨機(jī)密碼。store_password 函數(shù)將服務(wù)(例如網(wǎng)站或應(yīng)用程序)、用戶名和密碼作為輸入,并將哈希后的密碼存儲在安全位置。get_password 函數(shù)將服務(wù)和用戶名作為輸入,如果在安全存儲位置找到相應(yīng)的密碼,則檢索相應(yīng)的密碼。
到此這篇關(guān)于5個(gè)Python殺手級的自動化腳本分享的文章就介紹到這了,更多相關(guān)Python自動化腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch sampler對數(shù)據(jù)進(jìn)行采樣的實(shí)現(xiàn)
今天小編就為大家分享一篇pytorch sampler對數(shù)據(jù)進(jìn)行采樣的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12Python 實(shí)現(xiàn)字符串中指定位置插入一個(gè)字符
下面小編就為大家分享一篇Python 實(shí)現(xiàn)字符串中指定位置插入一個(gè)字符,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05Python使用Mechanize模塊編寫爬蟲的要點(diǎn)解析
這篇文章主要介紹了Python使用Mechanize模塊編寫爬蟲的要點(diǎn)解析,作者還講解了Mechanize程序占用內(nèi)存過高問題的相關(guān)解決方法,需要的朋友可以參考下2016-03-03關(guān)于多種方式完美解決Python pip命令下載第三方庫的問題
這篇文章主要介紹了多種方式完美解決python pip命令下載第三方庫的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12django框架實(shí)現(xiàn)模板中獲取request 的各種信息示例
這篇文章主要介紹了django框架實(shí)現(xiàn)模板中獲取request 的各種信息,結(jié)合實(shí)例形式分析了Django框架模板直接獲取request信息的相關(guān)配置與操作技巧,需要的朋友可以參考下2019-07-07python編輯用戶登入界面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python編輯用戶登入界面的實(shí)現(xiàn)代碼,非常不錯(cuò),代碼簡單易懂,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-07-07使用python+whoosh實(shí)現(xiàn)全文檢索
今天小編就為大家分享一篇使用python+whoosh實(shí)現(xiàn)全文檢索,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12使用Pyinstaller的最新踩坑實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了最近在使用Pyinstaller的踩坑實(shí)戰(zhàn)記錄,主要介紹了PYTHON2X.DLL缺失和WINDOWS2003 32BIT提示程序無效這兩個(gè)問題的解決方法,文中給出了詳細(xì)的解決方法,需要的朋友們下面來一起看看吧。2017-11-11