Windows 10下Python脚本调用telnet报错问题求助
Hey Bernhard, I totally get how frustrating this must be—you’ve got telnet.exe right where it should be, it works perfectly in regular CMD, but your Python script just can’t seem to find it. Let’s break down what’s happening and fix this step by step.
Root Cause: WoW64 File System Redirection
The core issue here is WoW64 redirection. If you’re running a 32-bit version of Python on a 64-bit Windows 10 system, Windows automatically redirects requests to C:\Windows\System32 to C:\Windows\SysWOW64 (the folder for 32-bit system binaries). Since telnet.exe is a 64-bit executable, it only lives in System32—so your Python-launched CMD can’t see it, even though PATH includes System32.
Fix Options
1. Confirm Your Python Architecture First
Let’s verify if you’re on 32-bit Python. Run this in your Python shell:
import platform print(platform.architecture())
If the output is ('32bit', 'WindowsPE'), that’s exactly why you’re hitting this problem.
2. Disable WoW64 Redirection Temporarily
You can use Windows API calls via ctypes to turn off redirection before running your subprocess, then revert it afterward. Here’s your modified script:
import subprocess import ctypes import sys # Disable WoW64 redirection if we're on 32-bit Python if sys.maxsize <= 2**32: kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) wow64_state = ctypes.c_long() kernel32.Wow64DisableWow64FsRedirection(ctypes.byref(wow64_state)) # Run your telnet command cmdline = "telnet 172.19.52.34" rc = subprocess.call("start cmd /K " + cmdline, shell=True) # Re-enable redirection to avoid breaking other system operations if sys.maxsize <= 2**32: kernel32.Wow64RevertWow64FsRedirection(wow64_state)
3. Use the Sysnative Alias for Direct Path
Instead of relying on PATH, point directly to the real telnet.exe using the Sysnative alias (this bypasses redirection for 32-bit apps):
import subprocess # Use Sysnative to access 64-bit System32 from 32-bit Python cmdline = r"C:\Windows\Sysnative\telnet.exe 172.19.52.34" rc = subprocess.call("start cmd /K " + cmdline, shell=True)
4. Switch to 64-bit Python (Permanent Fix)
If you don’t need 32-bit Python for other tools or dependencies, installing the 64-bit version will eliminate the redirection issue entirely. Once you switch, your original script should work exactly as expected—no extra code required.
内容的提问来源于stack exchange,提问作者BersekerBernhard

