社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

5 个用于自动化的杀手级 Python 脚本!

Python绿色通道 • 1 年前 • 160 次点击  

每天学Python新技能

后台回复【大礼包】送你Python自学大礼包

来源网络,侵删

Python 是一种功能强大的语言,广泛用于自动执行各种任务。无论您是开发人员、系统管理员,还是只是想通过自动化日常任务来节省时间的人,Python 都能满足您的需求。

这里有 5 个 Python 脚本,可以帮助您自动执行各种任务。

1.文件传输脚本

Python 中的文件传输脚本是一组指令或用 Python 编程语言编写的程序,用于自动化通过网络或在计算机之间传输文件的过程。

Python 提供了几个可用于创建文件传输脚本的库和模块,例如 socket、ftplib、smtplib和paramiko 等。

下面是一个简单的 Python 文件传输脚本示例,它使用 socket 模块通过网络传输文件:

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上的传入连接。当客户端连接时,服务器从客户端接收文件名,然后读取文件的内容并将其以块的形式发送给客户端。如果找不到该文件,服务器将向客户端发送适当的消息。

如上所述,还有其他库和模块可用于在 python 中创建文件传输脚本,例如使用 ftp 协议连接和传输文件的ftplib和用于 SFTP(SSH 文件传输协议)传输的paramiko 。

可以定制脚本以匹配特定要求或场景。

2.系统监控脚本:

系统监控是一种 Python 脚本,用于监控计算机或网络的性能和状态。该脚本可用于跟踪各种指标,例如 CPU 使用率、内存使用率、磁盘空间、网络流量和系统正常运行时间。该脚本还可用于监视某些事件或条件,例如错误的发生或特定服务的可用性。例如:

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 函数分别检索当前的 CPU 使用率、内存使用率和磁盘使用率。virtual_memory 函数返回一个具有各种属性的对象,例如内存总量以及已用和空闲内存量。disk_usage 函数将路径作为参数并返回一个对象,该对象具有诸如磁盘上的总空间量以及已用和可用空间量等属性。

3.Web 抓取脚本(最常用)

此脚本可用于从网站提取数据并将其存储在结构化格式中,例如电子表格或数据库。这对于收集数据进行分析或跟踪网站上的更改很有用。例如:

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 对象,因为我已经展示了如何找到页面上的所有链接。您可以修改脚本以抓取其他类型的数据,或导航到站点的不同页面。

您还可以使用 find 方法查找特定元素,或使用带有附加参数的 find_all 方法来过滤结果。

4.电子邮件自动化脚本

此脚本可用于根据特定条件自动发送电子邮件。例如,您可以使用此脚本向您的团队发送每日报告,或者在重要的截止日期临近时向您自己发送提醒。以下是如何使用 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"
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 和电子邮件模块,通过简单邮件传输协议 (SMTP) 发送电子邮件。smtplib 模块中的 SMTP 类用于创建 SMTP 客户端,starttls 和登录方法用于建立安全连接,电子邮件模块中的 MIMEText 类用于在多用途 Internet 邮件扩展中创建电子邮件消息( MIME) 格式。MIMEText 构造函数将电子邮件正文作为参数,您可以使用 __setitem__ 方法设置电子邮件的主题、收件人和发件人。

创建电子邮件消息后,将使用 SMTP 对象的 send_message 方法发送电子邮件。然后调用 quit 方法关闭与 SMTP 服务器的连接。

5. 密码管理器脚本

密码管理器脚本是一种用于安全存储和管理密码的 Python 脚本。该脚本通常包括用于生成随机密码、将散列密码存储在安全位置(例如数据库或文件)以及在需要时检索密码的功能。

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 函数使用字母、数字和标点符号的组合生成指定长度的随机密码。store_password 函数将服务(例如网站或应用程序)、用户名和密码作为输入,并将哈希后的密码存储在安全位置。get_password 函数将服务和用户名作为输入,如果在安全存储位置找到相应的密码,则检索相应的密码。

结论

伙计们,5 个 Python 脚本来自动化你的生活并成为一台生产力机器!只要确保不要让自己失业,你就可能会把所有的时间都花在其他事情上,而你的电脑却在做所有的工作。编码愉快!





    
  1. 清华最新发布的毕业生去向,太卷了吧!

  2. 常用统计检验Python代码!

  3. 没有年终奖的年轻人,挤满互联网


    Python社区是高质量的Python/Django开发社区
    本文地址:http://www.python88.com/topic/151982
     
    160 次点击