当前位置:   article > 正文

5个实用的自动化Python脚本_python自动化脚本

python自动化脚本

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

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

1.文件传输脚本

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

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

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

  1. import socket
  2. # create socket
  3. s = socket.socket()
  4. # bind socket to a address and port
  5. s.bind(('localhost', 12345))
  6. # put the socket into listening mode
  7. s.listen(5)
  8. print('Server listening...')
  9. # forever loop to keep server running
  10. while True:
  11. # establish connection with client
  12. client, addr = s.accept()
  13. print(f'Got connection from {addr}')
  14. # receive the file name
  15. file_name = client.recv(1024).decode()
  16. try:
  17. # open the file for reading in binary
  18. with open(file_name, 'rb') as file:
  19. # read the file in chunks
  20. while True:
  21. chunk = file.read(1024)
  22. if not chunk:
  23. break
  24. # send the chunk to the client
  25. client.sendall(chunk)
  26. print(f'File {file_name} sent successfully')
  27. except FileNotFoundError:
  28. # if file not found, send appropriate message
  29. client.sendall(b'File not found')
  30. print(f'File {file_name} not found')
  31. # close the client connection
  32. client.close()

该脚本运行一个服务器,该服务器侦听地址 localhost 和端口12345上的传入连接。当客户端连接时,服务器从客户端接收文件名,然后读取文件的内容并将其以块的形式发送给客户端。如果找不到该文件,服务器将向客户端发送适当的消息。

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

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

2.系统监控脚本:

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

  1. import psutil
  2. # Get the current CPU usage
  3. cpu_usage = psutil.cpu_percent()
  4. # Get the current memory usage
  5. memory_usage = psutil.virtual_memory().percent
  6. # Get the current disk usage
  7. disk_usage = psutil.disk_usage("/").percent
  8. # Get the network activity
  9. # Get the current input/output data rates for each network interface
  10. io_counters = psutil.net_io_counters(pernic=True)
  11. for interface, counters in io_counters.items():
  12. print(f"Interface {interface}:")
  13. print(f" bytes sent: {counters.bytes_sent}")
  14. print(f" bytes received: {counters.bytes_recv}")
  15. # Get a list of active connections
  16. connections = psutil.net_connections()
  17. for connection in connections:
  18. print(f"{connection.laddr} <-> {connection.raddr} ({connection.status})")
  19. # Print the collected data
  20. print(f"CPU usage: {cpu_usage}%")
  21. print(f"Memory usage: 1.15MB%")
  22. print(f"Disk usage: {disk_usage}%")

该脚本使用 psutil 模块中的 cpu_percent、virtual_memory 和 disk_usage 函数分别检索当前的 CPU 使用率、内存使用率和磁盘使用率。virtual_memory 函数返回一个具有各种属性的对象,例如内存总量以及已用和空闲内存量。disk_usage 函数将路径作为参数并返回一个对象,该对象具有诸如磁盘上的总空间量以及已用和可用空间量等属性。

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

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

  1. import requests
  2. from bs4 import BeautifulSoup
  3. # Fetch a web page
  4. page = requests.get("http://www.example.com")
  5. # Parse the HTML content
  6. soup = BeautifulSoup(page.content, "html.parser")
  7. # Find all the links on the page
  8. links = soup.find_all("a")
  9. # Print the links
  10. for link in links:
  11. print(link.get("href"))

在这里,您可以看到 BeautifulSoup 包的强大功能。你可以使用这个包找到任何类型的 dom 对象,因为我已经展示了如何找到页面上的所有链接。您可以修改脚本以抓取其他类型的数据,或导航到站点的不同页面。

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

4.电子邮件自动化脚本

此脚本可用于根据特定条件自动发送电子邮件。例如,您可以使用此脚本向您的团队发送每日报告,或者在重要的截止日期临近时向您自己发送提醒。以下是如何使用 Python 发送电子邮件的示例:

  1. import smtplib
  2. from email.mime.text import MIMEText
  3. # Set the SMTP server and login credentials
  4. smtp_server = "smtp.gmail.com"
  5. smtp_port = 587
  6. username = "your@email.com"
  7. pd = "yourpassword"
  8. # Set the email parameters
  9. recipient = "recipient@email.com"
  10. subject = "Test email from Python"
  11. body = "This is a test email sent from Python."
  12. # Create the email message
  13. msg = MIMEText(body)
  14. msg["Subject"] = subject
  15. msg["To"] = recipient
  16. msg["From"] = username
  17. # Send the email
  18. server = smtplib.SMTP(smtp_server, smtp_port)
  19. server.starttls()
  20. server.login(username, password)
  21. server.send_message(msg)
  22. server.quit()import smtplib
  23. from email.mime.text import MIMEText
  24. # Set the SMTP server and login credentials
  25. smtp_server = "smtp.gmail.com"
  26. smtp_port = 587
  27. username = "your@email.com"
  28. pd = "yourpassword"
  29. # Set the email parameters
  30. recipient = "recipient@email.com"
  31. subject = "Test email from Python"
  32. body = "This is a test email sent from Python."
  33. # Create the email message
  34. msg = MIMEText(body)
  35. msg["Subject"] = subject
  36. msg["To"] = recipient
  37. msg["From"] = username
  38. # Send the email
  39. server = smtplib.SMTP(smtp_server, smtp_port)
  40. server.starttls()
  41. server.login(username, password)
  42. server.send_message(msg)
  43. server.quit()

此脚本使用 smtplib 和电子邮件模块,通过简单邮件传输协议 (SMTP) 发送电子邮件。smtplib 模块中的 SMTP 类用于创建 SMTP 客户端,starttls 和登录方法用于建立安全连接,电子邮件模块中的 MIMEText 类用于在多用途 Internet 邮件扩展中创建电子邮件消息( MIME) 格式。MIMEText 构造函数将电子邮件正文作为参数,您可以使用 __setitem__ 方法设置电子邮件的主题、收件人和发件人。

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

5. 密码管理器脚本

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

  1. import secrets
  2. import string
  3. # Generate a random password
  4. def generate_password(length=16):
  5. characters = string.ascii_letters + string.digits + string.punctuation
  6. pd = "".join(secrets.choice(characters) for i in range(length))
  7. return password
  8. # Store a password in a secure way
  9. def store_password(service, username, password):
  10. # Use a secure hashing function to store the password
  11. hashed_password = hash_function(password)
  12. # Store the hashed password in a database or file
  13. with open("password_database.txt", "a") as f:
  14. f.write(f"{service},{username},{hashed_password}\n")
  15. # Retrieve a password
  16. def get_password(service, username):
  17. # Look up the hashed password in the database or file
  18. with open("password_database.txt") as f:
  19. for line in f:
  20. service_, username_, hashed_password_ = line.strip().split(",")
  21. if service == service_ and username == username_:
  22. # Use a secure hashing function to compare the stored password with the provided password
  23. if hash_function(password) == hashed_password_:
  24. return password
  25. return None

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

结论

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/51360
推荐阅读
相关标签
  

闽ICP备14008679号