已完成lab1 & lab2

This commit is contained in:
typingbugs 2024-03-28 21:55:25 +08:00
commit dd5f7134dd
7 changed files with 423 additions and 0 deletions

86
Lab1/src/main.py Normal file
View File

@ -0,0 +1,86 @@
import os
import socket
import urllib.parse
# 设置服务器的根目录
WEB_ROOT = os.path.abspath("../www")
def serve_file(client_socket:socket.socket, path):
# 解析请求的URL路径移除开头的/并处理URL编码
requested_path = urllib.parse.unquote(path)
if requested_path == "/":
requested_path = "/index.html" # 默认页面
# 构建文件的绝对路径
file_path = os.path.join(WEB_ROOT, requested_path.lstrip('/'))
# 获取安全的绝对路径,以确保它不会跳出根目录
safe_path = os.path.abspath(file_path)
if not safe_path.startswith(WEB_ROOT):
# 如果请求的路径不是根目录的子路径则返回403 Forbidden
response = b"HTTP/1.1 403 Forbidden\r\n"
response += b"Content-Type: text/html\r\n"
response += b"\r\n"
response += b"<html><body><h1>403 Forbidden</h1></body></html>"
else:
try:
# 尝试打开并读取文件
with open(safe_path, "rb") as file:
content = file.read()
# 根据文件类型设置Content-Type这里简化处理仅对HTML进行了处理
content_type = "text/html" if safe_path.endswith(".html") else "application/octet-stream"
response = b"HTTP/1.1 200 OK\r\n"
response += f"Content-Type: {content_type}\r\n".encode()
response += b"Content-Length: " + str(len(content)).encode() + b"\r\n"
response += b"\r\n"
response += content
except FileNotFoundError:
# 文件未找到返回404响应
response = b"HTTP/1.1 404 Not Found\r\n"
response += b"Content-Type: text/html\r\n"
response += b"\r\n"
response += b"<html><body><h1>404 Not Found</h1></body></html>"
client_socket.send(response)
def start_server(host="0.0.0.0", port=80):
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许地址重用
socket_server.bind((host, port))
socket_server.listen(5)
print(f"Server listening on {host}:{port}")
while True:
client_socket = None
try:
client_socket, address = socket_server.accept()
print(f"Connection from {address}")
# 接收客户端请求
request = client_socket.recv(1024).decode("utf-8")
if not request:
print("Empty request received.")
continue
# 解析HTTP请求的第一行获取请求路径
request_lines = request.split("\r\n")
if request_lines and len(request_lines[0].split(" ")) >= 3:
method, path, _ = request_lines[0].split(" ", 2)
# 根据路径返回相应的文件
serve_file(client_socket, path)
print(f'Respond client socket {client_socket} succeed')
else:
print("Invalid request line:", request_lines[0])
# 关闭客户端连接
except ConnectionResetError:
print("Connection reset by peer.")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
if client_socket:
client_socket.close()
if __name__ == "__main__":
start_server()

14
Lab1/www/dir/hello.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello页面</title>
</head>
<body>
<h1>Hello页面</h1>
<p>这是一个简单的Hello页面。</p>
<a href="../index.html">返回主页</a>
</body>
</html>

14
Lab1/www/index.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主页</title>
</head>
<body>
<h1>欢迎来到主页</h1>
<p>这是网站的主页。</p>
<a href="dir/hello.html">访问hello页面</a>
</body>
</html>

9
Lab2/email_config.json Normal file
View File

@ -0,0 +1,9 @@
{
"sender": "jingfan.ke@qq.com",
"receiver": "jingfan.ke@qq.com",
"subject": "SMTP 邮件测试",
"body": "这是一封测试邮件发送自Python程序。",
"smtp_server": "smtp.qq.com",
"imap_url": "imap.qq.com",
"password": "dbeucjitqdczebad"
}

207
Lab2/emails.json Normal file

File diff suppressed because one or more lines are too long

62
Lab2/receiver.py Normal file
View File

@ -0,0 +1,62 @@
import imaplib
import email
import json
from email.header import decode_header
# 从JSON文件中加载配置信息
with open('email_config.json', 'r') as config_file:
config = json.load(config_file)
user = config['sender']
password = config['password']
imap_url = config['imap_url']
# 连接到IMAP服务器
mail = imaplib.IMAP4_SSL(imap_url)
mail.login(user, password)
mail.select('inbox')
# 搜索所有邮件
result, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
id_list.reverse()
emails = []
# 遍历邮件ID
for i in id_list:
result, data = mail.fetch(i, '(RFC822)')
raw_email = data[0][1]
raw_email_string = raw_email.decode('utf-8',errors="ignore")
email_message = email.message_from_string(raw_email_string)
# 解析邮件内容
mail_from = email_message['From']
mail_subject = decode_header(email_message['Subject'])[0][0]
if isinstance(mail_subject, bytes):
mail_subject = mail_subject.decode('utf-8')
mail_body = ''
if email_message.is_multipart():
for part in email_message.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
if ctype == 'text/plain' and 'attachment' not in cdispo:
mail_body = part.get_payload(decode=True).decode('utf-8')
break
else:
mail_body = email_message.get_payload(decode=True).decode('utf-8')
emails.append({'From': mail_from, 'Subject': mail_subject, 'Body': mail_body})
# 保存邮件列表到JSON文件
with open('emails.json', 'w') as outfile:
json.dump(emails, outfile, indent=4, ensure_ascii=False)
# 打印最后一封邮件的信息
if emails:
print("From: ", emails[0]['From'])
print("Subject: ", emails[0]['Subject'])
print("Body: ", emails[0]['Body'])
mail.logout()

31
Lab2/sender.py Normal file
View File

@ -0,0 +1,31 @@
import smtplib
import json
from email.mime.text import MIMEText
from email.header import Header
# 从JSON文件中加载邮件配置
with open('email_config.json', 'r') as config_file:
config = json.load(config_file)
sender = config['sender']
receiver = config['receiver']
subject = config['subject']
body = config['body']
smtp_server = config['smtp_server']
password = config['password']
# 创建MIMEText对象设置邮件内容
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = Header(sender)
message['To'] = Header(receiver)
message['Subject'] = Header(subject, 'utf-8')
try:
# 连接SMTP服务器并发送邮件
server = smtplib.SMTP_SSL(smtp_server, 465) # 使用465端口
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
print("邮件发送成功")
server.quit()
except smtplib.SMTPException as e:
print("邮件发送失败", e)