本文整理汇总了Python中winrm.protocol.Protocol类的典型用法代码示例。如果您正苦于以下问题:Python Protocol类的具体用法?Python Protocol怎么用?Python Protocol使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Protocol类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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')
开发者ID:RajeevNambiar,项目名称:temp,代码行数:35,代码来源:winrm.py
示例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')
开发者ID:awiddersheim,项目名称:ansible,代码行数:58,代码来源:winrm.py
示例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
开发者ID:mattbernst,项目名称:polyhartree,代码行数:51,代码来源:winrm.py
示例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)
开发者ID:kschillz,项目名称:pywinrm,代码行数:7,代码来源:__init__.py
示例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))
开发者ID:ferhaty,项目名称:ansible,代码行数:47,代码来源:winrm.py
示例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('/'))
开发者ID:nicodeslandes,项目名称:pywinrm,代码行数:31,代码来源:__init__.py
示例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')
开发者ID:futuresimple,项目名称:ansible-project,代码行数:41,代码来源:winrm.py
示例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
开发者ID:cchurch,项目名称:ansible-winning,代码行数:41,代码来源:winrm.py
示例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
开发者ID:hhsiao,项目名称:pywinrm,代码行数:21,代码来源:conftest.py
示例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
开发者ID:DimensionDataCBUSydney,项目名称:plumbery,代码行数:14,代码来源:windows.py
示例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}
开发者ID:Kremmin,项目名称:st2contrib,代码行数:16,代码来源:try_winrm.py
示例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
开发者ID:ader1990,项目名称:pywinrm,代码行数:14,代码来源:__init__.py
示例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
开发者ID:DimensionDataCBUSydney,项目名称:plumbery,代码行数:22,代码来源:windows.py
示例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()
开发者ID:izrik,项目名称:opencafe,代码行数:20,代码来源:client.py
示例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
开发者ID:izrik,项目名称:opencafe,代码行数:85,代码来源:client.py
示例16: Session
class Session(object):
# TODO implement context manager methods
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)
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
def run_ps(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
# must use utf16 little endian on windows
encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
if len(rs.std_err):
# if there was an error message, clean it it up and make it human
# readable
rs.std_err = self._clean_error_msg(rs.std_err)
return rs
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if msg.startswith("#< CLIXML\r\n"):
# for proper xml, we need to remove the CLIXML part
# (the first line)
msg_xml = msg[11:]
try:
# remove the namespaces from the xml for easier processing
msg_xml = self._strip_namespace(msg_xml)
root = ET.fromstring(msg_xml)
# the S node is the error message, find all S nodes
nodes = root.findall("./S")
new_msg = ""
for s in nodes:
# append error msg string to result, also
# the hex chars represent CRLF so we replace with newline
new_msg += s.text.replace("_x000D__x000A_", "\n")
except Exception as e:
# if any of the above fails, the msg was not true xml
# print a warning and return the orignal string
# TODO do not print, raise user defined error instead
print("Warning: there was a problem converting the Powershell"
" error message: %s" % (e))
else:
# if new_msg was populated, that's our error message
# otherwise the original error message will be used
if len(new_msg):
# remove leading and trailing whitespace while we are here
msg = new_msg.strip()
return msg
def _strip_namespace(self, xml):
"""strips any namespaces from an xml string"""
try:
p = re.compile("xmlns=*[\"\"][^\"\"]*[\"\"]")
allmatches = p.finditer(xml)
for match in allmatches:
xml = xml.replace(match.group(), "")
return xml
except Exception as e:
raise Exception(e)
@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) # NOQA
scheme = match.group('scheme')
if not scheme:
# TODO do we have anything other than HTTP/HTTPS
scheme = 'https' if transport == 'ssl' else 'http'
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('/'))
开发者ID:kschillz,项目名称:pywinrm,代码行数:93,代码来源:__init__.py
示例17: __init__
def __init__(self, url, auth, transport = "plaintext"):
#TODO convert short urls into well-formed endpoint
self.protocol = Protocol(url, auth, transport)
开发者ID:ader1990,项目名称:pywinrm,代码行数:3,代码来源:__init__.py
示例18: len
if key == "params":
paramlist = value.split("--")
for param in paramlist:
itemlist = param.split()
if 1 < len(itemlist):
script = script.replace("$$"+itemlist[0], itemlist[1])
else:
script = script.replace("$$"+key, value)
script = script.replace("\n", ";")
if "\\" in data["serverusername"]:
#script = base64.b64encode(script.encode("utf-16"))
cmd = "powershell -ExecutionPolicy Bypass -command %s" % (script)
p = Protocol(
endpoint='https://'+data["servername"]+':5986/wsman',
transport='credssp',
username=data["serverusername"],
password=data["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)
else:
script = "\n"+script
s = winrm.Session(data["servername"], auth=(data["serverusername"], data["password"]))
try:
r = s.run_ps(script)
# except winrm.exceptions.UnauthorizedError:
# print "Could not authenticate on the remote server:", sys.exc_info()[1]
# sys.exit(100)
开发者ID:cloudmunch,项目名称:CloudMunch-php-SDK-V2,代码行数:32,代码来源:powershell-interceptor.py
示例19: 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
def run_ps_long(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
shell_id = self.protocol.open_shell()
def run_command(command):
command_id = self.protocol.run_command(shell_id, command)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
# Powershell errors are returned in XML, clean them up
if len(rs.std_err):
rs.std_err = self.clean_error_msg(rs.std_err)
return rs
def make_ps_command(ps_script):
return ("powershell -encodedcommand %s"
% base64.b64encode(ps_script.encode("utf_16_le")))
def run_and_check_ps(command, stage_message):
rs = run_command(command)
if len(rs.std_err) or rs.status_code != 0:
self.protocol.close_shell(shell_id)
raise Exception("%s\n%s" % (stage_message, rs.std_err))
return rs.std_out
# Get the name of a temp file
cmd = ("$script_file = [IO.Path]::GetTempFileName() | "
" Rename-Item -NewName { $_ -replace 'tmp$', 'tmp.ps1' } -PassThru\n"
'"$script_file"')
script_file = run_and_check_ps(make_ps_command(cmd), "Creating temp script file")
script_file = script_file.strip()
# Append the data to the file
base64_script = base64.b64encode(script)
chunk_size = 2000
for chunk_index in range(0, len(base64_script), chunk_size):
chunk = base64_script[chunk_index:chunk_index + chunk_size]
cmd ='ECHO %s %s "%s" ' % (chunk,
('>>' if chunk_index else '>'),
script_file)
run_and_check_ps(cmd, "writing chunk %s to temp script file" % chunk_index)
# Execute the powershell script
cmd = '''
# Convert it from b64 encoded
$b64 = get-content "%(script_file)s"
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($b64)) |
out-file -Encoding Default "%(script_file)s"
''' % {'script_file':script_file}
run_and_check_ps(make_ps_command(cmd),
"Converting temp script file back from b64 encoding")
cmd = ("""PowerShell.exe -ExecutionPolicy Bypass -Command "& '%s' " """
% script_file)
rs = run_command(cmd)
# Finally, cleanup the temp file
cmd = "remove-item '%s' " % script_file
run_and_check_ps(make_ps_command(cmd), "Deleting temp script file")
self.protocol.close_shell(shell_id)
return rs
def run_ps(self, script):
# Get a temp powershell file name
# TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
base64_script = base64.b64encode(script.encode("utf_16_le"))
# There is an issue with powershell scripts over 2k or 8k (platform dependent)
# You can not have a command line + argument longer than this
if len(base64_script) > 2000:
return self.run_ps_long(script)
# must use utf16 little endian on windows
rs = self.run_cmd("powershell -encodedcommand %s" % (base64_script))
#.........这里部分代码省略.........
开发者ID:jarrodchesney,项目名称:pywinrm,代码行数:101,代码来源:__init__.py
示例20: WinRMHook
#.........这里部分代码省略.........
def get_conn(self):
if self.client:
return self.client
self.log.debug('Creating WinRM client for conn_id: %s', self.ssh_conn_id)
if self.ssh_conn_id is not None:
conn = self.get_connection(self.ssh_conn_id)
if self.username is None:
self.username = conn.login
if self.password is None:
self.password = conn.password
if self.remote_host is None:
self.remote_host = conn.host
if conn.extra is not None:
extra_options = conn.extra_dejson
if "endpoint" in extra_options:
self.endpoint = str(extra_options["endpoint"])
if "remote_port" in extra_options:
self.remote_port = int(extra_options["remote_port"])
if "transport" in extra_options:
self.transport = str(extra_options["transport"])
if "service" in extra_options:
self.service = str(extra_options["service"])
if "keytab" in extra_options:
self.keytab = str(extra_options["keytab"])
if "ca_trust_path" in extra_options:
self.ca_trust_path = str(extra_options["ca_trust_path"])
if "cert_pem" in extra_options:
self.cert_pem = str(extra_options["cert_pem"])
if "cert_key_pem" in extra_options:
self.cert_key_pem = str(extra_options["cert_key_pem"])
if "server_cert_validation" in extra_options:
self.server_cert_validation = str(extra_options["server_cert_validation"])
if "kerberos_delegation" in extra_options:
self.kerberos_delegation = str(extra_options["kerberos_delegation"]).lower() == 'true'
if "read_timeout_sec" in extra_options:
self.read_timeout_sec = int(extra_options["read_timeout_sec"])
if "operation_timeout_sec" in extra_options:
self.operation_timeout_sec = int(extra_options["operation_timeout_sec"])
if "kerberos_hostname_override" in extra_options:
self.kerberos_hostname_override = str(extra_options["kerberos_hostname_override"])
if "message_encryption" in extra_options:
self.message_encryption = str(extra_options["message_encryption"])
if "credssp_disable_tlsv1_2" in extra_options:
self.credssp_disable_tlsv1_2 = \
str(extra_options["credssp_disable_tlsv1_2"]).lower() == 'true'
if "send_cbt" in extra_options:
self.send_cbt = str(extra_options["send_cbt"]).lower() == 'true'
if not self.remote_host:
raise AirflowException("Missing required param: remote_host")
# Auto detecting username values from system
if not self.use
|
请发表评论