SSH/SCP through Paramiko with key in string

I got a great Paramiko Python script to transfer file over SCP protocol. But My need is a single file (script.py) without any other file dependencies so I don't want to have an external file for my SSH private key.

What I'm trying to do is to embed the private key into a string variable and use this variable as the file needed by the script to connect. I tried with the StringIO library but it doesn't seems to work :

hostname = '1.1.1.1' # remote hostname where SSH server is running
port = 22
username = 'user'
password = 'pswd'

dir_local='/home/paramikouser/local_data'
dir_remote = "remote_machine_folder/subfolder"
glob_pattern='*.*'

import os
import glob
import paramiko
import md5
import StringIO

private_key = StringIO.StringIO('-----BEGIN RSA PRIVATE KEY-----\n-----END RSA PRIVATE KEY-----')

def agent_auth(transport, username):
    """
    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(private_key)
    except Exception, e:
        print 'Failed loading' % (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 %s' % key.get_fingerprint().encode('hex'),
        try:
            transport.auth_publickey(username, key)
            print '... success!'
            return
        except paramiko.SSHException, e:
            print '... failed!', e

# get host key, if we know one
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 = {}

if host_keys.has_key(hostname):
    hostkeytype = host_keys[hostname].keys()[0]
    hostkey = host_keys[hostname][hostkeytype]
    print 'Using host key of type %s' % hostkeytype

# now, connect and use paramiko Transport to negotiate SSH2 across the connection
try:
    print 'Establishing SSH connection to:', hostname, port, '...'
    t = paramiko.Transport((hostname, port))
    t.start_client()

    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)
# dirlist on remote host
#    dirlist = sftp.listdir('.')
#    print "Dirlist:", dirlist

How can I use this string as a key?


Use RSAKey.from_private_key:

ki = paramiko.RSAKey.from_private_key(private_key)

See How do use paramiko.RSAKey.from_private_key()?


The answer on the above question shows code for Python 3.

In Python 2.7, this works:

import os
import glob
import paramiko
import StringIO 

private_key_file = StringIO.StringIO()
private_key_file.write('-----BEGIN RSA PRIVATE KEY-----\nMIIEoQIBAAKCAQEAvG9YlF2da0jJ5PvvlmVnVnYYFc7kkJuC0wvsACVuvep/sds5\nIEX0e+/rq9UBj/V3rzsvbHzb6IVulSjEqcM32NA4SyqR1m5jAj/WVDXQcxzruBDO\nZbdNhDS1T4+HckTWzttAE4o83bRju+3BhR9CtrDtt+7CSei4MccSMEH7yxo1BGuL\nONfkhB6qAWh55T6tamTyjLg9R9xqBkG6x3ZmoOB9j/11P5awuUoE1DfbqQ3KMLSR\nr64unavECfBaBYvuxlWbxRJFAN8C95oE+Kbc1g1bEL9du6FIeHZ/eaBbkcl84Fm7\nswdHBnd7+tqfo4TGzvbEW4H2ZQLiuiGK23ao0wIBJQKCAQEAiYGvV4KVd81VDuFb\nzp0GOCypyrmSCKjVFowowdYgYRLnj5/5QRB0IxbcaKJbFgYm56e60qBNclOIC/sn\nuiasNm5uRLBclY7SoMbM1aq6tN3AxJakc70c4+8chip3mJMZStdYRZw6QOtrX5+o\n5JpFcI7yqNDS96nShTBnN/jMf3K6yjQjvTv/DJi9SHJ6dTtrY1AuUNEoiO3cwgeH\nFks169756L+fpweL4VjQl4UyClL0bwHWpe579XzjBV0AlGu1tHaE5zslTPtGw1lg\nnZhj/7skZKAIGQxIzfmGv4QEcvePKYzM8EUhOr/0O3BHjLC0lp5hMwmsPJfaHlMb\nBak0JQKBgQD0cRu65WNkCcRlpuUvp5/kiMvu7PmcFUsY6dMeV0bL4oQ+PCqfwXFj\nhkyS7V2DJnllYPwi6E68soie+IL1blmY7hWcoznJ48PWJ0bJmqBgzhpC623RtTKS\ny/O0IbrGKPpaRGfD/PAvqJOpwx7Im2k6/UVQ0OYSurC8CB3BDRTCXQKBgQDFWEq7\ny2SntPFA9zu+31bW57lb26l8nNmUXmRLnXyvqomAkCGSadiW/i5nBEBDV/zJ/rXp\n0QWrmrpfvjnMF6g26m4sj6Pfs5zoSV1+FEidqYDcytUPJnpR55Ulpshf57TGuFbx\n1SCnda1dmm3TzAzzKTc6MbSPV0krMyAgCP7E7wKBgFXijTPUDioRRQEe9pQz+eiD\nFzhFbHUcPPrqXu78EfSbsexaVCpK4qZtdNmtWDT/rhyzX4Hi6zthUpi4LgM0nAVM\nu3w5WX5JG0s+O3dEKoLgoXF1UBk/qfw50iqIZDfJNV38W889McuOQbgvzIusObrH\nsJIENSks1k/nLQx6N7npAoGAUAEzDdzVx3LeWJuUwwCY06oM4Azxrw8nxochvco5\nd6YAZI11ZN7NbaVRFQG5MA7p8QZlbKDYyQdgUFQJl+3qP8bSuB6Oix9Ncu1Panbt\nAaWVGz14+E3ej+hDYkqIlZVJSaStoE978NyuETDEvaXAD40/5yjoVclwsKYGGtM2\n2jcCgYA6v1tvd2QdDeijiSRnXAeJ1hDLB8Jj2WJqnDZ7dQ5+XTIKfY4POIpHCPx8\n6Uk4NCnyJGmBHog1M7Bjb/o0c1UTid6CNBI4ciVaRyXXcy6Czup2EhkiNGom2883\n8+9pdxShKf0pJCqdZxJdVmg1NHZnr20PwN7PASbVcRg3t+wt2g==\n-----END RSA PRIVATE KEY-----')
private_key_file.seek(0)

ki = paramiko.RSAKey.from_private_key(private_key_file)