当前位置: 首页>>代码示例>>Python>>正文


Python RSAKey.from_private_key_file方法代码示例

本文整理汇总了Python中paramiko.rsakey.RSAKey.from_private_key_file方法的典型用法代码示例。如果您正苦于以下问题:Python RSAKey.from_private_key_file方法的具体用法?Python RSAKey.from_private_key_file怎么用?Python RSAKey.from_private_key_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在paramiko.rsakey.RSAKey的用法示例。


在下文中一共展示了RSAKey.from_private_key_file方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sign_token

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
def sign_token(key_path, fingerprint, data):
    # from agent
    pkey = get_key_from_agent(fingerprint)
    if not pkey:
        # or from file (without passphrase)
        # assuming '.pub' file extension
        if not os.path.exists(key_path[:-4]):
            raise SignatureException('WrongKeyPath')
        try:
            pkey = RSAKey.from_private_key_file(key_path[:-4])
        except PasswordRequiredException:
            raise SignatureException('EncryptedKey')

    if not pkey:
        raise SignatureException('KeyNotFound')

    try:
        # paramiko is inconsistent here in that the agent's key
        # returns Message objects for 'sign_ssh_data' whereas RSAKey
        # objects returns byte strings.
        # Workaround: cast both return values to string and build a
        # new Message object
        s = str(pkey.sign_ssh_data(data))
        m = Message(s)
        m.rewind()
        if not m.get_string() == 'ssh-rsa':
            raise SignatureException('RSAKeyRequired')
        return base64.b64encode(m.get_string())
    except Exception:
        raise SignatureException('SignatureCreateFailure')
开发者ID:cloudControl,项目名称:cctrl,代码行数:32,代码来源:keyhelpers.py

示例2: createClient

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
def createClient(host, username=None, pkeyPath=None):
    """
    Creates an SSH client object that can be used to perform SSH-related
    operations
    """
    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())

    pkey = RSAKey.from_private_key_file(os.path.expanduser(pkeyPath)) if pkeyPath else None
    client.connect(host, username=username, pkey=pkey)
    return client
开发者ID:shaoguangleo,项目名称:dfms,代码行数:13,代码来源:remote.py

示例3: __init__

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
    def __init__(self, cb, config=None, address='', port=58337, backlog=100):
        self.cb = cb

        # Parse config <3
        if config is not None:
            with open(config, 'r') as f:
                cfg = yaml.load(f)
        else:
            cfg = {}

        logfile = cfg.get('logfile', None)
        if logfile is not None:
            paramiko.util.log_to_file(logile)

        host_key_path = cfg.get('host_key', 'server.key')
        host_key_password = cfg.get('host_key_password', None)
        try:
            self.host_key = RSAKey.from_private_key_file(host_key_path, host_key_password)
        except paramiko.ssh_exception.PasswordRequiredException:
            print 'Invalid host_key_password'
            sys.exit(1)
        except IOError:
            print '*****************************************'
            print '**      host_key does not exists!      **'
            print '** In the name of security by default, **'
            print '**   Sheet will generate one for you.  **'
            print '*****************************************'
            RSAKey.generate(2048).write_private_key_file(host_key_path, host_key_password)

        self.handler = Broker.get(cfg.get('auth_handler', 'BaseAuth'))
        self.handler_conf = cfg.get('auth_handler_config', {})

        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind((address, port))
        except Exception as e:
            print 'Bind failed: ', str(e)
            traceback.print_exc()
            sys.exit(1)

        try:
            self.socket.listen(backlog)
        except Exception as e:
            print 'Listen/accept failed:', str(e)
            traceback.print_exc()
            sys.exit(1)
开发者ID:jagheterfredrik,项目名称:sheet,代码行数:49,代码来源:server.py

示例4: public_key

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
def public_key():
    if not path.exists(PATH_TO_KEYFILE):
        abort('Required public key file does not exist. Create it with ssh-keygen.')

    comment = '{}@{}'.format(getuser(), gethostname().split('.')[0])
    pkey = None
    try:
        pkey = RSAKey.from_private_key_file(PATH_TO_KEYFILE)
    except PasswordRequiredException:
        abort('Keys with passphrases are not supported.')

    grep_cmd = 'grep {} "$HOME"/{}'.format(pkey.get_base64(), path.join('.ssh', 'authorized_keys'))
    grep = None
    with hide('everything'):
        grep = run(grep_cmd, warn_only=True)
    if grep.failed:
        with cd('"$HOME"'), hide('everything'):
            run('[ -d .ssh ] || (mkdir -p .ssh; chmod 700 .ssh)')
            key_entry = ' '.join((pkey.get_name(), pkey.get_base64(), comment))
            run('touch .ssh/authorized_keys')
            run('chmod 600 .ssh/authorized_keys')
            run('echo {} >> .ssh/authorized_keys'.format(key_entry))
    puts('Your public key is set up on {}.'.format(env.host_string))
开发者ID:phasetwenty,项目名称:dotfiles,代码行数:25,代码来源:public-key.py

示例5: host_key

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
 def host_key(self):
     return RSAKey.from_private_key_file(SERVER_KEY_PRIVATE)
开发者ID:5monkeys,项目名称:pytest-sftpserver,代码行数:4,代码来源:server.py

示例6: connect

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
    def connect(self, host, port=22, user=None, passw=None, cert=None, path='/', timeout=10):
        """Method connects to server

        Args:
           host (str): server host
           port (int): server port, default protocol port
           user (str): username
           passw (str): password
           cert (str): path to certificate file
           path (str): server path
           timeout (int): timeout

        Returns:
           bool: result

        Raises:
           event: ftp_before_connect
           event: ftp_after_connect

        """

        try:

            message = '{0}/{1}@{2}:{3}{4} cert:{5}, timeout:{6}'.format(
                user, passw, host, port, path, cert, timeout)
            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_ftp_connecting', message), self._mh.fromhere())

            ev = event.Event(
                'ftp_before_connect', host, port, user, passw, cert, path, timeout)
            if (self._mh.fire_event(ev) > 0):
                host = ev.argv(0)
                port = ev.argv(1)
                user = ev.argv(2)
                passw = ev.argv(3)
                cert = ev.argv(4)
                path = ev.argv(5)
                timeout = ev.argv(6)

            self._host = host
            self._port = port
            self._user = user
            self._passw = passw
            self._cert = cert

            if (ev.will_run_default()):
                setdefaulttimeout(timeout)
                t = Transport((host, self._port))

                if (user != None or cert != None):
                    pkey = RSAKey.from_private_key_file(
                        self._cert) if (cert != None) else None
                    t.connect(username=user, password=passw, pkey=pkey)
                    self._client = SFTPClient.from_transport(t)

                self._is_connected = True

                if (path != None):
                    self.change_dir(path)

            ev = event.Event('ftp_after_connect')
            self._mh.fire_event(ev)

            return True

        except (SSHException, NoValidConnectionsError, error) as ex:
            self._mh.demsg(
                'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
            return False
开发者ID:hydratk,项目名称:hydratk-lib-network,代码行数:71,代码来源:sftp_client.py

示例7: app_from_config_file

# 需要导入模块: from paramiko.rsakey import RSAKey [as 别名]
# 或者: from paramiko.rsakey.RSAKey import from_private_key_file [as 别名]
def app_from_config_file(filename):
    """Loads the app from the YAML-encoded config file, and updates
    the config file if needed.

    :param filename: the filename of the config to load
    :type filename: :class:`basestring`
    :returns: the loaded app
    :rtype: :class:`~asuka.app.App`

    """
    dirname = os.path.dirname(filename)
    with open(filename) as fp:
        loaded_config = load(fp)
    config = dict(loaded_config)
    config['ec2_connection'] = connect_to_region(**config['ec2_connection'])
    try:
        private_key = config['private_key']
    except KeyError:
        pass
    else:
        private_key = RSAKey.from_private_key_file(
            os.path.join(dirname, private_key)
        )
        config['private_key'] = private_key
    gh_auth = None
    try:
        gh_token = config['repository']['token']
        gh_repository = config['repository']['repository']
    except KeyError:
        try:
            gh_login = config['repository']['login']
            gh_password = config['repository']['password']
            gh_repository = config['repository']['repository']
        except KeyError:
            gh_token = None
        else:
            gh_auth = authorize(gh_login, gh_password, ['repo'],
                               'Asuka Deployment System')
            gh_token = str(gh_auth.token)
    if gh_token:
        gh = login(token=gh_token)
        config['repository'] = gh.repository(*gh_repository.split('/', 1))
    app, delta = app_from_config(config)
    if gh_auth:
        delta['repository'] = {
            'token': gh_token,
            'repository': gh_repository
        }
    if delta:
        try:
            private_key = delta['private_key']
        except KeyError:
            pass
        else:
            key_filename = app.name + '_id_rsa'
            private_key.write_private_key_file(
                os.path.join(dirname, key_filename)
            )
            delta['private_key'] = key_filename
        loaded_config.update(delta)
        with open(filename, 'w') as fp:
            dump(loaded_config, fp, default_flow_style=False)
    return app
开发者ID:Web5design,项目名称:asuka,代码行数:65,代码来源:config.py


注:本文中的paramiko.rsakey.RSAKey.from_private_key_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。