python - Django ssh 在 sftp 连接期间失败

标签 python linux ssh sftp paramiko

这是我得到的错误

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 key 失败那是什么?

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

你能帮我解决这个错误吗

最佳答案

编辑 来回反复之后,解决方案只是通过 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-----

检查您是否使用了正确的 key 文件。您可以通过以下方式对其进行测试:

openssl rsa -text -noout -in private_key_file

你不应该看到任何错误。

关于python - Django ssh 在 sftp 连接期间失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24380702/

相关文章:

javascript - Selenium鼠标滚轮下拉加载所有页面

c++ - 在 C++ 缓冲输出中避免 memcpy

c - exec*() 后内存使用会发生什么

python - 执行自定义命令以在 Windows 中运行 python 插件时出错

python - 如何解决 Google Cloud Function 上的 "No module named ' frontend'"错误消息

Python:更新文件时保持相同的行尾字符

ssh - 致命的 : Authentication failed when trying to clone GitLab project even though "ssh -i" command prints "Welcome to GitLab, [username]"

git - Windows 10 的 Git 客户端是否自动安装 SSH 客户端?

shell - 在 ssh 终端与 ubuntu 桌面上运行相同的命令,在 ssh 终端上无法运行?

python - 在 asyncio 模块中完成一个任务列表后,如何提交另一个任务列表?