685a366890
原来 test/host 一层混了三类东西:51 个主机侧单测模块目录、25 个台架驱动 与探针、若干专用目录。台架脚本平铺在顶层,与单测目录并列,看不出哪个是 「连板跑一次的」,也看不出加新脚本该往哪放。 现在按被验对象分域归档,单测模块目录一律不动(22 根 pre-commit 钩子逐个 点名它们,50 个运行器按固定层数推仓库根): - bench/bench_defaults.py 台架连接默认值单一真源 - bench/ftp/ (10) FTP 功能、速率、鉴权、中止、完整性、背靠背复现 - bench/net/ (9) CH395F socket、keepalive 判死、挂机、复连压力、PASV、 UDP 队列、链路时延对端 - bench/iec104/ (2) 主站客户端与它的离线样帧自检 - bench/wave/ (1) 录波段文件 PC 侧解码 - bench/screenlink/ (2) 屏板链路顶替与拉帧压测 顶层条目 78 -> 53。逐脚本作用、运行前置与「加新脚本往哪放」写在新建的 test/host/bench/README.md;test/host/README.md 增目录地图表,把原平铺的 网络/FTP 两节压成指针。 配套修正(移动后不修就会坏): - 17 个脚本加上 bench/ 到 sys.path 的 bootstrap(sys.path[0] 是脚本自身 目录,不补就 import bench_defaults 失败) - cal/cal_write.py 本来就坏的(只插 cal/ 到自己 sys.path,import bench_defaults 直接 ModuleNotFoundError),补两段路径后可用 - e6_soak 与 wave_read 用 dirname 固定层数推仓库根,多两层后分别指向 test/test 与 test/ci-artifacts(后者静默写错目录、不报错),层数已改对 - scripts/board_ui_nav.py 与 MDK-ARM 两个探针的 bench_defaults 搜索路径 清理与标注:删掉 test/host/iec104/(旧自研协议层单测退役后只剩一个零引用 的 stub 桩头);文档里对 test/host/iec104 与 iec104_serv 的引用加上「已 删除/已不存在 2026-11-18」状态词。冻结历史证据(带日期戳的台架日志)与 编号别名登记表里的旧路径按原样保留。
229 lines
7.8 KiB
Python
229 lines
7.8 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
FTP Server 测试脚本 — 连接 STM32F4 上的 lftpd 服务器
|
||
用法:python ftp_test.py [--host <设备IP>] [--port 21] [--user admin] [--password admin]
|
||
"""
|
||
|
||
import os
|
||
import socket
|
||
import sys
|
||
import time
|
||
import argparse
|
||
|
||
# 台架连接默认值单一真源已随域归档到 test/host/bench/bench_defaults.py:
|
||
# Python 的 sys.path[0] 是**脚本自身所在目录**,本脚本在 bench/<域>/ 下直接
|
||
# `import bench_defaults` 会 ModuleNotFoundError —— 先把 bench/ 补进 sys.path。
|
||
_BENCH_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
if _BENCH_DIR not in sys.path:
|
||
sys.path.insert(0, _BENCH_DIR)
|
||
|
||
import bench_defaults # noqa: E402 (台架连接默认值单一真源)
|
||
|
||
HOST = bench_defaults.DEVICE_IP
|
||
PORT = 21
|
||
# 设备侧 FTP 鉴权走 /config.ini 的 [ftp](user / pwd_hash),出厂默认 admin/admin;
|
||
# **没有匿名通道**(USER anonymous 一律回 530)。
|
||
USER = "admin"
|
||
PASSWORD = "admin"
|
||
TIMEOUT = 10.0
|
||
|
||
def recv_line(sock):
|
||
"""读取 FTP 响应行(以 \r\n 结尾)"""
|
||
data = b""
|
||
sock.settimeout(TIMEOUT)
|
||
while True:
|
||
try:
|
||
ch = sock.recv(1)
|
||
except socket.timeout:
|
||
print(f"[TIMEOUT] after receiving: {data!r}")
|
||
return None
|
||
if not ch:
|
||
return data if data else None
|
||
data += ch
|
||
if data.endswith(b"\r\n"):
|
||
return data
|
||
|
||
def send_cmd(sock, cmd):
|
||
"""发送 FTP 命令并读取响应"""
|
||
print(f">>> {cmd}")
|
||
sock.sendall((cmd + "\r\n").encode())
|
||
time.sleep(0.1)
|
||
response = recv_line(sock)
|
||
if response:
|
||
print(f"<<< {response.decode(errors='replace').rstrip()}")
|
||
else:
|
||
print(f"<<< [NO RESPONSE / CONNECTION CLOSED]")
|
||
return response
|
||
|
||
def parse_pasv(response):
|
||
"""解析 PASV 227 响应,返回 (ip, port)"""
|
||
import re
|
||
m = re.search(r"(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)", response.decode())
|
||
if m:
|
||
a, b, c, d, e, f = [int(x) for x in m.groups()]
|
||
ip = f"{a}.{b}.{c}.{d}"
|
||
port = e * 256 + f
|
||
return ip, port
|
||
return None, None
|
||
|
||
def test_ftp(host, port, user, password):
|
||
print(f"=== FTP Test: {host}:{port} ===\n")
|
||
checks = [] # (label, ok, detail)
|
||
|
||
def check(label, ok, detail=""):
|
||
checks.append((label, ok, detail))
|
||
mark = "PASS" if ok else "FAIL"
|
||
print(f" [{mark}] {label}{(' - ' + detail) if detail else ''}")
|
||
|
||
# 1. Connect
|
||
print("[1] Connecting to control channel...")
|
||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
sock.settimeout(TIMEOUT)
|
||
try:
|
||
sock.connect((host, port))
|
||
print(f" Connected to {host}:{port}")
|
||
check("Connect", True)
|
||
except Exception as e:
|
||
print(f" CONNECT FAILED: {e}")
|
||
check("Connect", False, str(e))
|
||
return False
|
||
|
||
# 2. Read welcome
|
||
print("\n[2] Reading welcome banner...")
|
||
resp = recv_line(sock)
|
||
if resp:
|
||
print(f" {resp.decode(errors='replace').rstrip()}")
|
||
check("Welcome 220", resp.startswith(b"220"),
|
||
resp.decode(errors='replace').rstrip())
|
||
else:
|
||
print(" NO WELCOME BANNER")
|
||
check("Welcome 220", False, "no banner")
|
||
sock.close()
|
||
return False
|
||
|
||
# 3. Login
|
||
print("\n[3] Login...")
|
||
resp = send_cmd(sock, "USER " + user)
|
||
if not resp:
|
||
sock.close()
|
||
check("Login USER", False, "no response")
|
||
return False
|
||
|
||
resp = send_cmd(sock, "PASS " + password)
|
||
if not resp:
|
||
sock.close()
|
||
check("Login PASS", False, "no response")
|
||
return False
|
||
login_ok = b"230" in resp
|
||
check("Login (USER/PASS 230)", login_ok,
|
||
resp.decode(errors='replace').rstrip())
|
||
if not login_ok:
|
||
print(" 提示:lftpd 按 /config.ini 的 [ftp] 段校验(user / pwd_hash),出厂默认 admin/admin;"
|
||
"设备没有匿名通道。口令被改过就用 --user/--password 传;连续 5 次失败会锁定 60 秒。")
|
||
|
||
# 4. PWD
|
||
print("\n[4] PWD...")
|
||
resp = send_cmd(sock, "PWD")
|
||
pwd_ok = bool(resp) and resp.startswith(b"257")
|
||
check("PWD 257", pwd_ok,
|
||
resp.decode(errors='replace').rstrip() if resp else "no response")
|
||
|
||
# 5. PASV mode
|
||
print("\n[5] PASV...")
|
||
resp = send_cmd(sock, "PASV")
|
||
pasv_ip, pasv_port = (None, None)
|
||
if resp:
|
||
pasv_ip, pasv_port = parse_pasv(resp)
|
||
if pasv_port is None and resp and b"227" in resp:
|
||
# 227 响应但解析端口失败
|
||
pasv_port = None
|
||
if pasv_port is None:
|
||
# Try EPSV
|
||
print("\n[5b] Trying EPSV...")
|
||
resp = send_cmd(sock, "EPSV")
|
||
if resp and b"229" in resp:
|
||
import re
|
||
m = re.search(r"\(\|\|\|(\d+)\|\)", resp.decode())
|
||
if m:
|
||
pasv_port = int(m.group(1))
|
||
pasv_ip = host
|
||
print(f" EPSV: {pasv_ip}:{pasv_port}")
|
||
pasv_ok = pasv_port is not None
|
||
check("PASV/EPSV data port", pasv_ok,
|
||
f"{pasv_ip}:{pasv_port}" if pasv_ok else "no port")
|
||
|
||
# 6. LIST (correct PASV flow: connect data first, then send LIST)
|
||
if pasv_ok:
|
||
print(f" Data channel: {pasv_ip}:{pasv_port}")
|
||
print("\n[6] LIST...")
|
||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
data_sock.settimeout(5.0)
|
||
try:
|
||
data_sock.connect((pasv_ip, pasv_port))
|
||
print(f" Data connected to {pasv_ip}:{pasv_port}")
|
||
resp = send_cmd(sock, "LIST")
|
||
list_open = bool(resp) and resp.startswith(b"150")
|
||
data = b""
|
||
while True:
|
||
try:
|
||
chunk = data_sock.recv(1024)
|
||
if not chunk:
|
||
break
|
||
data += chunk
|
||
except socket.timeout:
|
||
break
|
||
print(f" LIST result ({len(data)} bytes):")
|
||
print(data.decode(errors='replace'))
|
||
data_sock.close()
|
||
resp = recv_line(sock)
|
||
list_close = bool(resp) and resp.startswith(b"226")
|
||
print(f" LIST response: "
|
||
f"{resp.decode(errors='replace').rstrip() if resp else 'none'}")
|
||
list_ok = list_open and list_close
|
||
check("LIST 150->226", list_ok,
|
||
f"open={list_open} close={list_close} bytes={len(data)}")
|
||
except Exception as e:
|
||
print(f" LIST FAILED: {e}")
|
||
data_sock.close()
|
||
check("LIST 150->226", False, str(e))
|
||
else:
|
||
print(" Skipping LIST (no data port)")
|
||
|
||
# 7. QUIT
|
||
print("\n[7] QUIT...")
|
||
resp = send_cmd(sock, "QUIT")
|
||
quit_ok = bool(resp) and resp.startswith(b"221")
|
||
check("QUIT 221", quit_ok,
|
||
resp.decode(errors='replace').rstrip() if resp else "no response")
|
||
sock.close()
|
||
|
||
# Summary
|
||
passed = all(ok for _, ok, _ in checks)
|
||
print("\n" + "=" * 40)
|
||
print("FTP Test Summary:")
|
||
for label, ok, _ in checks:
|
||
print(f" [{'PASS' if ok else 'FAIL'}] {label}")
|
||
print("=" * 40)
|
||
if passed:
|
||
print(">>> TEST PASSED <<<")
|
||
else:
|
||
print(">>> TEST FAILED <<<")
|
||
print("=== Test Complete ===")
|
||
return passed
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="FTP Server Test")
|
||
parser.add_argument("--host", default=HOST, help=f"FTP server IP (default: {HOST})")
|
||
parser.add_argument("--port", type=int, default=PORT, help=f"FTP server port (default: {PORT})")
|
||
parser.add_argument("--user", default=USER, help=f"FTP user (default: {USER})")
|
||
parser.add_argument("--password", default=PASSWORD,
|
||
help="FTP password (default: the factory password)")
|
||
args = parser.parse_args()
|
||
|
||
success = test_ftp(args.host, args.port, args.user, args.password)
|
||
sys.exit(0 if success else 1)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|