Best Python code snippet using localstack_python
iam.py
Source:iam.py
...135 except Exception as e:136 printInfo('Failed')137 printException(e)138 errors.append(e.response['Error']['Code'])139 delete_virtual_mfa_device(iam_client, serial)140 if mfa_serial:141 delete_virtual_mfa_device(iam_client, mfa_serial)142 except Exception as e:143 printException(e)144 printError('Faile to fetch/delete MFA device serial number for user %s.' % user)145 errors.append(e.response['Error']['Code'])146 # Remove IAM user from groups147 try:148 groups = iam_client.list_groups_for_user(UserName = user)['Groups']149 for group in groups:150 try:151 printInfo('Removing from group %s... ' % group['GroupName'], False)152 iam_client.remove_user_from_group(GroupName = group['GroupName'], UserName = user)153 printInfo('Success')154 except Exception as e:155 printInfo('Failed')156 printException(e)157 errors.append(e.response['Error']['Code'])158 except Exception as e:159 printException(e)160 printError('Failed to fetch IAM groups for user %s.' % user)161 errors.append(e.response['Error']['Code'])162 # Delete login profile163 login_profile = []164 try:165 login_profile = iam_client.get_login_profile(UserName = user)['LoginProfile']166 except Exception as e:167 pass168 try:169 if len(login_profile):170 printInfo('Deleting login profile... ', False)171 iam_client.delete_login_profile(UserName = user)172 printInfo('Success')173 except Exception as e:174 printInfo('Failed')175 printException(e)176 errors.append(e.response['Error']['Code'])177 # Delete inline policies178 try:179 printInfo('Deleting inline policies... ', False)180 policies = iam_client.list_user_policies(UserName = user)181 for policy in policies['PolicyNames']:182 iam_client.delete_user_policy(UserName = user, PolicyName = policy)183 printInfo('Success')184 except Exception as e:185 printInfo('Failed')186 printException(e)187 errors.append(e.response['Error']['Code'])188 # Detach managed policies189 try:190 printInfo('Detaching managed policies... ', False)191 policies = iam_client.list_attached_user_policies(UserName = user)192 for policy in policies['AttachedPolicies']:193 iam_client.detach_user_policy(UserName = user, PolicyArn = policy['PolicyArn'])194 printInfo('Success')195 except Exception as e:196 printInfo('Failed')197 printException(e)198 errors.append(e.response['Error']['Code'])199 # Delete IAM user200 try:201 if not keep_user:202 iam_client.delete_user(UserName = user)203 printInfo('User %s deleted.' % user)204 else:205 for group in terminated_groups:206 add_user_to_group(iam_client, group, user)207 except Exception as e:208 printException(e)209 printError('Failed to delete user.')210 errors.append(e.response['Error']['Code'])211 pass212 return errors213def delete_virtual_mfa_device(iam_client, mfa_serial):214 """215 Delete a vritual MFA device given its serial number216 :param iam_client:217 :param mfa_serial:218 :return:219 """220 try:221 printInfo('Deleting MFA device %s...' % mfa_serial)222 iam_client.delete_virtual_mfa_device(SerialNumber = mfa_serial)223 except Exception as e:224 printException(e)225 printError('Failed to delete MFA device %s' % mfa_serial)226 pass227def get_access_keys(iam_client, user_name):228 """229 :param iam_client:230 :param user_name:231 :return:232 """233 keys = handle_truncated_response(iam_client.list_access_keys, {'UserName': user_name}, ['AccessKeyMetadata'])['AccessKeyMetadata']234 return keys235def init_group_category_regex(category_groups, category_regex_args):236 """...
awsrecipes_enable_mfa.py
Source:awsrecipes_enable_mfa.py
...24from opinel.utils.globals import check_requirements25########################################26##### Helpers27########################################28def delete_virtual_mfa_device(iam_client, mfa_serial):29 """30 Delete a vritual MFA device given its serial number31 :param iam_client:32 :param mfa_serial:33 :return:34 """35 try:36 printInfo('Deleting MFA device %s...' % mfa_serial)37 iam_client.delete_virtual_mfa_device(SerialNumber = mfa_serial)38 except Exception as e:39 printException(e)40 printError('Failed to delete MFA device %s' % mfa_serial)41 pass42def display_qr_code(png, seed):43 """44 Display MFA QR code45 :param png:46 :param seed:47 :return:48 """49 # This NamedTemporaryFile is deleted as soon as it is closed, so50 # return it to caller, who must close it (or program termination51 # could cause it to be cleaned up, that's fine too).52 # If we don't keep the file around until after the user has synced53 # his MFA, the file will possibly be already deleted by the time54 # the operating system gets around to execing the browser, if55 # we're using a browser.56 qrcode_file = tempfile.NamedTemporaryFile(suffix='.png', delete=True, mode='wt')57 qrcode_file.write(png)58 qrcode_file.flush()59 if _fabulous_available:60 fabulous.utils.term.bgcolor = 'white'61 with open(qrcode_file.name, 'rb') as png_file:62 print(fabulous.image.Image(png_file, 100))63 else:64 graphical_browsers = [webbrowser.BackgroundBrowser,65 webbrowser.Mozilla,66 webbrowser.Galeon,67 webbrowser.Chrome,68 webbrowser.Opera,69 webbrowser.Konqueror]70 if sys.platform[:3] == 'win':71 graphical_browsers.append(webbrowser.WindowsDefault)72 elif sys.platform == 'darwin':73 graphical_browsers.append(webbrowser.MacOSXOSAScript)74 browser_type = None75 try:76 browser_type = type(webbrowser.get())77 except webbrowser.Error:78 pass79 if browser_type in graphical_browsers:80 printError("Unable to print qr code directly to your terminal, trying a web browser.")81 webbrowser.open('file://' + qrcode_file.name)82 else:83 printInfo("Unable to print qr code directly to your terminal, and no graphical web browser seems available.")84 printInfo("But, the qr code file is temporarily available as this file:")85 printInfo("\n %s\n" % qrcode_file.name)86 printInfo("Alternately, if you feel like typing the seed manually into your MFA app:")87 # this is a base32-encoded binary string (for case88 # insensitivity) which is then dutifully base64-encoded by89 # amazon before putting it on the wire. so the actual90 # secret is b32decode(b64decode(seed)), and what users91 # will need to type in to their app is just92 # b64decode(seed). print that out so users can (if93 # desperate) type in their MFA app.94 printInfo("\n %s\n" % base64.b64decode(seed))95 return qrcode_file96def enable_mfa(iam_client, user, qrcode_file = None):97 """98 Create and activate an MFA virtual device99 :param iam_client:100 :param user:101 :param qrcode_file:102 :return:103 """104 mfa_serial = ''105 tmp_qrcode_file = None106 try:107 printInfo('Enabling MFA for user \'%s\'...' % user)108 mfa_device = iam_client.create_virtual_mfa_device(VirtualMFADeviceName = user)['VirtualMFADevice']109 mfa_serial = mfa_device['SerialNumber']110 mfa_png = mfa_device['QRCodePNG']111 mfa_seed = mfa_device['Base32StringSeed']112 tmp_qrcode_file = display_qr_code(mfa_png, mfa_seed)113 if qrcode_file != None:114 with open(qrcode_file, 'wt') as f:115 f.write(mfa_png)116 while True:117 mfa_code1 = prompt_4_mfa_code()118 mfa_code2 = prompt_4_mfa_code(activate = True)119 if mfa_code1 == 'q' or mfa_code2 == 'q':120 try:121 delete_virtual_mfa_device(iam_client, mfa_serial)122 except Exception as e:123 printException(e)124 pass125 raise Exception126 try:127 iam_client.enable_mfa_device(UserName = user, SerialNumber = mfa_serial, AuthenticationCode1= mfa_code1, AuthenticationCode2 = mfa_code2)128 printInfo('Succesfully enabled MFA for for \'%s\'. The device\'s ARN is \'%s\'.' % (user, mfa_serial))129 break130 except Exception as e:131 printException(e)132 pass133 except Exception as e:134 printException(e)135 # We shouldn't return normally because if we've gotten here...
aws_utils.py
Source:aws_utils.py
...104 def deactivate_mfa_device(self, user, serial):105 iam = self.iam106 response = iam.deactivate_mfa_device(UserName=user,SerialNumber=serial)107 108 def delete_virtual_mfa_device(self, user, serial):109 iam = self.iam110 self.deactivate_mfa_device(user, serial)111 response = iam.delete_virtual_mfa_device(SerialNumber=serial)112 def create_iam_users(self, user_list):113 iam = self.iam114 created_users = []115 create_failed = []116 create_error_dict = {}117 for user in user_list:118 user_exist = self.check_if_user_exists(user)119 if not user_exist:120 try:121 iam.create_user(UserName=user)122 created_users.append(user)123 except Exception as error:124 create_failed.append(user)125 create_error_dict[user] = error.response['Error']['Message']126 self.logger.exception(error)127 return created_users, create_failed, create_error_dict128 def remove_ssh_public_keys(self, user):129 iam = self.iam130 response = iam.list_ssh_public_keys(UserName=user)131 if 'SSHPublicKeys' in response and response['SSHPublicKeys']:132 for key in response['SSHPublicKeys']:133 iam.delete_ssh_public_key(UserName=user, SSHPublicKeyId=key['SSHPublicKeyId'])134 def remove_service_specific_credentials(self, user):135 iam = self.iam136 response = iam.list_service_specific_credentials(UserName=user)137 if 'ServiceSpecificCredentials' in response and response['ServiceSpecificCredentials']:138 iam.delete_service_specific_credential(UserName=user,139 ServiceSpecificCredentialId=response['ServiceSpecificCredentials']['ServiceSpecificCredentialId'])140 141 def remove_mfa_devices(self, user):142 devices = self.list_mfa_devices(user)143 if devices:144 for device in devices:145 self.delete_virtual_mfa_device(user, device['SerialNumber'])146 def remove_from_groups(self, user):147 groups = self.get_user_groups(user)148 if groups:149 for group_name in groups:150 if group_name != self.config.exclusion_group:151 self.remove_user_from_group(group_name, user)152 def delete_iam_users(self, user_list):153 iam = self.iam154 delete_failed = []155 deleted_users = []156 delete_error_dict = {}157 for user in user_list:158 user_exist = self.check_if_user_exists(user)159 if user_exist:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!