简体   繁体   English

sftp连接期间Django SSH失败

[英]Django ssh failed during sftp connection

This is the error am getting 这是错误越来越

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$

This is my setup code. 这是我的设置代码。 i took this setup code from activstate . 我从activstate那里获取了此设置代码。 I given correct path only and my doubt is firstly the error showing Failed loading ~/workspace/ssh/rsa_private_key. 我只给出了正确的路径,而我首先怀疑的是显示错误加载〜/ workspace / ssh / rsa_private_key的错误。 but its showing some ssh-agent key failed what is that? 但是显示某些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

can you help me to solve this error 你能帮我解决这个错误吗

EDIT After much to and fro, the solution was simply to add user's private key to she ssh agent via ssh-add . 编辑经过反复研究,解决方案只是通过ssh-add将用户的私钥添加到她的ssh代理中。


Actually, you might be trying to use your public key, not your private key. 实际上,您可能正在尝试使用公用密钥,而不是专用密钥。

The file name "id-rsa.pub" looks suspiciously like a public key. 文件名“ id-rsa.pub”看起来可疑地像公用密钥。 The corresponding private key is usually named "id-rsa". 相应的私钥通常称为“ id-rsa”。 Public keys look something like this: 公钥如下所示:

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

Whereas unencypted private keys look something like this: 未加密的私钥看起来像这样:

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

and encrypted private keys like this: 和加密的私钥,如下所示:

-----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-----

Check to see if you are using the correct key file. 检查您使用的密钥文件是否正确。 You can test it by: 您可以通过以下方式进行测试:

openssl rsa -text -noout -in private_key_file

You shouldn't see any errors. 您应该不会看到任何错误。

The first problem is occurring in this block of code 第一个问题发生在此代码块中

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)

I don't think that from_private_key_file() handles file expansion, so the ~ is interpreted literally as a tilde. 我认为from_private_key_file()处理文件扩展,因此~被字面上解释为波浪号。 Try changing rsa_private_key to the absolute file name. 尝试将rsa_private_key更改为绝对文件名。

Also the print statement in your except clause doesn't print out the exception. 同样,您的except子句中的print语句不会打印出异常。 I suggest changing it to print 'Failed loading {0} : {1}'.format (rsa_private_key, e) . 我建议将其更改为print 'Failed loading {0} : {1}'.format (rsa_private_key, e) You will probably then see the cause of the problem in the following error message: 然后,您可能会在以下错误消息中看到问题的原因:

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

Also, you may need to supply a password to from_private_key_file() if your key is encrypted. 另外,如果密钥已加密,则可能需要向from_private_key_file()提供密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM