def main(): args = parse_args() endpoint = '{}://{}:{}/{}'.format( 'http' if args.use_http else 'https', args.host, args.port, args.endpoint ) username = args.user if '\\' not in username or '@' not in username: username = '******'.format(args.host.split('.')[0], username) if args.shell: command = args.command[0] arguments = args.command[1:] else: command = 'powershell' encoded_command = ' '.join(args.command) encoded_command = base64.b64encode(encoded_command.encode('utf-16-le')) arguments = ['-EncodedCommand', encoded_command] proto = Protocol(endpoint, 'ntlm', username, args.password, server_cert_validation='ignore') shell_id = proto.open_shell() command_id = proto.run_command(shell_id, command, arguments) std_out, std_err, status_code = proto.get_command_output(shell_id, command_id) sys.stdout.write(std_out.decode('utf-8')) # sys.stderr.write(std_err.decode('utf-8')) proto.cleanup_command(shell_id, command_id) proto.close_shell(shell_id) return status_code
def run(self, scripturl, scriptarguments): scriptpath = "c:\\samanamon" #scripturl="http://%s/%s" % (self.nagiosaddress, scriptname) scriptname = scripturl.split('/')[-1] if self.cleanup: script = ''' if (-Not (Test-Path %(scriptpath)s)) { mkdir %(scriptpath)s | Out-Null} "Environment prepared." | Out-Host Invoke-WebRequest -Uri %(scripturl)s -OutFile "%(scriptpath)s\\%(scriptname)s" if (-Not (Test-Path %(scriptpath)s\\%(scriptname)s)) { "File not downloaded" | Out-Host; Remove-Item -Recurse -Force %(scriptpath)s exit 1 } "Downloaded Script." | Out-Host %(scriptpath)s\\%(scriptname)s %(scriptarguments)s| Out-Host "Done executing script" | Out-Host del %(scriptpath)s\\%(scriptname)s Remove-Item -Recurse -Force %(scriptpath)s "Done cleanup" | Out-Host''' % { 'scripturl': scripturl, 'scriptpath': scriptpath, 'scriptname': scriptname, 'scriptarguments': scriptarguments, 'hostaddress': self.hostaddress } else: script = ''' %(scriptpath)s\\%(scriptname)s %(scriptarguments)s| Out-Host "Done executing script" | Out-Host''' % { 'scriptpath': scriptpath, 'scriptname': scriptname, 'scriptarguments': scriptarguments } shell_id = None command_id = None p = None error = 0 std_out = '' std_err = '' try: p = Protocol( endpoint='http://%s:5985/wsman' % self.hostaddress, transport='ntlm', username=self.username, password=self.password) shell_id = p.open_shell() encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii') command_id = p.run_command(shell_id, 'powershell', ['-encodedcommand {0}'.format(encoded_ps), ]) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) self.check_error(std_err) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) except Exception as e: raise CheckWinRMExceptionUNKNOWN("Unable to get data from Server (%s) %s." % (type(e).__name__, str(e))) if status_code != 0: raise CheckWinRMExceptionUNKNOWN(std_err) return "%s\n%s" % (std_out, "")
def getLastTaskResult(self, taskname): script = """ $task = Get-ScheduledTaskInfo -TaskName %s $task.LastTaskResult """ % taskname shell_id = None command_id = None p = None error = False try: p = Protocol(endpoint='https://' + self.hostname + ':5986/wsman', transport='ntlm', username=self.username, password=self.password, server_cert_validation='ignore') shell_id = p.open_shell() encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii') command_id = p.run_command(shell_id, 'powershell', [ '-encodedcommand {0}'.format(encoded_ps), ]) std_out, std_err, status_code = p.get_command_output( shell_id, command_id) lasttaskresult = std_out.rstrip() except Exception as e: print("UNKNOWN - Unable to get data from server (%s) %s." % (str(e), type(e).__name__)) error = True finally: p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) if error: exit(3) return lasttaskresult
def _winrm_connect(self): ''' Establish a WinRM connection over HTTP/HTTPS. ''' display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % (self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host) netloc = '%s:%d' % (self._winrm_host, self._winrm_port) endpoint = urlunsplit((self._winrm_scheme, netloc, self._winrm_path, '', '')) errors = [] for transport in self._winrm_transport: if transport == 'kerberos' and not HAVE_KERBEROS: errors.append('kerberos: the python kerberos library is not installed') continue display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._winrm_host) try: protocol = Protocol(endpoint, transport=transport, **self._winrm_kwargs) protocol.send_message('') return protocol except Exception as e: err_msg = (str(e) or repr(e)).strip() if re.search(r'Operation\s+?timed\s+?out', err_msg, re.I): raise AnsibleError('the connection attempt timed out') m = re.search(r'Code\s+?(\d{3})', err_msg) if m: code = int(m.groups()[0]) if code == 401: err_msg = 'the username/password specified for this server was incorrect' elif code == 411: return protocol errors.append('%s: %s' % (transport, err_msg)) display.vvvvv('WINRM CONNECTION ERROR: %s\n%s' % (err_msg, traceback.format_exc()), host=self._winrm_host) if errors: raise AnsibleError(', '.join(errors)) else: raise AnsibleError('No transport found for WinRM connection')
def run_command(command, target): p = Protocol(endpoint='https://' + target + ':5986/wsman', transport='kerberos') # We do not want printed info about kerberos ticket stdout_orig = sys.stdout f = open('/dev/null', 'w') sys.stdout = f try: shell_id = p.open_shell() command_id = p.run_command(shell_id, 'powershell', [command]) std_out, std_err, status_code = p.get_command_output( shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) sys.stdout = stdout_orig print std_out if std_err: sys.exit(std_err) except kerberos.GSSError as e: print >> sys.stderr, "kerberos GSSError:", e sys.exit(2) except: print >> sys.stderr, ( "Unexpected error during remote ps command execution :", sys.exc_info()[0], sys.exc_info()[1]) sys.exit(2)
def run(self): # use win remote management to run powershell script # set command text, tell windows which module to import and run in this case script = "Import-Module -Name 'C:\\Users\\trota\\Source\\PowerShell\\Modules\\yo.psm1'; &WriteYo(' with var')" # must use utf16 little endian on windows # see run_ps in pywinrm __init__.py https://github.com/diyan/pywinrm/blob/master/winrm/__init__.py encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii') encoded_ps_command = 'powershell -encodedcommand {0}'.format( encoded_ps) print("") print("encoded ps command: ", encoded_ps_command) print("") # connect p = Protocol( endpoint='https://CCWL-2909.chsamerica.com:5986/wsman', transport='ntlm', username=r'chs\trota', password='******', # secure connection validation - see http://www.hurryupandwait.io/blog/understanding-and-troubleshooting-winrm-connection-and-authentication-a-thrill-seekers-guide-to-adventure # TODO: configure SSL properly for production/public spaces server_cert_validation='ignore' #server_cert_validation='validate' ) shell_id = p.open_shell() command_id = p.run_command(shell_id, encoded_ps_command) std_out, std_err, status_code = p.get_command_output( shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id)
def connect(self, host, username, password): client = Protocol(endpoint="http://{0}:5985/wsman".format(host), transport="ntlm", username=username, password=password, read_timeout_sec=30) return client
def run(self, host, password, command, params, username='******', port=5732, secure=True): proto = 'https' if secure else 'http' p = Protocol( endpoint='%s://%s:%i/wsman' % (proto, host, port), # RFC 2732? transport='ntlm', username=username, password=password, server_cert_validation='ignore') shell_id = p.open_shell() # run the command command_id = p.run_command(shell_id, command, params) std_out, std_err, status_code = p.get_command_output( shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) return {'stdout': std_out, 'stderr': std_err}
def get_pywinrm_session(ip, port, username, password): '''Get an insecure pywinrm session. :params ip, username, password: Windows host's WinRM details. :param port: the port where the WinRM service is listening in host. ''' transport_protocols = { 'http': ('plaintext', 'http'), 'https': ('ssl', 'https') } transport, protocol = transport_protocols['http' if port == 5985 else 'https'] session = winrm.Session("%(protocol)s://%(ip)s:%(port)s/wsman" % { "ip": ip, "port": port, "protocol": protocol }, auth=(username, password), transport=transport) session.protocol = Protocol(session.url, transport=transport, username=username, password=password, server_cert_validation='ignore') return session
def __init__(self, target, auth, transport='plaintext'): username, password = auth self.url = self._build_url(target, transport) self.protocol = Protocol(self.url, transport=transport, username=username, password=password)
def __init__(self, target, auth, **kwargs): username, password = auth self.url = self._build_url(target, kwargs.get('transport', 'plaintext')) self.protocol = Protocol(self.url, username=username, password=password, **kwargs)
def connect(self,host,username,password): client = Protocol(endpoint="http://{0}:5985/wsman".format(host),transport="ntlm",username=username,password=password,read_timeout_sec=30) try: smbclient.register_session(self.host, username=self.username, password=self.password, connection_timeout=30) except Exception as e: self.error = str(e) return None return client
def build_connection(host, username='', password='', transport='ntlm', useSSL=False): if (useSSL): p = Protocol(endpoint='https://' + host + ':5986/wsman', username=username, password=password, transport=transport, server_cert_validation='ignore') else: p = Protocol(endpoint='http://' + host + ':5985/wsman', username=username, password=password, transport=transport) return p
def test_set_timeout_as_sec(): protocol = Protocol('endpoint', username='******', password='******', read_timeout_sec='30', operation_timeout_sec='29') assert protocol.read_timeout_sec == 30 assert protocol.operation_timeout_sec == 29
def _winrm_connect(self): ''' Establish a WinRM connection over HTTP/HTTPS. ''' display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % (self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host) winrm_host = self._winrm_host if HAS_IPADDRESS: display.debug("checking if winrm_host %s is an IPv6 address" % winrm_host) try: ipaddress.IPv6Address(winrm_host) except ipaddress.AddressValueError: pass else: winrm_host = "[%s]" % winrm_host netloc = '%s:%d' % (winrm_host, self._winrm_port) endpoint = urlunsplit((self._winrm_scheme, netloc, self._winrm_path, '', '')) errors = [] for transport in self._winrm_transport: if transport == 'kerberos': if not HAVE_KERBEROS: errors.append('kerberos: the python kerberos library is not installed') continue if self._kerb_managed: self._kerb_auth(self._winrm_user, self._winrm_pass) display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._winrm_host) try: winrm_kwargs = self._winrm_kwargs.copy() if self._winrm_connection_timeout: winrm_kwargs['operation_timeout_sec'] = self._winrm_connection_timeout winrm_kwargs['read_timeout_sec'] = self._winrm_connection_timeout + 1 protocol = Protocol(endpoint, transport=transport, **winrm_kwargs) # open the shell from connect so we know we're able to talk to the server if not self.shell_id: self.shell_id = protocol.open_shell(codepage=65001) # UTF-8 display.vvvvv('WINRM OPEN SHELL: %s' % self.shell_id, host=self._winrm_host) return protocol except Exception as e: err_msg = to_text(e).strip() if re.search(to_text(r'Operation\s+?timed\s+?out'), err_msg, re.I): raise AnsibleError('the connection attempt timed out') m = re.search(to_text(r'Code\s+?(\d{3})'), err_msg) if m: code = int(m.groups()[0]) if code == 401: err_msg = 'the specified credentials were rejected by the server' elif code == 411: return protocol errors.append(u'%s: %s' % (transport, err_msg)) display.vvvvv(u'WINRM CONNECTION ERROR: %s\n%s' % (err_msg, to_text(traceback.format_exc())), host=self._winrm_host) if errors: raise AnsibleConnectionFailure(', '.join(map(to_native, errors))) else: raise AnsibleError('No transport found for WinRM connection')
def test_fail_set_operation_timeout_as_sec(): with pytest.raises(ValueError) as exc: Protocol('endpoint', username='******', password='******', read_timeout_sec=30, operation_timeout_sec='29a') assert str(exc.value) == "failed to parse operation_timeout_sec as int: " \ "invalid literal for int() with base 10: '29a'"
def get_proto(self): self.debug('Creating winrm connection:' + str(self.hostname) + ":" + str(self.port) + ", Username:" + str(self.username) + ', Password:' + str(self.password)) winproto = Protocol(endpoint=self.url, transport=self.transport, username=self.username, password=self.password) # winproto.transport.timeout = self.default_command_timeout return winproto
def _winrm_connect(self): ''' Establish a WinRM connection over HTTP/HTTPS. ''' port = self._connection_info.port or 5986 self._display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % \ (self._connection_info.remote_user, port, self._connection_info.remote_addr), host=self._connection_info.remote_addr) netloc = '%s:%d' % (self._connection_info.remote_addr, port) exc = None for transport, scheme in self.transport_schemes['http' if port == 5985 else 'https']: if transport == 'kerberos' and ( not HAVE_KERBEROS or not '@' in self._connection_info.remote_user): continue if transport == 'kerberos': realm = self._connection_info.remote_user.split( '@', 1)[1].strip() or None else: realm = None endpoint = parse.urlunsplit((scheme, netloc, '/wsman', '', '')) self._display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._connection_info.remote_addr) protocol = Protocol(endpoint, transport=transport, username=self._connection_info.remote_user, password=self._connection_info.password, realm=realm) try: protocol.send_message('') return protocol except WinRMTransportError as exc: err_msg = str(exc) if re.search(r'Operation\s+?timed\s+?out', err_msg, re.I): raise AnsibleError("the connection attempt timed out") m = re.search(r'Code\s+?(\d{3})', err_msg) if m: code = int(m.groups()[0]) if code == 401: raise AnsibleError( "the username/password specified for this server was incorrect" ) elif code == 411: return protocol self._display.vvvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self._connection_info.remote_addr) continue if exc: raise AnsibleError(str(exc))
def connect(self): inventory = Inventory() if inventory.has_option(self.hostname, 'address'): address = inventory.get(self.hostname, 'address') else: address = self.hostname logger.debug('Using address ' + address) if inventory.has_option(self.hostname, 'scheme'): scheme = inventory.get(self.hostname, 'scheme') else: scheme = 'http' logger.debug('Using url scheme ' + scheme) if inventory.has_option(self.hostname, 'port'): port = inventory.get(self.hostname, 'port') else: if scheme == 'http': port = '5985' elif scheme == 'https': port = '5986' else: raise('Invalid WinRM scheme: ' + scheme) logger.debug('Using port ' + port) if not inventory.has_option(self.hostname, 'username'): raise RuntimeError('Host ' + self.hostname + ' has not specified option: username') username = inventory.get(self.hostname, 'username') if inventory.has_option(self.hostname, 'kerberos_realm'): username = username + '@' + inventory.get(self.hostname, 'kerberos_realm') logger.debug('Using username ' + username) if inventory.has_option(self.hostname, 'kerberos_delegation'): kerberos_delegation = inventory.get(self.hostname, 'kerberos_delegation') else: kerberos_delegation = False if inventory.has_option(self.hostname, 'kerberos_hostname_override'): kerberos_hostname_override = inventory.get(self.hostname, 'kerberos_hostname_override') else: kerberos_hostname_override = None self.protocol = Protocol( endpoint=scheme + '://' + address + ':' + port + '/wsman', transport='kerberos', username=username, kerberos_delegation=kerberos_delegation, kerberos_hostname_override=kerberos_hostname_override) try: self.shell_id = self.protocol.open_shell() except Exception as e: logger.warning(str(e))
def _winrm_connect(self): ''' Establish a WinRM connection over HTTP/HTTPS. ''' display.vvv( "ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % (self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host) netloc = '%s:%d' % (self._winrm_host, self._winrm_port) endpoint = urlunsplit( (self._winrm_scheme, netloc, self._winrm_path, '', '')) errors = [] for transport in self._winrm_transport: if transport == 'kerberos' and not HAVE_KERBEROS: errors.append( 'kerberos: the python kerberos library is not installed') continue display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._winrm_host) try: protocol = Protocol(endpoint, transport=transport, **self._winrm_kwargs) # send keepalive message to ensure we're awake # TODO: is this necessary? # protocol.send_message(xmltodict.unparse(rq)) if not self.shell_id: self.shell_id = protocol.open_shell( codepage=65001) # UTF-8 display.vvvvv('WINRM OPEN SHELL: %s' % self.shell_id, host=self._winrm_host) return protocol except Exception as e: err_msg = to_unicode(e).strip() if re.search(to_unicode(r'Operation\s+?timed\s+?out'), err_msg, re.I): raise AnsibleError('the connection attempt timed out') m = re.search(to_unicode(r'Code\s+?(\d{3})'), err_msg) if m: code = int(m.groups()[0]) if code == 401: err_msg = 'the username/password specified for this server was incorrect' elif code == 411: return protocol errors.append(u'%s: %s' % (transport, err_msg)) display.vvvvv(u'WINRM CONNECTION ERROR: %s\n%s' % (err_msg, to_unicode(traceback.format_exc())), host=self._winrm_host) if errors: raise AnsibleConnectionFailure(', '.join(map(to_str, errors))) else: raise AnsibleError('No transport found for WinRM connection')
def connect(self, output, server): self.output = output self.datastore = os.path.join(self.output, server['server']) os.makedirs(self.datastore) # session = winrm.Session(server['url'], # auth=(server['user'], server['password']), # transport='ntlm') self.protocol = Protocol(endpoint='http://{}:5985/wsman'.format( server['url']), transport='ntlm', username=server['user'], password=server['password'])
def run_powershell_with_codepage_936(target, username, password, script): """ run remote command with WinRM [Chinese characters are not displayed properly #288](https://github.com/diyan/pywinrm/issues/288) [Code Page Identifiers](https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers) codepage use 936, gb2312, ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) :param target: hostname or ip address :type target: str :param username: :type username: str :param password: :type password: str :param script: powershell commands or scripts :type script: str | unicode :return: status_code, std_out :rtype: tuple """ script = to_unicode_or_bust(script) encoded_ps = b64encode(script.encode('utf_16_le')).decode("ascii") p = Protocol( endpoint='http://{}:5985/wsman'.format(target), transport='ntlm', username=username, password=password, read_timeout_sec=10, operation_timeout_sec=5, ) try: shell_id = p.open_shell(codepage=936) except requests.exceptions.ConnectionError as e: return 1, "requests failed.", str(e) try: command_id = p.run_command(shell_id, 'powershell.exe', ['-EncodedCommand', encoded_ps]) try: std_out, std_err, status_code = p.get_command_output( shell_id, command_id) finally: p.cleanup_command(shell_id, command_id) finally: p.close_shell(shell_id) # print(std_out.decode('utf-8')) # print(std_err.decode('utf-8')) # print(status_code) return status_code, std_out, std_err
def protocol_real(): config_path = os.path.join(os.path.dirname(__file__), 'config.json') if os.path.isfile(config_path): # TODO consider replace json with yaml for integration test settings # TODO json does not support comments settings = json.load(open(config_path)) from winrm.protocol import Protocol protocol = Protocol(**settings) return protocol else: skip('config.json was not found. Integration tests will be skipped')
def auto_ss(): from winrm.protocol import Protocol p = Protocol(endpoint='http://172.30.200.149:5985/wsman', transport='basic', username=r'chry', password='******', server_cert_validation='ignore') shell_id = p.open_shell() command_id = p.run_command(shell_id, 'ipconfig', ['/all']) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id)
def init_winrm_connection(self, host, port, username, password): endpoint = 'https://%s:%s/wsman' % (host, port) try: self.winrm = Protocol(endpoint=endpoint, transport='ntlm', username=username, password=password, server_cert_validation='ignore') return True except Exception as ex: print "\t=> WinRM : Authentication failed on server: %s cause: %s" % ( host, str(ex)) return False
def main(computer, username, password, command): p = Protocol(endpoint='https://{}:5986/wsman'.format(computer), transport='ntlm', username=username, password=password, server_cert_validation='ignore') shell_id = p.open_shell() #command_id = p.run_command(shell_id, 'query', ['user']) command_id = p.run_command(shell_id, command, []) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id)
def _try_winrm(self, node): ip = node.private_ips[0] p = Protocol( endpoint='http://%s:5985/wsman' % ip, # RFC 2732 transport='ntlm', username=self.username, password=self.secret, server_cert_validation='ignore') shell_id = p.open_shell() command_id = p.run_command(shell_id, 'ipconfig', ['/all']) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) return std_out
def winrm_cmd(cmd): p = Protocol(endpoint='https://192.168.183.186:5986/wsman', transport='basic', username=r'Administrator', password='******', server_cert_validation='ignore') shell_id = p.open_shell() command_id = p.run_command(shell_id, cmd) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) return std_out
def run_vncApplyAttribute_winrm_command(attribute_name, attribute_value, idrac_ip, idrac_userName, idrac_password, windows_ip, windows_username, windows_password): """ This function is used for getting output of enumeration class as speciified Function Owner : Nithya_V Date created : 6/9/2016 @param attribute_name : VNC attribute name which needs to be changed @param attribute_value : VNC attribute value which needs to be applied @param idrac_ip : (string) idrac ip of system @param idrac_userName : (string) idrac user name @param idrac_password : (string) idrac password @param windows_ip : (string) windows system ip from which query will be executed @param windows_userName : (string) windows system user name @param windows_password : (string) windows system password @param instance_id : (string) instance id for fetching data specific to an instance. Optional @return command_output : (string) Command Output, None in case of any error @return no_of_instances : (string) number of instances returned """ try: 'establish connection with windows system' p = Protocol(endpoint='http://' + windows_ip + ':5985/wsman', transport='plaintext', username=windows_username, password=windows_password) shell_id = p.open_shell() 'execute winrm command on idrac ip' winrm_command = global_vars.winrm_apply_vnc_attributes_command + ' -u:' + idrac_userName + ' -p:' + idrac_password + \ ' -r:https://' + idrac_ip + '/wsman -SkipCNcheck -SkipCAcheck -encoding:utf-8 -a:basic @{Target="iDRAC.Embedded.1";AttributeName=%s;AttributeValue=%s}' % (attribute_name, attribute_value) print "Winrm Command %s \n" % (winrm_command) command_id = p.run_command(shell_id, 'ls') 'get command output' command_output, command_error, command_status = p.get_command_output( shell_id, command_id) print 'Command Output:' + str(command_output) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) return command_output, 0 except: traceback.print_exc() return None, '0'
def _winrm_connect(self): ''' Establish a WinRM connection over HTTP/HTTPS. ''' port = self.port or 5986 vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" % \ (self.user, port, self.host), host=self.host) netloc = '%s:%d' % (self.host, port) cache_key = '%s:%s@%s:%d' % (self.user, hashlib.md5( self.password).hexdigest(), self.host, port) if cache_key in _winrm_cache: vvvv('WINRM REUSE EXISTING CONNECTION: %s' % cache_key, host=self.host) return _winrm_cache[cache_key] transport_schemes = [('plaintext', 'https'), ('plaintext', 'http')] # FIXME: ssl/kerberos if port == 5985: transport_schemes = reversed(transport_schemes) exc = None for transport, scheme in transport_schemes: endpoint = urlparse.urlunsplit((scheme, netloc, '/wsman', '', '')) vvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self.host) protocol = Protocol(endpoint, transport=transport, username=self.user, password=self.password) try: protocol.send_message('') _winrm_cache[cache_key] = protocol return protocol except WinRMTransportError, exc: err_msg = str(exc.args[0]) if re.search(r'Operation\s+?timed\s+?out', err_msg, re.I): raise errors.AnsibleError( "the connection attempt timed out") m = re.search(r'Code\s+?(\d{3})', err_msg) if m: code = int(m.groups()[0]) if code == 401: raise errors.AnsibleError( "the username/password specified for this server was incorrect" ) elif code == 411: _winrm_cache[cache_key] = protocol return protocol vvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self.host) continue