How to use the paramiko.RSAKey.from_private_key function in paramiko

To help you get started, we’ve selected a few paramiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Mirantis / mos-integration-tests / mos_tests / environment / os_actions.py View on Github external
timeout_seconds=60 * 3,
                    sleep_seconds=10,
                    waiting_for="any alive DHCP agent for instance network",
                    log=False)
            else:
                proxy_nodes = [proxy_node]

            for node in proxy_nodes:
                for pkey in env.admin_ssh_keys:
                    ip = env.find_node_by_fqdn(node).data['ip']
                    proxy = NetNsProxy(ip=ip, pkey=pkey, ns=dhcp_namespace,
                                       proxy_to_ip=vm_ip)
                    proxies.append(proxy)
        instance_keys = []
        if vm_keypair is not None:
            instance_keys.append(paramiko.RSAKey.from_private_key(six.StringIO(
                vm_keypair.private_key)))
        return SSHClient(vm_ip,
                         port=22,
                         username=username,
                         password=password,
                         private_keys=instance_keys,
                         proxies=proxies)
github mytardis / mytardis / tardis / apps / push_to / ssh_authz.py View on Github external
data=json.dumps(payload))
    cert_response = json.loads(r.text)
    if 'certificate' not in cert_response:
        return False

    # Ignore the certificate comment field
    remote_user_name = cert_response['user']
    cert_type, cert_data = cert_response['certificate'].split()[0:2]
    if cert_type != 'ssh-rsa-cert-v01@openssh.com':
        return False  # We only support this certificate type at the moment

    old_key = credential.key
    private_key = StringIO()
    old_key.write_private_key(private_key)
    private_key.seek(0)
    cert = RSAKey.from_private_key(private_key)
    cert.load_certificate(Message(base64.b64decode(cert_data)))
    credential.key = cert
    credential.remote_user = remote_user_name
    credential.save()
    return True
github schasins / helena / utilities / runHelenaScriptDistributed.py View on Github external
def run(self):
			i = self.i

			ip = availableIps[i]
			if debug: print "ip", ip

			try:
				k = paramiko.RSAKey.from_private_key(keystring)
				#k = paramiko.RSAKey.from_private_key_file("/Users/sarahchasins/.ssh/MyKeyPair.pem")
				c = paramiko.SSHClient()
				c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
				if debug: print "connecting"
				c.connect( hostname = ip, username = "ec2-user", pkey = k )
				if debug: print "connected"
				# below, 1 is fixed because for now we only set one browser instance going on any given distributed machine
				# also all our amazon images have chromedriver in the same folder where we run, thus the hardcoded chromedriver loc
				com = "python runHelenaScriptInParallel.py " + str(scriptName) + " 1 " + str(timeouts[i]) + " 1 ./chromedriver " + str(runIdsForThisStage[i]) + ")"
				commands = ['(cd helena/utilities;' + com]
				for command in commands:
				    print "Executing {}".format( command )
				    stdin , stdout, stderr = c.exec_command(command)
				    print stdout.read()

				    # ok, here's where it gets weird.  because if we got errors, we actually want to start this machine up fresh
github candlepin / rho / src / rho / my_sshpt.py View on Github external
def get_pkey(auth):

    if auth.type != config.SSH_KEY_TYPE:
        return None

    fo = StringIO.StringIO(auth.key)
    # this is lame, but there doesn't appear to be any API to just
    # DWIM with the the key_data, I have to figure out if its RSA or DSA/DSS myself
    if fo.readline().find("-----BEGIN DSA PRIVATE KEY-----") > -1:
        fo.seek(0)
        pkey = paramiko.DSSKey.from_private_key(fo, password=auth.password)
        return pkey
    fo.seek(0)
    if fo.readline().find("-----BEGIN RSA PRIVATE KEY-----") > -1:
        fo.seek(0)
        pkey = paramiko.RSAKey.from_private_key(fo, password=auth.password)
        return pkey

    print _("The private key file for %s is not a recognized ssh key type" % auth.name)
    return None
github openstack / mistral / mistral / utils / ssh_utils.py View on Github external
def _to_paramiko_private_key(private_key_filename,
                             private_key=None,
                             password=None):
    if private_key:
        return paramiko.RSAKey.from_private_key(
            file_obj=six.StringIO(private_key),
            password=password)

    if private_key_filename:
        if '../' in private_key_filename or '..\\' in private_key_filename:
            raise exc.DataAccessException(
                "Private key filename must not contain '..'. "
                "Actual: %s" % private_key_filename
            )

        if private_key_filename.startswith('/'):
            private_key_path = private_key_filename
        else:
            private_key_path = KEY_PATH + private_key_filename

        return paramiko.RSAKey(
github bucknerns / sshaolin / sshaolin / client.py View on Github external
accept_missing_host_key=None, timeout=None, compress=None, pkey=None,
        look_for_keys=None, allow_agent=None, key_filename=None,
            proxy_type=None, proxy_ip=None, proxy_port=None, sock=None):
        connect_kwargs = dict(self.connect_kwargs)
        connect_kwargs.update({
            k: locals().get(k) for k in self.connect_kwargs
            if locals().get(k) is not None})
        connect_kwargs["port"] = int(connect_kwargs.get("port"))

        ssh = ExtendedParamikoSSHClient()

        if bool(self.accept_missing_host_key or accept_missing_host_key):
            ssh.set_missing_host_key_policy(AutoAddPolicy())

        if connect_kwargs.get("pkey") is not None:
            connect_kwargs["pkey"] = RSAKey.from_private_key(
                six.BytesIO(six.u(connect_kwargs["pkey"])))

        proxy_type = proxy_type or self.proxy_type
        proxy_ip = proxy_ip or self.proxy_ip
        proxy_port = proxy_port or self.proxy_port
        if connect_kwargs.get("sock") is not None:
            pass
        elif all([proxy_type, proxy_ip, proxy_port]):
            connect_kwargs["sock"] = create_connection(
                (connect_kwargs.get("hostname"), connect_kwargs.get("port")),
                proxy_type, proxy_ip, int(proxy_port))

        ssh.connect(**connect_kwargs)
        return ssh
github delfick / bespin / bespin / operations / ssh.py View on Github external
def retrieve_key(self, host, location, path):
        if os.path.exists(path):
            try:
                current_key = paramiko.RSAKey.from_private_key(open(path))
                if fingerprint(current_key) != self.rattic_fingerprint(host, location):
                    log.info("You current key is not the correct fingerprint, downloading new key\tlooking_at=%s", path)
                else:
                    return False
            except paramiko.ssh_exception.SSHException as error:
                log.error("You current key is invalid (%s), downloading it now\tlooking_at=%s", error, path)
        else:
            log.info("No key found, downloading it now\tlooking_at=%s", path)

        self.rattic_download_key(host, location, path)
        return True
github Salamek / gitlab-tools / gitlab_tools / views / home / index.py View on Github external
def get_home():
    pull_mirrors_count = PullMirror.query.filter_by(is_deleted=False).count()
    push_mirrors_count = PushMirror.query.filter_by(is_deleted=False).count()
    private_key_path = get_user_private_key_path(current_user, flask.current_app.config['USER'])
    if os.path.isfile(private_key_path):

        with open(private_key_path, 'r') as f:
            private_key = paramiko.RSAKey.from_private_key(f)
        fingerprint_md5 = format_md5_fingerprint(calculate_fingerprint(private_key, 'md5'))
        fingerprint_sha256 = format_sha256_fingerprint(calculate_fingerprint(private_key, 'sha256'))
    else:
        private_key = None
        fingerprint_md5 = None
        fingerprint_sha256 = None

    return flask.render_template(
        'home.index.home.html',
        pull_mirrors_count=pull_mirrors_count,
        push_mirrors_count=push_mirrors_count,
        private_key=private_key,
        fingerprint_md5=fingerprint_md5,
        fingerprint_sha256=fingerprint_sha256
    )
github apache / mina-sshd / sshd-sources / python / sftpclient.py View on Github external
password = args.get("password", None)
    keyfile = args.get("keyFile", None)
    keytype = args.get("keyType", "RSA")

    sftp = None
    transport = None
    try:
        key = None
        if keyfile is not None:
            # Get private key used to authenticate user.
            if keytype == 'DSA':
                # The private key is a DSA type key.
                key = paramiko.DSSKey.from_private_key_file(keyfile)
            else:
                # The private key is a RSA type key.
                key = paramiko.RSAKey.from_private_key(keyfile)

        # Create Transport object using supplied method of authentication.
        transport = paramiko.Transport((host, port))
        transport.connect(None, username, password, key)
 
        sftp = paramiko.SFTPClient.from_transport(transport)
        return sftp
    except Exception as e:
        print('An error occurred creating SFTP client: %s: %s' % (e.__class__, e))

        if sftp is not None:
            try:
                sftp.close()
            except Exception as err:
                print('Failed to close SFTP client: %s: %s' % (err.__class__, err))
github dagster-io / dagster / python_modules / libraries / dagster-ssh / dagster_ssh / resources.py View on Github external
def key_from_str(key_str):
    '''Creates a paramiko SSH key from a string.'''
    check.str_param(key_str, 'key_str')

    # py2 StringIO doesn't support with
    key_file = StringIO(key_str)
    result = paramiko.RSAKey.from_private_key(key_file)
    key_file.close()
    return result