本文整理汇总了Python中winrm.protocol.Protocol.open_shell方法的典型用法代码示例。如果您正苦于以下问题:Python Protocol.open_shell方法的具体用法?Python Protocol.open_shell怎么用?Python Protocol.open_shell使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类winrm.protocol.Protocol
的用法示例。
在下文中一共展示了Protocol.open_shell方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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('/'))
示例2: _winrm_connect
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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: _try_winrm
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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
示例4: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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
示例5: run
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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}
示例6: _winrm_connect
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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')
示例7: _winrm_commands
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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
示例8: BaseWinRMClient
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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
示例9: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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('/'))
示例10: WinRMHook
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
#.........这里部分代码省略.........
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.username:
self.log.debug(
"username to WinRM to host: %s is not specified for connection id"
" %s. Using system's default provided by getpass.getuser()",
self.remote_host, self.ssh_conn_id
)
self.username = getpass.getuser()
# If endpoint is not set, then build a standard wsman endpoint from host and port.
if not self.endpoint:
self.endpoint = 'http://{0}:{1}/wsman'.format(self.remote_host, self.remote_port)
try:
if self.password and self.password.strip():
self.winrm_protocol = Protocol(
endpoint=self.endpoint,
transport=self.transport,
username=self.username,
password=self.password,
service=self.service,
keytab=self.keytab,
ca_trust_path=self.ca_trust_path,
cert_pem=self.cert_pem,
cert_key_pem=self.cert_key_pem,
server_cert_validation=self.server_cert_validation,
kerberos_delegation=self.kerberos_delegation,
read_timeout_sec=self.read_timeout_sec,
operation_timeout_sec=self.operation_timeout_sec,
kerberos_hostname_override=self.kerberos_hostname_override,
message_encryption=self.message_encryption,
credssp_disable_tlsv1_2=self.credssp_disable_tlsv1_2,
send_cbt=self.send_cbt
)
self.log.info("Establishing WinRM connection to host: %s", self.remote_host)
self.client = self.winrm_protocol.open_shell()
except Exception as error:
error_msg = "Error connecting to host: {0}, error: {1}".format(self.remote_host, error)
self.log.error(error_msg)
raise AirflowException(error_msg)
return self.client
示例11: Protocol
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
# Run a process on a remote host
s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
r = s.run_cmd('ipconfig', ['/all'])
print r.status_code, r.std_out,
# Run Powershell script on remote host
ps_script = """$strComputer = $Host
Clear
$RAM = WmiObject Win32_ComputerSystem
$MB = 1048576
"Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """
r = s.run_ps(ps_script)
print r.status_code, r.std_out,
# Run process with low-level API with domain user, disabling HTTPS cert validation
from winrm.protocol import Protocol
p = Protocol(
endpoint='https://windows-host:5986/wsman',
transport='ntlm',
username=r'somedomain\someuser',
password='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)
示例12: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
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))
#.........这里部分代码省略.........
示例13: WinRMHook
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import open_shell [as 别名]
#.........这里部分代码省略.........
:param username: username to connect to the remote_host
:type username: str
:param password: password of the username to connect to the remote_host
:type password: str
:param key_file: key file to use to connect to the remote_host.
:type key_file: str
:param timeout: timeout for the attempt to connect to the remote_host.
:type timeout: int
:param keepalive_interval: send a keepalive packet to remote host
every keepalive_interval seconds
:type keepalive_interval: int
"""
def __init__(self,
ssh_conn_id=None,
remote_host=None,
username=None,
password=None,
key_file=None,
timeout=10,
keepalive_interval=30
):
super(WinRMHook, self).__init__(ssh_conn_id)
# TODO make new win rm connection class
self.ssh_conn_id = ssh_conn_id
self.remote_host = remote_host
self.username = username
self.password = password
self.key_file = key_file
self.timeout = timeout
self.keepalive_interval = keepalive_interval
# Default values, overridable from Connection
self.compress = True
self.no_host_key_check = True
self.client = None
self.winrm_protocol = None
def get_conn(self):
if not 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
self.key_file = extra_options.get("key_file")
if "timeout" in extra_options:
self.timeout = int(extra_options["timeout"], 10)
if "compress" in extra_options \
and extra_options["compress"].lower() == 'false':
self.compress = False
if "no_host_key_check" in extra_options \
and extra_options["no_host_key_check"].lower() == 'false':
self.no_host_key_check = False
if not self.remote_host:
raise AirflowException("Missing required param: remote_host")
# Auto detecting username values from system
if not self.username:
self.log.debug(
"username to ssh to host: %s is not specified for connection id"
" %s. Using system's default provided by getpass.getuser()",
self.remote_host, self.ssh_conn_id
)
self.username = getpass.getuser()
try:
if self.password and self.password.strip():
self.winrm_protocol = Protocol(
# TODO pass in port from ssh conn
endpoint='http://' + self.remote_host + ':5985/wsman',
# TODO get cert transport working
# transport='certificate',
transport='plaintext',
# cert_pem=r'publickey.pem',
# cert_key_pem=r'dev.pem',
read_timeout_sec=70,
operation_timeout_sec=60,
username=self.username,
password=self.password,
server_cert_validation='ignore')
self.log.info("Opening WinRM shell")
self.client = self.winrm_protocol.open_shell()
except Exception as error:
self.log.error(
"Error connecting to host: %s, error: %s",
self.remote_host, error
)
return self.client