You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SSH会话接入Python并实现模拟按键操作旧CentOS系统?

How to Automate SSH Terminal Interactions in Python (Replace .cmd Keystroke Simulation)

Great question! Moving your Windows .cmd keystroke automation to Python for SSH sessions is totally doable, and gives you way more flexibility than batch files. Here’s how to approach it:

1. Pick the Right Python Tools

You’ll need libraries to handle SSH connections and simulate user-like terminal input. Two solid options are:

  • Pexpect (with pxssh): Built specifically for interactive terminal workflows, making it easy to send keystrokes and wait for system responses.
  • Paramiko: A low-level SSH library that gives you full control over the connection, ideal if you need custom behavior.

Install them via pip:

# For pxssh (simplest for interactive SSH tasks)
pip install pexpect

# For Paramiko (more granular control)
pip install paramiko

2. Example with Pexpect/Pxssh (Easiest Approach)

Pxssh wraps Pexpect to handle SSH login automatically, which is perfect for mimicking your .cmd keystroke workflow. This script sends commands, presses Enter, and waits for your old system’s unique prompts:

import pexpect

# Configure connection details
hostname = "your-centos-host-ip"
username = "your-ssh-username"
password = "your-ssh-password"

try:
    # Initialize and connect to the SSH session
    ssh_session = pexpect.pxssh.pxssh()
    ssh_session.login(hostname, username, password)
    
    # Simulate keystrokes to run your report (adjust to match your system's workflow)
    # 1. Type the command to launch the report tool and press Enter
    ssh_session.sendline("launch-old-report-tool")
    # Wait for the system's custom prompt (replace with your actual prompt, e.g., "LegacySys> ")
    ssh_session.expect("LegacySys> ")
    
    # 2. Press Enter to confirm the report type
    ssh_session.sendline("")  # Sends an Enter keystroke
    ssh_session.expect("Confirm report generation? (Y/N): ")
    
    # 3. Type "Y" to proceed
    ssh_session.sendline("Y")
    ssh_session.expect("Report saved to /var/legacy-reports/")
    
    # Optional: Print output to verify success
    print("System response:", ssh_session.before.decode())

finally:
    # Clean up the session when done
    if ssh_session.isalive():
        ssh_session.logout()

3. Example with Paramiko (More Control)

If you need finer-grained control over the SSH connection, use Paramiko’s interactive shell:

import paramiko
import time

# Set up SSH client
ssh_client = paramiko.SSHClient()
# Auto-add unknown host keys (adjust this for production environments!)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # Connect to the CentOS host
    ssh_client.connect(hostname="your-centos-host-ip", username="your-ssh-username", password="your-ssh-password")
    
    # Start an interactive shell session
    shell = ssh_client.invoke_shell()
    shell.settimeout(15)  # Increase timeout for slow legacy systems
    
    # Wait for the initial system prompt to load
    while not shell.recv_ready():
        time.sleep(1)
    initial_output = shell.recv(1024).decode()
    print("Initial system output:", initial_output)
    
    # Simulate your workflow step-by-step
    # Send command to launch report tool + Enter
    shell.send("launch-old-report-tool\n")
    time.sleep(3)  # Wait for tool to load
    
    # Press Enter to confirm report type
    shell.send("\n")
    # Wait for confirmation prompt before proceeding
    while "Confirm report generation? (Y/N): " not in shell.recv(1024).decode():
        time.sleep(1)
    
    # Send "Y" to start report
    shell.send("Y\n")
    time.sleep(5)
    
    # Retrieve final output
    final_output = shell.recv(4096).decode()
    print("Final system response:", final_output)

finally:
    # Close the SSH connection
    ssh_client.close()

Critical Tips for Your Legacy System

  • Target Unique Prompts: Your 1991-2001 system definitely has a custom prompt (not just $ or #). Use expect() (with pxssh) or check received output (with Paramiko) to wait for these specific strings—this prevents your script from sending input too early.
  • Adjust Timing: Old systems are slow! Increase timeouts or add short time.sleep() calls where needed to avoid race conditions.
  • Test Incrementally: Start with a simple script that logs in and sends one command, then build up to your full workflow.
  • Add Error Handling: Wrap critical steps in try-except blocks to catch connection failures, timeouts, or unexpected system responses.

内容的提问来源于stack exchange,提问作者Caleb McNevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:37:13