使用Pywinauto自动化Putty登录与命令执行的问题求助
I’ve dealt with this exact scenario before—needing to keep the PuTTY GUI open for post-automation manual work while handling those pesky initial popups. Here’s a step-by-step solution tailored to your needs:
1. Handle the First-Time Security Alert
When connecting to a new IP, PuTTY throws a "Security Alert" dialog asking if you trust the host key. We can detect this window and auto-accept it using Pywinauto’s window detection:
from pywinauto import Application, timings import time # Adjust timings to be more forgiving for slow dialogs timings.TIMEOUTS['wait_for_window'] = 10 # Launch PuTTY and pass the target IP directly app = Application().start(r'putty.exe -ssh 10.22.22.222') # Check for the security alert window and accept it try: alert_window = app.window(title_re="Security Alert") alert_window.wait('visible', timeout=5) # Button text might be "Accept" or "Yes" depending on your PuTTY version alert_window.Button.click() except Exception as e: # No alert means the host is already trusted—just proceed print(f"No security alert detected: {e}")
2. Automate Login & Command Execution
Once the main PuTTY terminal loads, we can send keystrokes for credentials and commands. PuTTY’s terminal area is typically an Edit control, so we can target that directly:
# Get the main PuTTY terminal window (title usually starts with "PuTTY") terminal_window = app.window(title_re="PuTTY.*") terminal_window.wait('ready', timeout=10) # Send username and press Enter terminal_window.Edit.type_keys('your_username{ENTER}') # Wait for password prompt to appear, then send password time.sleep(1) terminal_window.Edit.type_keys('your_password{ENTER}') # Wait for the shell to be fully ready, then run your commands time.sleep(2) terminal_window.Edit.type_keys('ls -la{ENTER}') terminal_window.Edit.type_keys('echo "Automation step done!"{ENTER}')
3. Keep the GUI Window Open for Subsequent Operations
The critical part here is not closing the Pywinauto application object or killing the process. As long as your script doesn’t exit (or you keep the app and terminal_window objects in scope), the PuTTY window will stay open for manual use later. If you need to interact with it again in the same script, just reuse the existing terminal_window object.
Key Tips
- Button Text Variations: If your PuTTY version uses "Yes" instead of "Accept" on the security alert, update the button click logic accordingly.
- Timing Adjustments: Add longer
time.sleep()calls or use Pywinauto’swait('enabled')method if your system is slow to render prompts. - Control Debugging: If
Editcontrol targeting fails, useterminal_window.print_control_identifiers()to list all available controls and adjust your code.
内容的提问来源于stack exchange,提问作者Nik Zeyn

