# 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 whileTrue: # 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 whileTrue: chunk = file.read(1024) ifnot 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')
系统监控是一种 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}%")
# Generate a random password defgenerate_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 defstore_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 defget_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 returnNone