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

使用Python脚本通过SecureCRT连接Cisco路由器失败求助

问题描述

我使用Python脚本通过SecureCRT连接Cisco路由器,在VSCode中输出的connection_string格式看起来完全正常:

"/SSH2 /L *username* /PASSWORD *password* 192.168.202.144"

但在SecureCRT中执行脚本时,crt.Session.ConnectInTab(connection_string)这行代码报错"Connection Failed"。脚本代码如下(已省略modify函数):

import os
from dotenv import load_dotenv
from pathlib import Path

dotenv_path = Path(r'C:\Users\user\Desktop\PythonScripts\.env')
load_dotenv(dotenv_path=dotenv_path)
username = os.getenv('env_username')
password = os.getenv('env_password')


def main():
    # 读取IP地址列表
    with open(r"C:\Users\user\Desktop\PythonScripts\ipaddresses", "r") as f:

        for host in f:

            modified_host = modify(host)

            connection_string = f"/SSH2 /L {username} /PASSWORD {password} {modified_host}"

            print(f"Connection string: {connection_string}")

            crt.Session.ConnectInTab(connection_string)


main()
排查与解决思路
  • 清理IP地址无效字符:modify函数处理后的modified_host可能携带换行符、空格等无效字符,导致SecureCRT无法识别。在代码中添加modified_host = modified_host.strip(),去除首尾的空白字符。
  • 验证账号密码有效性:直接在SecureCRT中手动使用.env文件里的账号密码连接目标路由器,确认凭证是否正确;同时检查.env文件中变量名是否和脚本里的env_username、env_password完全匹配。
  • 调整连接字符串格式:
    • 明确指定SSH端口(默认22),避免端口识别异常:
      connection_string = f"/SSH2 /L {username} /PASSWORD {password} /PORT 22 {modified_host}"
      
    • 若账号或密码包含特殊字符(如@、#等),给参数添加引号包裹:
      connection_string = f'/SSH2 /L "{username}" /PASSWORD "{password}" {modified_host}'
      
  • 检查文件权限与路径:确保SecureCRT运行脚本时,有权限读取.env和ipaddresses文件;可尝试将绝对路径改为相对路径,减少权限或路径解析问题。
  • 查看连接详情日志:在SecureCRT中开启会话日志,查看连接失败的具体原因,比如SSH版本不兼容、路由器端SSH配置限制、网络连通性问题等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:23:29