Django 在 SFTP 连接中 SSH 失败

0 投票
2 回答
1384 浏览
提问于 2025-04-18 10:51

我遇到的错误是这个

ri@ri-desktop:~/workspace/ssh$ python ssh.py
Establishing SSH connection to: upload.partner.com 19321 ...
Failed loading ~/workspace/ssh/rsa_private_key
No handlers could be found for logger "paramiko.transport"
Trying ssh-agent key b747f6899b3a450e63bc6faab1625686 ... failed! key cannot be used for signing
*** Caught exception: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'get_fingerprint'
============================================================
Total files copied: 0
All operations complete!
============================================================
ri@ri-desktop:~/workspace/ssh$

这是我的设置代码。我是从 activstate 上拿的这段代码。我给的路径是正确的,但我有个疑问,首先错误提示说无法加载 ~/workspace/ssh/rsa_private_key。然后又显示了一些 ssh-agent 的密钥失败,这是什么意思呢?

hostname = 'upload.partner.com' # remote hostname where SSH server is running
port = 19321
username = 'music--test'
password = 'grg'
rsa_private_key = r"~/workspace/ssh/rsa_private_key"
dir_local='~/workspace/ssh/New/'
dir_remote = "remote_machine_folder/subfolder"
glob_pattern='*.*'
import os
import glob
import paramiko
import md5
rsa = None
def agent_auth(transport, username):
    ki = None
    #ppk = None
    Attempt to authenticate to the given transport using any of the private
    keys available from an SSH agent or from a local private RSA key file (assumes no pass phrase).
    try:
        ki = paramiko.RSAKey.from_private_key_file(rsa_private_key)
    except Exception, e:
        print 'Failed loading {0}'.format (rsa_private_key, e)
    agent = paramiko.Agent()
    agent_keys = agent.get_keys() + (ki,)
    if len(agent_keys) == 0:
        return
        for key in agent_keys:
        print 'Trying ssh-agent key {0}'.format(key.get_fingerprint().encode('hex')),
        try:
            transport.auth_publickey(username, key)
            print '... success!'
            return
        except paramiko.SSHException, e:
            print '... failed!', e
hostkeytype = None
hostkey = None
files_copied = 0
try:
    host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
    try:
        # try ~/ssh/ too, e.g. on windows
        host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
    except IOError:
        print ' Unable to open host keys file'
        host_keys = {hostname:'upload.partner.com'}
if hostname in host_keys:
    hostkeytype = host_keys[hostname].keys()[0]
    hostkey = host_keys[hostname][hostkeytype]
    print 'Using host key of type {0}'.format(hostkeytype)
try:
    print 'Establishing SSH connection to:', hostname, port, '...'
    t = paramiko.Transport((hostname, port))
    t.connect()
    agent_auth(t, username)
      if not t.is_authenticated():
        print 'RSA key auth failed! Trying password login...'
        t.connect(username=username, password=password, hostkey=hostkey)
    else:
        sftp = t.open_session()
    sftp = paramiko.SFTPClient.from_transport(t)
    try:
        sftp.mkdir(dir_remote)
    except IOError, e:
        print '(assuming ', dir_remote, 'exists)', e
    for fname in glob.glob(dir_local + os.sep + glob_pattern):
        is_up_to_date = False
        if fname.lower().endswith('xml'):
            local_file = os.path.join(dir_local, fname)
            remote_file = dir_remote + '/' + os.path.basename(fname)
            try:
                if sftp.stat(remote_file):
                    local_file_data = open(local_file, "rb").read()
                    remote_file_data = sftp.open(remote_file).read()
                    md1 = md5.new(local_file_data).digest()
                    md2 = md5.new(remote_file_data).digest()
                    if md1 == md2:
                        is_up_to_date = True
                        print "UNCHANGED:", os.path.basename(fname)
                    else:
                        print "MODIFIED:", os.path.basename(fname),
            except:
                print "NEW: ", os.path.basename(fname),
                if not is_up_to_date:
                print 'Copying', local_file, 'to ', remote_file
                sftp.put(local_file, remote_file)
                files_copied += 1
    t.close()
except Exception, e:
    print '*** Caught exception: %s: %s' % (e.__class__, e)
    try:
        t.close()
    except:
        pass
print '=' * 60
print 'Total files copied:',files_copied
print 'All operations complete!'
print '=' * 60

你能帮我解决这个错误吗?

2 个回答

0

第一个问题出现在这段代码中

rsa_private_key = r"~/workspace/ssh/rsa_private_key"
.
.
.
try:
    ki = paramiko.RSAKey.from_private_key_file(rsa_private_key)
except Exception, e:
    print 'Failed loading {0}'.format (rsa_private_key, e)

我觉得 from_private_key_file() 这个函数可能不支持文件路径的扩展,所以它把 ~ 当作普通的波浪线来处理。你可以试着把 rsa_private_key 改成完整的文件名。

另外,你在 except 语句里的打印语句没有显示出异常的具体信息。我建议把它改成 print 'Failed loading {0} : {1}'.format (rsa_private_key, e)。这样你可能会在后面的错误信息中看到问题的原因:

Failed loading ~/workspace/ssh/rsa_private_key : [Errno 2] No such file or directory: '~/workspace/ssh/rsa_private_key'

此外,如果你的密钥是加密的,你可能还需要给 from_private_key_file() 提供一个密码。

1

编辑 经过多次反复,解决办法其实很简单,就是通过 ssh-add 命令把用户的私钥添加到 SSH 代理中。


实际上,你可能是在尝试使用你的公钥,而不是私钥。

文件名 "id-rsa.pub" 看起来很像是一个公钥。对应的私钥通常叫做 "id-rsa"。公钥的格式大概是这样的:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCUmHZlySQqmZCGgE0NKWYyYlPHb3g1Bwdll2ztngUWNkrDSWGmLq6IqJP9EwwxungwJkdkR/U86gFv5MQfQ92+0ote7pUXOACwHfqvIoUXXFI3ZLo/C2cuqDIO7fcO50KKGFAuWbjTd3rugbpoMnNqT99wz/1lrCkTsJLd0YxtRo/QsJ8jiZXRuaEzbdXKwZJaP8G3eBHSMiEa1781yWklk50xxLk2qtpWVzen+Om6InbQ2cR6bBvfiA4B3LES53ccmMfzrCygjl8B6yaV3NI60Re5oNdyNrPZgH4VXf5p4VwrKpY4dCcJZyNmHlFhJlTgZu25uKAbp8Wk4u1ky0vJ mhawke@localhost.localdomain

而未加密的私钥格式大概是这样的:

-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCfqBLoK4Vec7r0df4a2CYNzmhJn74qIDqbJnkGasHcN5/GYuDv
.
.
xLCNrVMXYPd1I7L5NGzZalaTrS+DkgLwNvGhkVGKUGao
-----END RSA PRIVATE KEY-----

加密的私钥则是这样的:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,1ACD09B7F078AEB84B9A109979B77CBB

LDEuf08/xMGsHyesZxFGkRNHf8C78vpdDJyBBManOt/mRf/5fkjOel8RgoH4oYEz
.
.
tKjd+PlR4WLluMPFeHujdqhvyC4fQeFzWqak+rlUG5o3lm+TAcKqjypAEU4RVUuW
-----END RSA PRIVATE KEY-----

检查一下你是否在使用正确的密钥文件。你可以通过以下命令来测试:

openssl rsa -text -noout -in private_key_file

如果没有错误信息,那就说明没问题。

撰写回答