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

Python使用Fabric执行远程命令时出现'str'无fingerprint错误如何解决

问题原因
  • 参数类型不匹配错误:connect_kwargs中的pkey参数要求传入paramiko.PKey类型的实例对象,你当前直接传入了字符串'pkey',类型不符合要求,所以触发'str' object has no fingerprint属性报错。
  • 认证逻辑冲突:你同时配置了pkey和key_filename两个认证参数,fabric会优先使用pkey做身份校验,pkey本身无效就会直接导致连接失败,因此is_connected属性为False。
解决方法

根据你的登录方式选择对应修改方案:

方案1:使用本地密钥文件登录(适配你手动SSH可正常连接的场景)

删除错误的pkey配置即可,仅保留key_filename参数,修改后代码如下:

from fabric import Connection


class RemoteShell:
    def __init__(self, host):
        self.host = host
        self.user = 'root'
        self.key_file = get_key_file_path()

    def execute(self, command):
        with Connection(
                self.host,
                user=self.user,
                connect_kwargs={"key_filename": self.key_file}
        ) as c:
            # 可选添加hide=True参数,避免命令输出直接打印到控制台
            message = c.run(command, hide=True)
            return message

方案2:使用账号密码登录

如果是用root账号密码做认证,不需要配置密钥相关参数,直接传入password字段即可:

from fabric import Connection


class RemoteShell:
    def __init__(self, host):
        self.host = host
        self.user = 'root'
        self.password = '你的root账号实际密码'

    def execute(self, command):
        with Connection(
                self.host,
                user=self.user,
                connect_kwargs={"password": self.password}
        ) as c:
            message = c.run(command)
            return message

方案3:使用私钥字符串内容登录

如果你拿到的是私钥的字符串内容,需要先转换为RSAKey实例再传给pkey参数:

from fabric import Connection
from paramiko import RSAKey
from io import StringIO


class RemoteShell:
    def __init__(self, host, key_content, key_passphrase=None):
        self.host = host
        self.user = 'root'
        # 把私钥字符串转为PKey实例
        self.pkey = RSAKey.from_private_key(StringIO(key_content), password=key_passphrase)

    def execute(self, command):
        with Connection(
                self.host,
                user=self.user,
                connect_kwargs={"pkey": self.pkey}
        ) as c:
            message = c.run(command)
            return message

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:45:03