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

Binary file not shown.

Binary file not shown.

Binary file not shown.

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()

View File

@@ -55,6 +55,12 @@ def parse_pasv(response):
def test_ftp(host, port):
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...")
@@ -63,8 +69,10 @@ def test_ftp(host, port):
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
@@ -72,8 +80,11 @@ def test_ftp(host, port):
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
@@ -82,27 +93,35 @@ def test_ftp(host, port):
resp = send_cmd(sock, "USER anonymous")
if not resp:
sock.close()
check("Login USER", False, "no response")
return False
resp = send_cmd(sock, "PASS test@test.com")
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())
# 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")
if not resp:
sock.close()
return False
pasv_ip, pasv_port = parse_pasv(resp)
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:
print(" FAILED to parse PASV response")
# Try EPSV
print("\n[5b] Trying EPSV...")
resp = send_cmd(sock, "EPSV")
@@ -113,21 +132,21 @@ def test_ftp(host, port):
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")
if pasv_port is None:
print(" PASV/EPSV FAILED, trying PORT mode...")
# Skip data connection tests
else:
# 6. LIST (correct PASV flow: connect data first, then send LIST)
if pasv_ok:
print(f" Data channel: {pasv_ip}:{pasv_port}")
# 6. LIST (correct PASV flow: connect data first, then send LIST)
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}")
send_cmd(sock, "LIST")
resp = send_cmd(sock, "LIST")
list_open = bool(resp) and resp.startswith(b"150")
data = b""
while True:
try:
@@ -140,22 +159,41 @@ def test_ftp(host, port):
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()
# Read LIST response
resp = recv_line(sock)
if resp:
print(f" LIST response: {resp.decode(errors='replace').rstrip()}")
check("LIST 150->226", False, str(e))
else:
print(" Skipping LIST (no data port)")
# 7. QUIT
print("\n[7] QUIT...")
send_cmd(sock, "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()
print("\n=== Test Complete ===")
return True
# 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")

View File

@@ -128,33 +128,67 @@ def ftp_transfer_data(host, pasv_ip, pasv_port, cmd, data_to_send=None, read_dat
def test_upload_download(host, port):
print(f"=== FTP Upload/Download Test: {host}:{port} ===\n")
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 Upload/Download 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
# 1. Connect + Login
print("[1] Connect + Login")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(TIMEOUT)
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
if not send_cmd(sock, "USER anonymous", 230):
sock.close(); return
check("Login USER 230", False)
return finish(sock)
if not send_cmd(sock, "PASS test@test.com", 230):
sock.close(); return
check("Login PASS 230", False)
return finish(sock)
check("Login (USER/PASS 230)", True)
# 2. TYPE I (binary mode)
print("\n[2] Set binary mode")
send_cmd(sock, "TYPE I")
resp = send_cmd(sock, "TYPE I")
type_ok = bool(resp) and resp.startswith(b"200")
check("TYPE I 200", type_ok)
# 3. PASV + STOR (upload)
print("\n[3] Upload: STOR up_test.dat")
resp = send_cmd(sock, "PASV")
if not resp:
sock.close(); return
check("PASV", False, "no response")
return finish(sock)
pasv_ip, pasv_port = parse_pasv(resp)
print(f" PASV: {pasv_ip}:{pasv_port}")
# Connect data channel
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data_sock.settimeout(10.0)
try:
@@ -162,12 +196,11 @@ def test_upload_download(host, port):
print(f" Data connected.")
except Exception as e:
print(f" Data connect FAILED: {e}")
sock.close(); return
check("PASV data connect", False, str(e))
return finish(sock)
check("PASV data connect", True, f"{pasv_ip}:{pasv_port}")
# Send STOR
send_cmd(sock, "STOR up_test.dat")
# Send file data
total = 0
while total < len(TEST_DATA):
try:
@@ -179,20 +212,20 @@ def test_upload_download(host, port):
print(f" Send error: {e}")
break
print(f" Uploaded {total}/{len(TEST_DATA)} bytes.")
data_sock.shutdown(socket.SHUT_WR)
data_sock.close()
# Read STOR response
resp = recv_line(sock)
if resp:
print(f" Response: {resp.decode().rstrip()}")
stor_ok = bool(resp) and resp.startswith(b"226") and total == len(TEST_DATA)
check("STOR 226 + bytes", stor_ok,
f"uploaded={total}/{len(TEST_DATA)} resp={resp.decode().rstrip() if resp else 'none'}")
# 4. PASV + LIST (verify)
print("\n[4] Verify: LIST")
resp = send_cmd(sock, "PASV")
if not resp:
sock.close(); return
check("LIST PASV", False, "no response")
return finish(sock)
pasv_ip, pasv_port = parse_pasv(resp)
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -213,15 +246,17 @@ def test_upload_download(host, port):
data_sock.close()
resp = recv_line(sock)
if resp:
print(f" Response: {resp.decode().rstrip()}")
list_ok = bool(data) and b"UP_TEST.DAT" in data.upper()
check("LIST shows UP_TEST.DAT", list_ok,
resp.decode().rstrip() if resp else "no resp")
# 5. PASV + RETR (download)
time.sleep(1.0)
print("\n[5] Download: RETR up_test.dat")
resp = send_cmd(sock, "PASV")
if not resp:
sock.close(); return
check("RETR PASV", False, "no response")
return finish(sock)
pasv_ip, pasv_port = parse_pasv(resp)
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -230,10 +265,11 @@ def test_upload_download(host, port):
data_sock.connect((pasv_ip, pasv_port))
except Exception as e:
print(f" Data connect FAILED: {e}")
sock.close(); return
check("RETR data connect", False, str(e))
return finish(sock)
check("RETR data connect", True, f"{pasv_ip}:{pasv_port}")
send_cmd(sock, "RETR up_test.dat")
dl_data = b""
while True:
try:
@@ -244,39 +280,46 @@ def test_upload_download(host, port):
except socket.timeout:
break
data_sock.close()
resp = recv_line(sock)
if resp:
print(f" Response: {resp.decode().rstrip()}")
retr_ok = bool(resp) and resp.startswith(b"226")
check("RETR 226", retr_ok, resp.decode().rstrip() if resp else "no resp")
# Compare
print(f"\n[6] Compare")
print(f" Uploaded: {len(TEST_DATA)} bytes")
print(f" Downloaded: {len(dl_data)} bytes")
if dl_data == TEST_DATA:
match = (dl_data == TEST_DATA)
if match:
print(f" *** MATCH! Upload/Download success. ***")
else:
print(f" *** MISMATCH! ***")
if dl_data:
print(f" First 80 bytes uploaded: {TEST_DATA[:80]!r}")
print(f" First 80 bytes downloaded: {dl_data[:80]!r}")
check("Upload/Download MATCH", match, f"up={len(TEST_DATA)} dl={len(dl_data)}")
# 7. DELE (delete test file)
print("\n[7] Cleanup: DELE up_test.dat")
send_cmd(sock, "DELE up_test.dat")
resp = send_cmd(sock, "DELE up_test.dat")
dele_ok = bool(resp) and resp.startswith(b"250")
check("DELE 250", dele_ok, resp.decode().rstrip() if resp else "no resp")
# 8. QUIT
print("\n[8] QUIT")
send_cmd(sock, "QUIT")
sock.close()
print("\n=== Test Complete ===")
resp = send_cmd(sock, "QUIT")
quit_ok = bool(resp) and resp.startswith(b"221")
check("QUIT 221", quit_ok, resp.decode().rstrip() if resp else "no resp")
return finish(sock)
def main():
parser = argparse.ArgumentParser(description="FTP Upload/Download Test")
parser.add_argument("--host", default=HOST)
parser.add_argument("--port", type=int, default=PORT)
args = parser.parse_args()
test_upload_download(args.host, args.port)
success = test_upload_download(args.host, args.port)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()