0

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 . I given correct path only and my doubt is firstly the error showing Failed loading ~/workspace/ssh/rsa_private_key. but its showing some ssh-agent key failed what is that?

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

Raja Simon
  • 10,126
  • 5
  • 43
  • 74
  • 1
    You should really work on formatting this correctly. It's incredibly hard for people to read it as it is right now. – Matt Jun 24 '14 at 07:25
  • @Matt hey. sorry for the formatting but it`s look fine right now. Can u help me – Raja Simon Jun 24 '14 at 07:43

2 Answers2

1

EDIT After much to and fro, the solution was simply to add user's private key to she ssh agent via ssh-add.


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. The corresponding private key is usually named "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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • so you are saying that only encrypted private keys allowed for sftp transfer ah ? Then i have unencrypted rsa private key. Can you tell me how to encrypt rsa private key? – Raja Simon Jun 24 '14 at 12:17
  • No, I'm not saying that your private key must be encrypted. AFAIK it doesn't have to be. What I am saying is that it appears that you are actually referencing your public key file instead of your private key file. I say this because you posted this output in one of your comments: _"Failed loading /home/ri/workspace/ssh/rsa_private_key/id-rsa.pub : not a valid RSA private key file"_ – mhawke Jun 24 '14 at 12:26
  • Have you tried inspecting the contents of the key file to see whether it looks like the public or private examples that I posted above? Have you tried running the openssl command to display the key? – mhawke Jun 24 '14 at 12:28
  • Oh .. That i changed. This is what right now Establishing SSH connection to: upload.partner.com 19321 ... No handlers could be found for logger "paramiko.transport" Trying ssh-agent key b747f6899b3a450e63bc6faab1625686 ... failed! key cannot be used for signing Trying ssh-agent key 5e08bb83615bcc303ca84abe561ef0a6 ... failed! No existing session – Raja Simon Jun 24 '14 at 12:30
  • Ok . See openssl command gives unable to load Private key. But that is putty file so i changed into openssl private key and that is giving some output.i pointed that openssl private key only – Raja Simon Jun 24 '14 at 12:38
  • Great :S. Try changing the line `agent_keys = agent.get_keys() + (ki,)` to `agent_keys = (ki,)`. The agent key doesn't appear to work, and the SSH session is closed when it is attempted. – mhawke Jun 24 '14 at 12:51
  • Hold that change.... Have you added you ssh key to the agent? Probably not... try running `ssh-add` then run your script again. – mhawke Jun 24 '14 at 12:57
  • Hey u there .. i just lost . see only txt file uploaded to server. I need entire folder uploaded to server how to do that.. i lost – Raja Simon Jun 25 '14 at 09:25
  • @rajasimon : you need to copy files recursively, but there is no variant of `SFTPClient.put()` to handle that so you need to implement it yourself. Take a look at this [answer](http://stackoverflow.com/a/4411048/21945). – mhawke Jun 25 '14 at 11:14
  • Thanks but seems that looks hard to me .. Shall i use this one [Link](http://stackoverflow.com/a/19974994/3762142) – Raja Simon Jun 25 '14 at 11:26
0

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. Try changing rsa_private_key to the absolute file name.

Also the print statement in your except clause doesn't print out the exception. I suggest changing it to 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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • i changed the code the way you suggested, rsa-private key is passed but 'NoneType' object has no attribute 'ppk' error is comming – Raja Simon Jun 24 '14 at 08:43
  • sorry then i give correct file name now i am getting Establishing SSH connection to: upload.partner.com 19321 ... Failed loading /home/ri/workspace/ssh/rsa_private_key/id-rsa.pub : not a valid RSA private key file No handlers could be found for logger "paramiko.transport" Trying ssh-agent key b747f6899b3a450e63bc6faab1625686 ... failed! key cannot be used for signing *** Caught exception: : 'NoneType' object has no attribute 'get_fingerprint' – Raja Simon Jun 24 '14 at 08:49
  • i converted the file putty private key file into openssh format but this time key cant be used for sigining and trying ssh agent key failed. No exiting session – Raja Simon Jun 24 '14 at 09:19
  • @rajasimon - You've accepted my answer but you still seem to have a problem? It sounds as if the format of your private key file is not supported. It should contain an RSA private key in PEM format. The first line of the file should start with this: `-----BEGIN RSA PRIVATE KEY-----`. You can generate an RSA key pair, with or without passphrase, using `ssh-keygen`. You can also generate one (with passphrase) using `openssl genrsa -aes256 -out my_rsa_private_key.pem 2048` – mhawke Jun 24 '14 at 11:06
  • Hey thanks for the comment. I accepted your ans bcse that error gone. Now my problem is i only have my client private and public key. And i am trying to setup whether the files is uploading or not. See the above code is checking my local known_hosts then its going to password. I dont have the password i only have my client rsa and username. I dont have much exp with python to modify the code. – Raja Simon Jun 24 '14 at 11:45
  • but i discovered that paramiko does support without known_hosts. See this link [missing known_hosts](http://docs.paramiko.org/en/1.13/api/client.html?highlight=missing#paramiko.client.MissingHostKeyPolicy.missing_host_key) – Raja Simon Jun 24 '14 at 11:55