def _AutomaticJoin(self): """Join the domain with automated credentials.""" creds = DomainJoinCredentials() self._username = creds.GetUsername() self._password = creds.GetPassword() logging.info('Starting automated domain join. Hostname: %s', socket.gethostname()) while True: ps = powershell.PowerShell() try: logging.debug('Attempting to join the domain %s.', self._domain_name) ps.RunLocal( r'%s\join-domain.ps1' % constants.SYS_CACHE, args=[self._username, self._password, self._domain_name]) except powershell.PowerShellError as e: logging.error( 'Domain join failed. Sleeping 5 minutes then trying again. (%s)', e) time.sleep(300) continue logging.info('Joined the machine to the domain.') break
def testLaunchPsSilent(self, eb, path): path.return_value = powershell.constants.SYS_POWERSHELL self.pssilent = powershell.PowerShell(log=False) self.pssilent._LaunchPs('-File', [self.path]) eb.assert_called_with(powershell.constants.SYS_POWERSHELL, ['-NoProfile', '-NoLogo', '-File', self.path], None, False, False)
def setUp(self): super(PowershellTest, self).setUp() self.fs = fake_filesystem.FakeFilesystem() powershell.os = fake_filesystem.FakeOsModule(self.fs) powershell.resources.os = fake_filesystem.FakeOsModule(self.fs) self.fs.CreateFile('/resources/bin/script.ps1') self.ps = powershell.PowerShell()
def _AutomaticJoin(self): """Join the domain with automated credentials.""" creds = DomainJoinCredentials() self._username = creds.GetUsername() self._password = creds.GetPassword() logging.info('Starting automated domain join. Hostname: %s', socket.gethostname()) while True: ps = powershell.PowerShell() try: logging.debug('Attempting to join the domain %s.', self._domain_name) ps.RunLocal( r'%s\join-domain.ps1' % constants.SYS_CACHE, args=[self._username, self._password, self._domain_name]) except powershell.PowerShellError as e: # Replace and mask password in error output. c = [] error = str(e).split() for item in error: if self._password in item: c.append('************') else: c.append(item) # Display cleaned output logging.error( 'Domain join failed. Sleeping 5 minutes then trying again. (%s)', c) time.sleep(300) continue logging.info('Joined the machine to the domain.') break
def testStartShellSilent(self, eb, path): path.return_value = powershell.constants.SYS_POWERSHELL self.pssilent = powershell.PowerShell(log=False) self.pssilent.StartShell() eb.assert_called_with(powershell.constants.SYS_POWERSHELL, ['-NoProfile', '-NoLogo'], shell=False, log=False)
def testLaunchPsEcho(self, call, ps, d): ps.return_value = powershell.constants.WINPE_POWERSHELL call.return_value = 0 self.psecho = powershell.PowerShell(echo_off=False) self.psecho._LaunchPs('-File', [''], [0]) d.assert_called_with( 'Running Powershell: %s', 'X:\\Windows\\System32\\Wind' 'owsPowerShell\\v1.0\\powershell.exe -NoProfile ' '-NoLogo -File ')
def _PsTpm(self): """Enable TPM mode using Powershell (Win8 +).""" ps = powershell.PowerShell() try: ps.RunCommand(['$ErrorActionPreference=\'Stop\'', ';', 'Enable-BitLocker', 'C:', '-TpmProtector', '-UsedSpaceOnly', '-SkipHardwareTest ', '>>', r'%s\enable-bitlocker.txt' % constants.SYS_LOGS_PATH]) ps.RunCommand(['$ErrorActionPreference=\'Stop\'', ';', 'Add-BitLockerKeyProtector', 'C:', '-RecoveryPasswordProtector', '>NUL']) except powershell.PowerShellError as e: raise BitlockerError('Error enabling Bitlocker via Powershell: %s.' % str(e))
def Run(self): command: List[str] = self._args[0].split() success_codes: List[int] = [0] reboot_codes: List[int] = [] restart_retry: bool = False shell: bool = False log: bool = True if len(self._args) > 1: success_codes = self._args[1] if len(self._args) > 2: reboot_codes = self._args[2] if len(self._args) > 3: restart_retry = self._args[3] if len(self._args) > 4: shell = self._args[4] if len(self._args) > 5: log = self._args[5] # TODO: Remove once updated PowerShell is used in the image. # PSScript (which calls powershell.exe -File) does not accept non-string # parameters. Instead, if the command string starts with a PowerShell # script, cache it's location and run the script using powershell.exe # -Command. See link below for more context. # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-file----filepath-args if command[0] and command[0].endswith('.ps1'): logging.info('Interpreting PowerShell script: %s', command[0]) try: command[0] = cache.Cache().CacheFromLine( command[0], self._build_info) except cache.CacheError as e: raise ActionError(e) try: # Exit $LASTEXITCODE is necessary because PowerShell.exe -Command only # exits 0 or 1 by default. result = powershell.PowerShell(shell, log).RunCommand( command + ['; exit $LASTEXITCODE'], success_codes + reboot_codes) except powershell.PowerShellError as e: raise ActionError(str(e)) if result in reboot_codes: raise RestartEvent('Restart triggered by exit code %d' % result, 5, retry_on_restart=restart_retry) elif result not in success_codes: raise ActionError('Command returned invalid exit code %d' % result)
def Run(self): script = self._args[0] ps_args = None if len(self._args) > 1: ps_args = self._args[1] ps = powershell.PowerShell(echo_off=True) c = cache.Cache() logging.debug('Interpreting Powershell script %s', script) try: script = c.CacheFromLine(script, self._build_info) except cache.CacheError as e: raise ActionError(e) try: ps.RunLocal(script, args=ps_args) except powershell.PowerShellError as e: raise ActionError('Failure executing Powershell script. [%s]' % e)
def Run(self): script: str = self._args[0] ps_args: List[str] = [] success_codes: List[int] = [0] reboot_codes: List[int] = [] restart_retry: bool = False shell: bool = False log: bool = True if len(self._args) > 1: ps_args = self._args[1] if len(self._args) > 2: success_codes = self._args[2] if len(self._args) > 3: reboot_codes = self._args[3] if len(self._args) > 4: restart_retry = self._args[4] if len(self._args) > 5: shell = self._args[5] if len(self._args) > 6: log = self._args[6] logging.info('Interpreting PowerShell script: %s', script) try: script = cache.Cache().CacheFromLine(script, self._build_info) # pytype: disable=annotation-type-mismatch except cache.CacheError as e: raise ActionError(e) try: result = powershell.PowerShell(shell, log).RunLocal( script, ps_args, success_codes + reboot_codes) except powershell.PowerShellError as e: raise ActionError(str(e)) if result in reboot_codes: raise RestartEvent('Restart triggered by exit code %d' % result, 5, retry_on_restart=restart_retry) elif result not in success_codes: raise ActionError('Script returned invalid exit code %d' % result)
def _InteractiveJoin(self): """Join the domain with user-interactive dialog.""" while True: self._SetUsername() ps = powershell.PowerShell() cmd = [ 'Add-Computer', '-DomainName', self._domain_name, '-Credential', self._username, '-PassThru' ] if self._domain_ou: cmd += ['-OUPath', f'"{self._domain_ou}"'] try: logging.debug('Attempting to join the domain %s.', self._domain_name) ps.RunCommand(cmd) except powershell.PowerShellError as e: logging.error( 'Domain join failed. Sleeping 5 minutes then trying again. (%s)', e) continue logging.info('Joined the machine to the domain.') break