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

Python技术问询:SSH隧道开启时远程cat文件并获取内容

用Python通过手动SSH隧道执行远程cat命令读取文件

嘿,完全理解你的处境——毕业之后没怎么碰专业编程,只搞过点简单的VB,现在想上手Python实现远程读文件,还得手动操控SSH隧道对吧?咱们一步一步来,把这事弄明白。

第一步:先手动建立SSH隧道

首先你得先在本地终端里手动建好隧道,把本地某个端口转发到目标主机的SSH端口上。假设:

  • 跳板机(你用来中转的机器)IP是 jump-host-ip,登录用户是 jump-user
  • 目标主机(你要读文件的机器)IP是 target-host-ip,它的SSH端口是默认的22
  • 你想把本地的2222端口绑定到目标主机的22端口

那执行这条命令就行:

ssh -L 2222:target-host-ip:22 jump-user@jump-host-ip

执行后按提示完成登录(输密码或者用密钥),保持这个终端窗口打开,隧道就一直通着啦。

第二步:用Python连接隧道并执行cat命令

接下来用Python的paramiko库来实现,这个库专门处理SSH连接,很适合你的需求。

先安装依赖

打开另一个终端,先装paramiko:

pip install paramiko

代码示例

下面是完整的代码,我给你加了注释,方便理解:

import paramiko

def read_remote_file_via_tunnel():
    # 这里填你的目标主机信息
    target_username = "target-user"  # 目标主机的登录用户名
    target_private_key_path = "/path/to/your/private-key"  # 你的私钥文件路径
    local_tunnel_port = 2222  # 刚才手动隧道绑定的本地端口
    remote_file_path = "/path/to/remote/file.txt"  # 你要读的远程文件路径

    try:
        # 加载私钥
        private_key = paramiko.RSAKey.from_private_key_file(target_private_key_path)
        
        # 连接本地的隧道端口(相当于间接连到目标主机)
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受未知主机密钥
        ssh_client.connect(hostname="localhost", port=local_tunnel_port, username=target_username, pkey=private_key)

        # 执行cat命令读取文件
        stdin, stdout, stderr = ssh_client.exec_command(f"cat {remote_file_path}")
        
        # 获取命令输出和错误信息
        file_content = stdout.read().decode('utf-8')
        error_msg = stderr.read().decode('utf-8')

        if error_msg:
            print(f"执行出错:{error_msg}")
        else:
            print("远程文件内容:")
            print(file_content)

    except Exception as e:
        print(f"连接或执行失败:{str(e)}")
    finally:
        # 不管成功失败,都关闭SSH连接
        if 'ssh_client' in locals() and ssh_client.get_transport().is_active():
            ssh_client.close()

if __name__ == "__main__":
    read_remote_file_via_tunnel()

一些实用提示

  • 如果你用密码登录目标主机,把pkey=private_key换成password="your-target-password"就行,但更推荐用密钥登录,安全又不用反复输密码。
  • Linux/macOS下要确保私钥文件权限正确,最好设成chmod 600 /path/to/your/private-key,权限太宽会被SSH拒绝。
  • 如果执行时提示文件不存在,先确认远程文件路径是不是绝对路径,或者目标用户有没有该文件的读取权限。

这样弄下来,你就能通过手动隧道,用Python轻松读取远程文件内容啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:33:34