FTP 测试通过

This commit is contained in:
2026-08-28 12:22:10 +08:00
parent cf33171c8f
commit 615a9b13e9
10 changed files with 437 additions and 128 deletions

View File

@@ -52,84 +52,122 @@ def test_speed(host, port, size_kb):
print(f"\n=== FTP Speed Test: {host}:{port}, {size_kb}KB file ===")
print(f" Test data: {total_bytes:,} bytes generated\n")
# ---- Upload ----
print("[UPLOAD] Connecting...")
checks = []
def check(label, ok, detail=""):
checks.append((label, ok, detail))
mark = "PASS" if ok else "FAIL"
print(f" [{mark}] {label}{(' - ' + detail) if detail else ''}")
def finish(sock):
passed = all(ok for _, ok, _ in checks)
print("\n" + "=" * 40)
print("FTP Speed 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 ===")
if sock:
try:
sock.close()
except Exception:
pass
return passed
# ---- Connect + Login ----
print("[Connect] Connecting...")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(60.0)
sock.connect((host, port))
try:
sock.connect((host, port))
except Exception as e:
print(f" CONNECT FAILED: {e}")
check("Connect", False, str(e))
return finish(sock)
recv_line(sock) # 220
send_cmd(sock, "USER anonymous")
send_cmd(sock, "PASS test@test.com")
if not send_cmd(sock, "USER anonymous"):
check("Login USER", False)
return finish(sock)
if not send_cmd(sock, "PASS test@test.com"):
check("Login PASS", False)
return finish(sock)
check("Login (USER/PASS)", True)
send_cmd(sock, "TYPE I")
# PASV
# ---- Upload ----
print("[UPLOAD] Connecting...")
resp = send_cmd(sock, "PASV")
if not resp:
print(" PASV failed"); sock.close(); return
check("PASV", False, "no response")
return finish(sock)
pasv_ip, pasv_port = parse_pasv(resp)
if pasv_port is None:
print(f" PASV parse failed: {resp.decode()}"); sock.close(); return
check("PASV parse", False, resp.decode())
return finish(sock)
check("PASV parse", True, f"{pasv_ip}:{pasv_port}")
# Connect data channel
data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data.settimeout(60.0)
data.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # 关 Nagle防 FIN 跑在数据前面
try:
data.connect((pasv_ip, pasv_port))
except Exception as e:
print(f" Data connect failed: {e}"); sock.close(); return
print(f" Data connect failed: {e}")
check("PASV data connect", False, str(e))
return finish(sock)
check("PASV data connect", True)
# STOR - measure from STOR send to 226 response
t0 = time.time()
send_cmd(sock, f"STOR {test_name}")
# Send all data at once (sendall handles partial sends)
data.sendall(test_data)
data.shutdown(socket.SHUT_WR)
data.close()
# Wait for response from server (data received + written to disk)
resp = recv_line(sock, timeout=120.0)
t1 = time.time()
upload_time = t1 - t0
upload_speed = total_bytes / upload_time / 1024 if upload_time > 0 else 0
# Read STOR response
resp = recv_line(sock)
stor_code = resp[:3].decode() if resp else "???"
print(f" Sent: {sent:,} / {total_bytes:,} bytes")
print(f" Sent: {total_bytes:,} / {total_bytes:,} bytes")
print(f" Time: {upload_time:.1f}s")
print(f" Speed: {upload_speed:.1f} KB/s")
print(f" Response: {resp.decode().rstrip() if resp else 'NONE'}")
if stor_code != "226":
print(f" UPLOAD FAILED (code={stor_code}), skipping download")
upload_ok = (stor_code == "226")
check("STOR 226", upload_ok, f"{stor_code} up={upload_speed:.1f}KB/s")
if not upload_ok:
send_cmd(sock, "QUIT")
sock.close()
return
return finish(sock)
# ---- Download ----
time.sleep(3.0)
print("[DOWNLOAD] Connecting...")
resp = send_cmd(sock, "PASV")
if not resp:
print(" PASV failed"); sock.close(); return
check("RETR PASV", False, "no response")
return finish(sock)
pasv_ip, pasv_port = parse_pasv(resp)
if pasv_port is None:
print(f" PASV parse failed"); sock.close(); return
check("RETR PASV parse", False, resp.decode())
return finish(sock)
data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data.settimeout(60.0)
try:
data.connect((pasv_ip, pasv_port))
except Exception as e:
print(f" Data connect failed: {e}"); sock.close(); return
print(f" Data connect failed: {e}")
check("RETR data connect", False, str(e))
return finish(sock)
check("RETR data connect", True)
t0 = time.time()
send_cmd(sock, f"RETR {test_name}")
dl_data = b""
while True:
try:
@@ -140,25 +178,24 @@ def test_speed(host, port, size_kb):
except socket.timeout:
break
data.close()
resp = recv_line(sock, timeout=120.0)
t1 = time.time()
download_time = t1 - t0
download_speed = len(dl_data) / download_time / 1024 if download_time > 0 else 0
resp = recv_line(sock)
retr_code = resp[:3].decode() if resp else "???"
print(f"\n[DOWNLOAD]")
print(f" Received: {len(dl_data):,} / {total_bytes:,} bytes")
print(f" Time: {download_time:.1f}s")
print(f" Speed: {download_speed:.1f} KB/s")
print(f" Response: {resp.decode().rstrip() if resp else 'NONE'}")
retr_ok = bool(resp) and resp.startswith(b"226")
check("RETR 226", retr_ok,
f"{resp[:3].decode() if resp else '???'} dl={download_speed:.1f}KB/s")
# Compare
print(f"\n[VERIFY]")
if len(dl_data) == total_bytes and dl_data == test_data:
match = (len(dl_data) == total_bytes and dl_data == test_data)
if match:
print(f" *** MATCH! {total_bytes:,} bytes identical. ***")
else:
print(f" MISMATCH: sent={total_bytes}, got={len(dl_data)}")
@@ -169,16 +206,15 @@ def test_speed(host, port, size_kb):
if dl_data[i] != test_data[i]:
print(f" First diff at byte {i}")
break
check("Upload/Download MATCH", match,
f"up={total_bytes:,} dl={len(dl_data):,} up={upload_speed:.1f}KB/s dl={download_speed:.1f}KB/s")
# Cleanup
send_cmd(sock, f"DELE {test_name}")
send_cmd(sock, "QUIT")
sock.close()
print(f"\n=== Summary ===")
print(f" File size: {total_bytes:,} bytes ({size_kb} KB)")
print(f" Upload: {upload_speed:.1f} KB/s ({upload_time:.1f}s)")
print(f" Download: {download_speed:.1f} KB/s ({download_time:.1f}s)")
return finish(sock)
def main():
parser = argparse.ArgumentParser(description="FTP Speed Test")
@@ -187,7 +223,8 @@ def main():
parser.add_argument("--size", type=int, default=FILE_SIZE_KB,
help=f"File size in KB (default {FILE_SIZE_KB})")
args = parser.parse_args()
test_speed(args.host, args.port, args.size)
success = test_speed(args.host, args.port, args.size)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()