def Run(self, args): """Update a Database Migration Service connection profiles. Args: args: argparse.Namespace, The arguments that this command was invoked with. Returns: A dict object representing the operations resource describing the create operation if the create was successful. """ connection_profile_ref = args.CONCEPTS.connection_profile.Parse() if args.prompt_for_password: args.password = console_io.PromptPassword( 'Please Enter Password: '******'datamigration.projects.locations.operations', operationsId=result_operation.name, projectsId=connection_profile_ref.projectsId, locationsId=connection_profile_ref.locationsId) return client.projects_locations_operations.Get( messages.DatamigrationProjectsLocationsOperationsGetRequest( name=operation_ref.operationsId))
def testPromptPassword(self): self.mock_getpass.side_effect = self._GetFakeGetPass( 'PasswordPrompt:', 'the_passwd') self.SetAnswers('the_passwd') result = console_io.PromptPassword('PasswordPrompt:') self.assertIn('PasswordPrompt', self.GetErr()) self.assertEqual(result, 'the_passwd')
def Run(self, args): """Runs the command to import into the Cloud SQL instance.""" if args.prompt_for_pvk_password: args.pvk_password = console_io.PromptPassword( 'Private Key Password: ') client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) return import_util.RunBakImportCommand(args, client)
def Run(self, args): """Create service account credentials.""" file_content, is_json = _IsJsonFile(args.key_file) if is_json: if _UseGoogleAuth(): cred = auth_service_account.CredentialsFromAdcDictGoogleAuth( file_content) else: # TODO(b/161992086): Remove the flow of activating via oauth2client once # this legacy auth lib is deprecated. Leave this option for now so that # the users are able to fall back to the old flow of if any issues # related to google-auth comes up. The users can do this by setting # property auth/disable_activate_service_account_google_auth to True. cred = auth_service_account.CredentialsFromAdcDict( file_content) if args.password_file or args.prompt_for_password: raise c_exc.InvalidArgumentException( '--password-file', 'A .json service account key does not require a password.') account = cred.service_account_email if args.account and args.account != account: raise c_exc.InvalidArgumentException( 'ACCOUNT', 'The given account name does not match the account name in the key ' 'file. This argument can be omitted when using .json keys.' ) else: account = args.account if not account: raise c_exc.RequiredArgumentException( 'ACCOUNT', 'An account is required when using .p12 keys') password = None if args.password_file: try: password = files.ReadFileContents( args.password_file).strip() except files.Error as e: raise c_exc.UnknownArgumentException('--password-file', e) elif args.prompt_for_password: password = console_io.PromptPassword('Password: '******'Activated service account credentials for: [{0}]'.format(account))
def PromptForAuthCode(): """Prompts the user to enter the auth code.""" message = ('Please provide the authorization code from the domain\'s current ' 'registrar to transfer the domain.') log.status.Print(message) auth_code = console_io.PromptPassword( prompt='Authorization code: ', error_message=' Authorization code must not be empty.', validation_callable=ValidateNonEmpty) return auth_code
def Run(self, args): """Create service account credentials.""" file_content, is_json = _IsJsonFile(args.key_file) if is_json: cred = auth_service_account.CredentialsFromAdcDictGoogleAuth( file_content) if args.password_file or args.prompt_for_password: raise c_exc.InvalidArgumentException( '--password-file', 'A .json service account key does not require a password.') account = cred.service_account_email if args.account and args.account != account: raise c_exc.InvalidArgumentException( 'ACCOUNT', 'The given account name does not match the account name in the key ' 'file. This argument can be omitted when using .json keys.' ) else: account = args.account if not account: raise c_exc.RequiredArgumentException( 'ACCOUNT', 'An account is required when using .p12 keys') password = None if args.password_file: try: password = files.ReadFileContents( args.password_file).strip() except files.Error as e: raise c_exc.UnknownArgumentException('--password-file', e) elif args.prompt_for_password: password = console_io.PromptPassword('Password: '******'Activated service account credentials for: [{0}]'.format(account))
def Run(self, args): """Changes a user's password in a given instance. Args: args: argparse.Namespace, The arguments that this command was invoked with. Returns: SQL user resource iterator. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages if args.prompt_for_password: args.password = console_io.PromptPassword('Instance Password: '******'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') operation_ref = None result_operation = sql_client.users.Update( sql_messages.SqlUsersUpdateRequest( project=instance_ref.project, instance=args.instance, name=args.username, host=args.host, user=sql_messages.User( project=instance_ref.project, instance=args.instance, name=args.username, host=args.host, password=args.password))) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result_operation.name, project=instance_ref.project) if args.async_: return sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) operations.OperationsV1Beta4.WaitForOperation(sql_client, operation_ref, 'Updating Cloud SQL user')
def _GetLdapUserAndPass(cluster_config, auth_name, cluster): """Prompt User for Ldap Username and Password.""" ldap_user = None ldap_pass = None if not cluster_config.IsLdap(): return None, None # do the prompting user_message = ('Please enter the ldap user for ' '[{}] on cluster [{}]: '.format(auth_name, cluster)) pass_message = ('Please enter the ldap password for ' '[{}] on cluster [{}]: '.format(auth_name, cluster)) ldap_user = console_io.PromptWithValidator( validator=lambda x: len(x) > 1, error_message='Error: Invalid username, please try again.', prompt_string=user_message) ldap_pass = console_io.PromptPassword( pass_message, validation_callable=lambda x: len(x) > 1) return _Base64EncodeLdap(ldap_user, ldap_pass)
def RunBaseSetPasswordCommand(args, release_track): """Changes a user's password in a given instance. Args: args: argparse.Namespace, The arguments that this command was invoked with. release_track: base.ReleaseTrack, the release track that this was run under. Returns: SQL user resource iterator. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client if args.prompt_for_password: args.password = console_io.PromptPassword('New Password: '******'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') dual_password_type = None if release_track == base.ReleaseTrack.ALPHA: dual_password_type = users.ParseDualPasswordType(sql_messages, args) request = users_util.CreateSetPasswordRequest(sql_messages, args, dual_password_type, instance_ref.project) result_operation = sql_client.users.Update(request) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result_operation.name, project=instance_ref.project) if args.async_: return sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) operations.OperationsV1Beta4.WaitForOperation(sql_client, operation_ref, 'Updating Cloud SQL user')
def testPromptPasswordWithValidationAndEncoding(self): self.mock_getpass.side_effect = self._GetFakeGetPass( 'PasswordPrompt:', 'good') self.SetAnswers('bad', 'good') mock_iter = iter((False, True)) def fake_validator(s): del s return next(mock_iter) def fake_encoder(s): return 'ENCODED[{}]'.format(s) # fake_validator = Mock() result = console_io.PromptPassword('PasswordPromptWValidation:', error_message='InvalidPassword', encoder_callable=fake_encoder, validation_callable=fake_validator) self.assertIn('InvalidPassword', self.GetErr()) self.assertEqual(result, 'ENCODED[good]')
def ConstructCreateInstanceFromArgs(cls, sql_messages, args, original=None, instance_ref=None, release_track=DEFAULT_RELEASE_TRACK): """Constructs Instance for create request from base instance and args.""" ShowZoneDeprecationWarnings(args) instance_resource = cls._ConstructBaseInstanceFromArgs( sql_messages, args, original, instance_ref) instance_resource.region = reducers.Region(args.region, _GetZone(args), _GetSecondaryZone(args)) instance_resource.databaseVersion = _ParseDatabaseVersion( sql_messages, args.database_version) instance_resource.masterInstanceName = args.master_instance_name instance_resource.rootPassword = args.root_password # BETA: Set the host port and return early if external master instance. if _IsBetaOrNewer(release_track) and args.IsSpecified( 'source_ip_address'): on_premises_configuration = reducers.OnPremisesConfiguration( sql_messages, args.source_ip_address, args.source_port) instance_resource.onPremisesConfiguration = on_premises_configuration return instance_resource instance_resource.settings = cls._ConstructCreateSettingsFromArgs( sql_messages, args, original, release_track) if args.master_instance_name: replication = sql_messages.Settings.ReplicationTypeValueValuesEnum.ASYNCHRONOUS if args.replica_type == 'FAILOVER': instance_resource.replicaConfiguration = ( sql_messages.ReplicaConfiguration( kind='sql#demoteMasterMysqlReplicaConfiguration', failoverTarget=True)) else: replication = sql_messages.Settings.ReplicationTypeValueValuesEnum.SYNCHRONOUS if not args.replication: instance_resource.settings.replicationType = replication if args.failover_replica_name: instance_resource.failoverReplica = ( sql_messages.DatabaseInstance.FailoverReplicaValue( name=args.failover_replica_name)) if args.collation: instance_resource.settings.collation = args.collation # BETA: Config for creating a replica of an external master instance. if _IsBetaOrNewer(release_track) and args.IsSpecified( 'master_username'): # Ensure that the master instance name is specified. if not args.IsSpecified('master_instance_name'): raise exceptions.RequiredArgumentException( '--master-instance-name', 'To create a read replica of an external ' 'master instance, [--master-instance-name] must be specified' ) # TODO(b/78648703): Remove when mutex required status is fixed. # Ensure that the master replication user password is specified. if not (args.IsSpecified('master_password') or args.IsSpecified('prompt_for_master_password')): raise exceptions.RequiredArgumentException( '--master-password', 'To create a read replica of an external ' 'master instance, [--master-password] or ' '[--prompt-for-master-password] must be specified') # Get password if not specified on command line. if args.prompt_for_master_password: args.master_password = console_io.PromptPassword( 'Master Instance Password: '******'sql#diskEncryptionConfiguration', kmsKeyName=key_name) instance_resource.diskEncryptionConfiguration = config return instance_resource
def GetHandshakeSecret(): """Prompt for user input of handshake secret with target domain.""" unused_cred = console_io.PromptPassword( "Please enter handshake secret with target domain. The secret will not be stored: " ) return unused_cred
def GetPfxPasssword(): """Prompt for user input of pfx password.""" cred = console_io.PromptPassword( 'Please enter the password used the encrypt the pfx certificate: ') return cred
def testPromptNoPrompt(self): properties.VALUES.core.disable_prompts.Set(True) self.assertIsNone(console_io.PromptPassword('PasswordPrompt:'))