本文整理汇总了Python中winrm.protocol.Protocol类的典型用法代码示例。如果您正苦于以下问题:Python Protocol类的具体用法?Python Protocol怎么用?Python Protocol使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Protocol类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _winrm_connect
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')
示例2: _winrm_connect
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.vvvv("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')
示例3: _winrm_connect
def _winrm_connect(self):
'''
Establish a WinRM connection over HTTP/HTTPS.
'''
# get winrm-specific connection vars
host_vars = self.runner.inventory._hosts_cache[self.delegate].get_variables()
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)
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.user):
continue
if transport == 'kerberos':
realm = self.user.split('@', 1)[1].strip() or None
else:
realm = None
endpoint = urlparse.urlunsplit((scheme, netloc, '/wsman', '', ''))
self._winrm_kwargs = dict(username=self.user, password=self.password, realm=realm)
argspec = inspect.getargspec(Protocol.__init__)
for arg in argspec.args:
if arg in ('self', 'endpoint', 'transport', 'username', 'password', 'realm'):
continue
if 'ansible_winrm_%s' % arg in host_vars:
self._winrm_kwargs[arg] = host_vars['ansible_winrm_%s' % arg]
vvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint),
host=self.host)
protocol = Protocol(endpoint, transport=transport, **self._winrm_kwargs)
try:
protocol.send_message('')
return protocol
except WinRMTransportError, exc:
err_msg = str(exc)
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:
return protocol
vvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self.host)
continue
示例4: __init__
def __init__(self, target, auth, transport='plaintext',
timeout=None):
username, password = auth
self.url = self._build_url(target, transport)
self.protocol = Protocol(self.url, transport=transport,
username=username, password=password,
timeout=timeout)
示例5: _winrm_connect
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))
示例6: Session
class Session(object):
#TODO implement context manager methods
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 run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
@staticmethod
def _build_url(target, transport):
match = re.match(
'(?i)^((?P<scheme>http[s]?)://)?(?P<host>[0-9a-z-_]+)(:(?P<port>\d+))?(?P<path>(/)?(wsman)?)?', target)
scheme = match.group('scheme')
if not scheme:
scheme = 'https' if transport == 'ssl' else 'http' # TODO do we have anything other than HTTP/HTTPS
host = match.group('host')
port = match.group('port')
if not port:
port = 5986 if transport == 'ssl' else 5985
path = match.group('path')
if not path:
path = 'wsman'
return '{0}://{1}:{2}/{3}'.format(scheme, host, port, path.lstrip('/'))
示例7: _winrm_connect
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')
示例8: _winrm_connect
def _winrm_connect(self):
'''
Establish a WinRM connection over HTTP/HTTPS.
'''
if _winrm_hacks:
port = _winrm_hacks.get_port(self)
else:
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:%[email protected]%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
m = re.search(r'Code\s+?(\d{3})', err_msg)
if m:
code = int(m.groups()[0])
if code == 411:
_winrm_cache[cache_key] = protocol
return protocol
vvvv('WINRM CONNECTION ERROR: %s' % err_msg, host=self.host)
continue
示例9: protocol_fake
def protocol_fake(request):
uuid4_patcher = patch('uuid.uuid4')
uuid4_mock = uuid4_patcher.start()
uuid4_mock.return_value = uuid.UUID(
'11111111-1111-1111-1111-111111111111')
from winrm.protocol import Protocol
protocol_fake = Protocol(
endpoint='http://windows-host:5985/wsman',
transport='plaintext',
username='john.smith',
password='secret')
protocol_fake.transport = TransportStub()
def uuid4_patch_stop():
uuid4_patcher.stop()
request.addfinalizer(uuid4_patch_stop)
return protocol_fake
示例10: _try_winrm
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
示例11: run
def run(self, host, password, username='Administrator',
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()
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 {'stdout': std_out, 'stderr': std_err}
示例12: Session
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth, transport = "plaintext"):
#TODO convert short urls into well-formed endpoint
self.protocol = Protocol(url, auth, transport)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
示例13: _winrm_commands
def _winrm_commands(self, node, commands):
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()
std_out_logs = []
std_err_logs = []
# run the commands in sequence.
for command, params in commands:
command_id = p.run_command(shell_id, command, params)
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
std_out_logs.append(std_out)
std_err_logs.append(std_err)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
return std_out_logs, std_err_logs
示例14: connect
def connect(self, username=None, password=None):
"""
Attempts to connect to a remote server via WinRM.
@param username: Username to be used for the WinRM connection
@type username: string
@param password: Password to be used for the WinRM connection
@type password: string
"""
endpoint = "http://{host}:5985/wsman".format(host=self.host)
try:
self.connection = Protocol(endpoint=endpoint, username=username, password=password)
# Doing a wide catch as the exception handling in WinRM is not
# very thorough or specific
except Exception as exception:
self._log(exception.message)
else:
self.shell_id = self.connection.open_shell()
示例15: BaseWinRMClient
class BaseWinRMClient(BaseClient):
def __init__(self, host=None):
"""
Initialization
@param host: IP address or host name to connect to
@type host: string
"""
self.host = host
self.connection = None
self.shell_id = None
def connect(self, username=None, password=None):
"""
Attempts to connect to a remote server via WinRM.
@param username: Username to be used for the WinRM connection
@type username: string
@param password: Password to be used for the WinRM connection
@type password: string
"""
endpoint = "http://{host}:5985/wsman".format(host=self.host)
try:
self.connection = Protocol(endpoint=endpoint, username=username, password=password)
# Doing a wide catch as the exception handling in WinRM is not
# very thorough or specific
except Exception as exception:
self._log(exception.message)
else:
self.shell_id = self.connection.open_shell()
def is_connected(self):
"""
Checks to see if a WinRM connection exists.
@rtype: bool
"""
return self.connection is not None and self.shell_id is not None
def _format_response(self, std_out=None, std_err=None, status_code=None):
"""
Converts the executed command responses into an object.
@param std_out: The stdout result
@type std_out: string
@param std_err: The stderr result
@type std_err: string
@param status_code: The status code of the executed command
@type status_code: int
@rtype: WinRMResponse
"""
response = WinRMResponse(std_out=std_out, std_err=std_err, status_code=status_code)
return response
def execute_command(self, command=None, args=None):
"""
Executes a command via remote shell.
@param command: The command to execute
@type command: string
@param args: A list of arguments to pass to the command
@type args: list of strings
@return: Result of command execution
@rtype: WinRMResponse
"""
if not self.is_connected():
message = "Not currently connected to {host}.".format(host=self.host)
self._log.error(message)
raise Exception(message)
if args is None:
args = []
self._log.debug("Executing command: {command} {args}".format(command=command, args=" ".join(args)))
command_id = self.connection.run_command(self.shell_id, command, args)
std_out, std_err, status_code = self.connection.get_command_output(self.shell_id, command_id)
response = self._format_response(std_out=std_out, std_err=std_err, status_code=status_code)
self._log.debug("Stdout: {std_out}".format(std_out=response.std_out))
self._log.debug("Stderr: {std_err}".format(std_err=response.std_err))
self._log.debug("Status code: {status_code}".format(status_code=response.status_code))
return response