當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。