class ReauthenticatingKerberosSession: """ Wrapper around WinRM Session object that automatically tries to generate a new Kerberos token and session if authentication fails """ def _generate_kerberos_ticket(self): """ Tries to generate a new Kerberos ticket, through a call to kinit Raises an exception if the subprocess has non-zero exit code """ cmd = ["kinit", self._username] try: subprocess.run( cmd, check=True, input=self._password.encode(), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, ) except subprocess.CalledProcessError as e: print(e.stderr.decode("utf-8")) raise def _create_new_session(self): """ Generate new internal session XXX: Session is not properly cleaned up when a command fails so we have to create a new internal session object each time """ self._session = Session(target=self._target, transport="kerberos", auth=(None, None)) def __init__(self, target: str, username: str, password: str): self._username = username self._password = password self._target = target self._create_new_session() def run_cmd(self, *args, **kwargs): try: rs = self._session.run_cmd(*args, **kwargs) except KerberosExchangeError: self._generate_kerberos_ticket() self._create_new_session() rs = self._session.run_cmd(*args, **kwargs) return rs def run_ps(self, *args, **kwargs): try: rs = self._session.run_ps(*args, **kwargs) except KerberosExchangeError: self._generate_kerberos_ticket() self._create_new_session() rs = self._session.run_ps(*args, **kwargs) return rs
def test_run_ps(protocol_fake): s = Session('windows-host', auth=('john.smith', 'secret')) r = s.run_ps('hostname') assert r.status_code == 0 assert 'Windows IP Configuration' in r.std_out assert len(r.std_err) == 0
def __runPowerShellScript(self, scriptfile="FileCopy.ps1", isFile=True): """ run the content of a powershell script given in scriptfile if isFile=True, scriptFile must contain path to Powershell script, if isFile==False, scriptFile is treaded as scripting string prints std_out, std_err and status returns std_out """ script = "" if isFile == True: with open(scriptfile) as file: script = file.read() else: script = scriptfile s = Session(self.ip, auth=(self.remoteAdminUser, self.passwd)) r = s.run_ps(script) if self.debug: print("std_out:") for line in str(r.std_out).split(r"\r\n"): print(line) if r.status_code != self.STATUS_OK: print("status_code: " + str(r.status_code)) print("error: " + str(r.std_err)) return r.std_out.decode("utf-8").rstrip()
def test_run_ps_with_error(protocol_fake): # TODO this test should cover __init__ method s = Session('windows-host', auth=('john.smith', 'secret')) s.protocol = protocol_fake r = s.run_ps('Write-Error "Error"') assert r.status_code == 1 assert b'Write-Error "Error"' in r.std_err assert len(r.std_out) == 0
def uruchom_ps(polecenie): sesja = Session('https://jumpbox.monad.net:5986', auth=(None, None), transport='kerberos', kerberos_delegation=True, server_cert_validation='ignore') try: wynik = sesja.run_ps(polecenie) print wynik.std_out if wynik.status_code > 0: raise PowerShellError(wynik.std_err) else: print "%sCommand return code 0 %s" % (bcolors.OKGREEN, bcolors.ENDC) except: raise
def run_ps(command): print "Running command: %s" % command sesja = Session('https://jumpbox.monad.net:5986', auth=(None, None), transport='kerberos', kerberos_delegation=True, server_cert_validation='ignore') try: result = sesja.run_ps(command) print result.std_out if result.status_code > 0: raise PowerShellError(result.std_err) else: print "%sCommand returned code 0 %s" % (bcolors.OKGREEN, bcolors.ENDC) except: raise
def test_run_ps(protocol_fake): s = Session('windows-host', auth=('john.smith', 'secret')) s.protocol = protocol_fake script = """ $strComputer = $Host Clear $RAM = WmiObject Win32_ComputerSystem $MB = 1048576 "Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """ r = s.run_ps(script) assert r.status_code == 0 assert b'Installed Memory: 2044 MB' in r.std_out assert len(r.std_err) == 0
#!/usr/bin/env python from winrm import Session from sys import exit, argv if len(argv) < 3 : exit('Usage: %s times command' % argv[0]) times = int(argv[1]) command = " ".join(argv[2:]) * times print "Command length: %d" % len(command) mySession = Session( 'jumpbox.monad.net', auth = (None, None), transport = 'kerberos', ) result = mySession.run_ps(command) print "Output length: %d" % len(result.std_out) if result.status_code > 0: print "Error: %s" % result.std_err