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


Python secrets.token_hex方法代码示例

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


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

示例1: upgrade

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def upgrade():
    conn = op.get_bind()
    session = Session(bind=conn)

    op.add_column('organisation', sa.Column('external_auth_username', sa.String(), nullable=True))
    op.add_column('organisation', sa.Column('_external_auth_password', sa.String(), nullable=True))

    tcr = sa.sql.table('organisation',
                       sa.Column('id', sa.Integer, primary_key=True),
                       sa.Column('external_auth_username', sa.String(), nullable=True),
                       sa.Column('_external_auth_password', sa.String(), nullable=True),
                       sa.Column('name', sa.String(), nullable=True))

    for org in session.query(tcr).execution_options(show_all=True).all():
        org.external_auth_username = 'admin_'+(org.name or '').lower().replace(' ', '_')
        org._external_auth_password = encrypt_string(secrets.token_hex(16))
    session.commit() 
开发者ID:teamsempo,项目名称:SempoBlockchain,代码行数:19,代码来源:961ab9adc300_.py

示例2: vm_set_mac

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def vm_set_mac(vm, mac):
    """Change MAC address for VM

    :param vm: Virtual machine name.
    :param mac: New MAC address.
    :return: returncode, stdout, stderr.
    """
    logging.debug(f'Changing MAC address for VM "{vm}".')
    if mac == 'new':
        # Generate new MAC in VirtualBox range (080027xxxxxx)
        mac = f'080027{secrets.token_hex(3)}'
    if mac == 'random':
        # Fully random MAC
        mac = secrets.token_hex(6)
    result = vboxmanage(f'modifyvm {vm} --macaddress1 {mac}')
    if result[0] == 0:
        logging.debug('MAC changed.')
    else:
        logging.error(f'Unable to change MAC address: {result[2]}')
    return result[0], result[1], result[2] 
开发者ID:Pernat1y,项目名称:vm-automation,代码行数:22,代码来源:vm_functions.py

示例3: test_user_code_execute

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_user_code_execute():
    """
    User logs in, starts a server & executes code
    """
    # This *must* be localhost, not an IP
    # aiohttp throws away cookies if we are connecting to an IP!
    hub_url = 'http://localhost'
    username = secrets.token_hex(8)

    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'set', 'auth.type', 'dummyauthenticator.DummyAuthenticator')).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'reload')).wait()

    async with User(username, hub_url, partial(login_dummy, password='')) as u:
            await u.login()
            await u.ensure_server()
            await u.start_kernel()
            await u.assert_code_output("5 * 4", "20", 5, 5)

            # Assert that the user exists
            assert pwd.getpwnam(f'jupyter-{username}') is not None 
开发者ID:jupyterhub,项目名称:the-littlest-jupyterhub,代码行数:22,代码来源:test_hub.py

示例4: test_user_admin_add

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_user_admin_add():
    """
    User is made an admin, logs in and we check if they are in admin group
    """
    # This *must* be localhost, not an IP
    # aiohttp throws away cookies if we are connecting to an IP!
    hub_url = 'http://localhost'
    username = secrets.token_hex(8)

    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'set', 'auth.type', 'dummyauthenticator.DummyAuthenticator')).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'add-item', 'users.admin', username)).wait()
    assert 0 == await (await asyncio.create_subprocess_exec(*TLJH_CONFIG_PATH, 'reload')).wait()

    async with User(username, hub_url, partial(login_dummy, password='')) as u:
            await u.login()
            await u.ensure_server()

            # Assert that the user exists
            assert pwd.getpwnam(f'jupyter-{username}') is not None

            # Assert that the user has admin rights
            assert f'jupyter-{username}' in grp.getgrnam('jupyterhub-admins').gr_mem


# FIXME: Make this test pass 
开发者ID:jupyterhub,项目名称:the-littlest-jupyterhub,代码行数:27,代码来源:test_hub.py

示例5: call_web_app

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def call_web_app(url, headers):

    # Generate an HTTP 'traceparent' distributed tracing header
    # (per the W3C Trace Context proposed specification).
    headers['traceparent'] = "00-{0}-{1}-00".format(
        secrets.token_hex(16), secrets.token_hex(8))

    retries = 600
    for i in range(retries):
        try:
            response = requests.post(
                url, json=input, headers=headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if i == retries - 1:
                raise e
            print(e)
            print("Retrying...")
            time.sleep(1) 
开发者ID:microsoft,项目名称:MLOpsPython,代码行数:22,代码来源:smoke_test_scoring_service.py

示例6: detect_wildcard

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def detect_wildcard(domain, authoritative_ns):
    """
    Detect use wildcard dns record or not

    :param  str  domain:  domain
    :param  list authoritative_ns: authoritative name server
    :return bool use wildcard dns record or not
    """
    logger.log('INFOR', f'Detecting {domain} use wildcard dns record or not')
    token = secrets.token_hex(4)
    random_subdomain = f'{token}.{domain}'
    resolver = utils.dns_resolver()
    resolver.nameservers = authoritative_ns
    resolver.rotate = True
    resolver.cache = None
    try:
        wildcard = do_query_a(random_subdomain, resolver)
    except Exception as e:
        logger.log('DEBUG', e.args)
        logger.log('ALERT', f'Multiple detection errors, so temporarily {domain} does not use wildcard dns record')
        return False
    else:
        return wildcard 
开发者ID:shmilylty,项目名称:OneForAll,代码行数:25,代码来源:brute.py

示例7: test_mk_config_bootstrap

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_mk_config_bootstrap(self, mock_hub):
        '''
        test heist.salt_master.mk_config when expecting bootstrap to be
        returned
        '''
        t_name = secrets.token_hex()
        root_dir = 'test_dir'
        roster = {'master': '1.1.1.1', 'master_port': '4506'}
        mock_hub.heist.ROSTERS = {t_name: roster}
        mock_hub.heist.init.ip_is_loopback.return_value = False
        minion_config = heist.heist.salt_master.mk_config(mock_hub, root_dir, t_name)
        with open(minion_config, 'r') as min_conf:
            conf = dict(line.strip().split(': ') for line in min_conf.readlines())

        for key, default in [('master', '127.0.0.1'),
                             ('master_port', '44506'),
                             ('publish_port', '44505')]:
            if roster.get(key):
                assert conf[key] == roster[key]
            else:
                assert conf[key] == default

        roster_data = mock_hub.heist.ROSTERS
        assert roster_data[list(roster_data.keys())[0]]['bootstrap']
        assert conf['root_dir'] == root_dir 
开发者ID:saltstack,项目名称:heist,代码行数:27,代码来源:test_salt_master.py

示例8: test_detect_os

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_detect_os(self,
                             mock_hub):
        '''
        test heist.heist.salt_master.detect_os
        when returncode is 0 and os is linux
        '''
        cmd_ret = asyncssh.process.SSHCompletedProcess(
            command={'uname -a'},
            exit_status=0,
            returncode=0,
            stdout='Linux test-name 5.0',
            stderr='')

        # Setup
        t_name = secrets.token_hex()
        mock_hub.tunnel.asyncssh.cmd.return_value = cmd_ret
        ret = await heist.heist.salt_master.detect_os(mock_hub, t_name, 'asyncssh')
        assert ret == 'linux' 
开发者ID:saltstack,项目名称:heist,代码行数:20,代码来源:test_salt_master.py

示例9: test_get_start_cmd

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_get_start_cmd(self,
                                 mock_hub: testing.MockHub):
        '''
        test heist.heist.salt_master._get_start_cmd when systemctl exists
        '''
        # Setup
        t_name = secrets.token_hex()
        run_dir = os.path.join(os.sep, 'var', 'tmp', 'test')
        mock_hub.heist.ROSTERS[t_name]['bootstrap'] = True
        cmd_ret = asyncssh.process.SSHCompletedProcess(
            command={'which systemctl'},
            exit_status=0,
            returncode=0,
            stdout='/usr/bin/systemctl',
            stderr='')

        mock_hub.tunnel.asyncssh.cmd.return_value = cmd_ret

        ret = await heist.heist.salt_master._get_start_cmd(mock_hub, 'asyncssh', t_name,
                                                           os.path.join(run_dir, 'salt-2019.2.2'),
                                                           run_dir, os.path.join(run_dir, 'pfile'))
        assert ret == 'systemctl start salt-minion' 
开发者ID:saltstack,项目名称:heist,代码行数:24,代码来源:test_salt_master.py

示例10: test_get_artifact

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_get_artifact(self,
                                mock_hub: testing.MockHub,
                                tmp_path):
        '''
        test heist.salt_master.get_artifact
        when artifact does not already exist
        '''
        t_name = secrets.token_hex()
        ver = '2019.2.1'

        art_l = os.path.join(tmp_path, f'salt-{ver}')
        os.mknod(art_l)

        mock_hub.artifact.salt.fetch.return_value = art_l
        mock_hub.heist.salt_master.latest.return_value = False
        ret = await heist.artifact.salt_artifact.get_artifact(mock_hub, t_name,
                                                              'asyncssh', tmp_path,
                                                              'linux', ver)
        assert ret 
开发者ID:saltstack,项目名称:heist,代码行数:21,代码来源:test_salt_artifact.py

示例11: test_get_artifact_exists

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def test_get_artifact_exists(self,
                                       mock_hub: testing.MockHub,
                                       tmp_path):
        '''
        test heist.salt_master.get_artifact
        when artifact already exists
        '''
        t_name = secrets.token_hex()
        ver = '2019.2.1'

        art_l = os.path.join(tmp_path, f'salt-{ver}')

        mock_hub.artifact.salt.fetch.return_value = art_l
        mock_hub.heist.salt_master.latest.return_value = True
        ret = await heist.artifact.salt_artifact.get_artifact(mock_hub, t_name,
                                                              'asyncssh', tmp_path,
                                                              'linux', ver)
        assert ret
        mock_hub.artifact.salt.fetch.assert_not_called() 
开发者ID:saltstack,项目名称:heist,代码行数:21,代码来源:test_salt_artifact.py

示例12: api_organization_create

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def api_organization_create(self, client_ctx, msg):
        msg = apiv1_organization_create_serializer.req_load(msg)

        bootstrap_token = token_hex(self.bootstrap_token_size)
        expiration_date = msg.get("expiration_date", None)
        try:
            await self.create(
                msg["organization_id"],
                bootstrap_token=bootstrap_token,
                expiration_date=expiration_date,
            )

        except OrganizationAlreadyExistsError:
            return {"status": "already_exists"}

        rep = {"bootstrap_token": bootstrap_token, "status": "ok"}
        if expiration_date:
            rep["expiration_date"] = expiration_date

        return apiv1_organization_create_serializer.rep_dump(rep) 
开发者ID:Scille,项目名称:parsec-cloud,代码行数:22,代码来源:organization.py

示例13: createRandomRuns

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def createRandomRuns(number):

    edb = ExperimentalDB()
    users = ["ggilestro", "afrench", "hjones", "mjoyce", "ebeckwith", "qgeissmann"]
    ethoscopes = {"ETHOSCOPE_%03d" % num : eid for (num, eid) in zip (range(1,150), [secrets.token_hex(8) for i in range(149)] ) }
    
    for run in [secrets.token_hex(8) for i in range(number)]:
        user = random.choice(users)
        user_id = users.index(user)
        ethoscope_name = random.choice([n for n in ethoscopes.keys()])
        ethoscope_id = ethoscopes[ethoscope_name]
        location = random.choice(["Incubator_%02d" % i for i in range(1,11)])
        date = random_date(datetime.datetime(2020,1,1), datetime.datetime(2020,12,31)).strftime("%Y-%m-%d_%H-%M-%S")
        database = "%s_%s.db" % (date, ethoscope_id)
        filepath = "/ethoscope_data/results/%s/%s/%s/%s" % (ethoscope_id, ethoscope_name, date, database)
        r = edb.addRun(run, "tracking", ethoscope_name, ethoscope_id, user, user_id, location, random.choice([1,0]), "", filepath)
        print (r) 
开发者ID:gilestrolab,项目名称:ethoscope,代码行数:19,代码来源:etho_db.py

示例14: make_interaction_data

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def make_interaction_data(message: discord.Message, interaction_name: str, interaction_url: str, url_hash: str):
    """

    :param message:
    :type message:
    :param interaction_name:
    :type interaction_name:
    :param interaction_url:
    :type interaction_url:
    :param url_hash:
    :type url_hash:
    :return:
    :rtype:
    """
    return {
        'name': interaction_name.lower(),
        'user_id': message.author.id,
        'server_id': message.guild.id,
        'url': interaction_url,
        'hash': url_hash,
        'interaction_id': secrets.token_hex(4),
        'message_id': None,
        'reported': False,
        'active': False
    } 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:27,代码来源:addinteraction.py

示例15: addstatus

# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import token_hex [as 别名]
def addstatus(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        status_text = ' '.join(pld.args)
        status_exists = await cmd.db[cmd.db.db_nam].StatusFiles.find_one({'text': status_text})
        if not status_exists:
            status_id = secrets.token_hex(5)
            await cmd.db[cmd.db.db_nam].StatusFiles.insert_one({'text': status_text, 'id': status_id})
            response = ok(f'Added status `{status_id}`.')
        else:
            response = error('Status already exists.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response) 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:21,代码来源:addstatus.py


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