Commit 3aede800 by James Cammarata

Fixing winrm connection for v2

parent 946c37fd
...@@ -48,7 +48,7 @@ class ConnectionInformation: ...@@ -48,7 +48,7 @@ class ConnectionInformation:
self.remote_addr = None self.remote_addr = None
self.remote_user = None self.remote_user = None
self.password = passwords.get('conn_pass','') self.password = passwords.get('conn_pass','')
self.port = 22 self.port = None
self.private_key_file = C.DEFAULT_PRIVATE_KEY_FILE self.private_key_file = C.DEFAULT_PRIVATE_KEY_FILE
self.timeout = C.DEFAULT_TIMEOUT self.timeout = C.DEFAULT_TIMEOUT
......
...@@ -56,20 +56,10 @@ class ActionBase: ...@@ -56,20 +56,10 @@ class ActionBase:
def get_shell(self): def get_shell(self):
# FIXME: no more inject, get this from the host variables? if hasattr(self._connection, '_shell'):
#default_shell = getattr(self._connection, 'default_shell', '') shell_plugin = getattr(self._connection, '_shell', '')
#shell_type = inject.get('ansible_shell_type') else:
#if not shell_type: shell_plugin = shell_loader.get(os.path.basename(C.DEFAULT_EXECUTABLE))
# if default_shell:
# shell_type = default_shell
# else:
# shell_type = os.path.basename(C.DEFAULT_EXECUTABLE)
shell_type = getattr(self._connection, 'default_shell', '')
if not shell_type:
shell_type = os.path.basename(C.DEFAULT_EXECUTABLE)
shell_plugin = shell_loader.get(shell_type)
if shell_plugin is None: if shell_plugin is None:
shell_plugin = shell_loader.get('sh') shell_plugin = shell_loader.get('sh')
......
...@@ -141,7 +141,8 @@ class Connection(ConnectionBase): ...@@ -141,7 +141,8 @@ class Connection(ConnectionBase):
if not HAVE_PARAMIKO: if not HAVE_PARAMIKO:
raise AnsibleError("paramiko is not installed") raise AnsibleError("paramiko is not installed")
self._display.vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (self._connection_info.remote_user, self._connection_info.port, self._connection_info.remote_addr), host=self._connection_info.remote_addr) port = self._connection_info.port or 22
self._display.vvv("ESTABLISH 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)
ssh = paramiko.SSHClient() ssh = paramiko.SSHClient()
...@@ -170,7 +171,7 @@ class Connection(ConnectionBase): ...@@ -170,7 +171,7 @@ class Connection(ConnectionBase):
key_filename=key_filename, key_filename=key_filename,
password=self._connection_info.password, password=self._connection_info.password,
timeout=self._connection_info.timeout, timeout=self._connection_info.timeout,
port=self._connection_info.port port=port,
) )
except Exception, e: except Exception, e:
msg = str(e) msg = str(e)
...@@ -178,7 +179,7 @@ class Connection(ConnectionBase): ...@@ -178,7 +179,7 @@ class Connection(ConnectionBase):
raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible") raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
elif "Private key file is encrypted" in msg: elif "Private key file is encrypted" in msg:
msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % ( msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
self._connection_info.remote_user, self._connection_info.remote_addr, self._connection_info.port, msg) self._connection_info.remote_user, self._connection_info.remote_addr, port, msg)
raise AnsibleConnectionFailure(msg) raise AnsibleConnectionFailure(msg)
else: else:
raise AnsibleConnectionFailure(msg) raise AnsibleConnectionFailure(msg)
......
...@@ -39,7 +39,7 @@ from ansible.plugins.connections import ConnectionBase ...@@ -39,7 +39,7 @@ from ansible.plugins.connections import ConnectionBase
class Connection(ConnectionBase): class Connection(ConnectionBase):
''' ssh based connections ''' ''' ssh based connections '''
def __init__(self, connection_info, *args, **kwargs): def __init__(self, *args, **kwargs):
# SSH connection specific init stuff # SSH connection specific init stuff
self.HASHED_KEY_MAGIC = "|1|" self.HASHED_KEY_MAGIC = "|1|"
self._has_pipelining = True self._has_pipelining = True
...@@ -50,7 +50,7 @@ class Connection(ConnectionBase): ...@@ -50,7 +50,7 @@ class Connection(ConnectionBase):
self._cp_dir = '/tmp' self._cp_dir = '/tmp'
#fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN) #fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
super(Connection, self).__init__(connection_info, *args, **kwargs) super(Connection, self).__init__(*args, **kwargs)
@property @property
def transport(self): def transport(self):
......
...@@ -32,33 +32,6 @@ _powershell_version = os.environ.get('POWERSHELL_VERSION', None) ...@@ -32,33 +32,6 @@ _powershell_version = os.environ.get('POWERSHELL_VERSION', None)
if _powershell_version: if _powershell_version:
_common_args = ['PowerShell', '-Version', _powershell_version] + _common_args[1:] _common_args = ['PowerShell', '-Version', _powershell_version] + _common_args[1:]
def _escape(value, include_vars=False):
'''Return value escaped for use in PowerShell command.'''
# http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
# http://stackoverflow.com/questions/764360/a-list-of-string-replacements-in-python
subs = [('\n', '`n'), ('\r', '`r'), ('\t', '`t'), ('\a', '`a'),
('\b', '`b'), ('\f', '`f'), ('\v', '`v'), ('"', '`"'),
('\'', '`\''), ('`', '``'), ('\x00', '`0')]
if include_vars:
subs.append(('$', '`$'))
pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
substs = [s for p, s in subs]
replace = lambda m: substs[m.lastindex - 1]
return re.sub(pattern, replace, value)
def _encode_script(script, as_list=False):
'''Convert a PowerShell script to a single base64-encoded command.'''
script = '\n'.join([x.strip() for x in script.splitlines() if x.strip()])
encoded_script = base64.b64encode(script.encode('utf-16-le'))
cmd_parts = _common_args + ['-EncodedCommand', encoded_script]
if as_list:
return cmd_parts
return ' '.join(cmd_parts)
def _build_file_cmd(cmd_parts):
'''Build command line to run a file, given list of file name plus args.'''
return ' '.join(_common_args + ['-ExecutionPolicy', 'Unrestricted', '-File'] + ['"%s"' % x for x in cmd_parts])
class ShellModule(object): class ShellModule(object):
def env_prefix(self, **kwargs): def env_prefix(self, **kwargs):
...@@ -75,19 +48,19 @@ class ShellModule(object): ...@@ -75,19 +48,19 @@ class ShellModule(object):
return '' return ''
def remove(self, path, recurse=False): def remove(self, path, recurse=False):
path = _escape(path) path = self._escape(path)
if recurse: if recurse:
return _encode_script('''Remove-Item "%s" -Force -Recurse;''' % path) return self._encode_script('''Remove-Item "%s" -Force -Recurse;''' % path)
else: else:
return _encode_script('''Remove-Item "%s" -Force;''' % path) return self._encode_script('''Remove-Item "%s" -Force;''' % path)
def mkdtemp(self, basefile, system=False, mode=None): def mkdtemp(self, basefile, system=False, mode=None):
basefile = _escape(basefile) basefile = self._escape(basefile)
# FIXME: Support system temp path! # FIXME: Support system temp path!
return _encode_script('''(New-Item -Type Directory -Path $env:temp -Name "%s").FullName | Write-Host -Separator '';''' % basefile) return self._encode_script('''(New-Item -Type Directory -Path $env:temp -Name "%s").FullName | Write-Host -Separator '';''' % basefile)
def md5(self, path): def md5(self, path):
path = _escape(path) path = self._escape(path)
script = ''' script = '''
If (Test-Path -PathType Leaf "%(path)s") If (Test-Path -PathType Leaf "%(path)s")
{ {
...@@ -105,15 +78,43 @@ class ShellModule(object): ...@@ -105,15 +78,43 @@ class ShellModule(object):
Write-Host "1"; Write-Host "1";
} }
''' % dict(path=path) ''' % dict(path=path)
return _encode_script(script) return self._encode_script(script)
def build_module_command(self, env_string, shebang, cmd, rm_tmp=None): def build_module_command(self, env_string, shebang, cmd, rm_tmp=None):
cmd = cmd.encode('utf-8') cmd = cmd.encode('utf-8')
cmd_parts = shlex.split(cmd, posix=False) cmd_parts = shlex.split(cmd, posix=False)
if not cmd_parts[0].lower().endswith('.ps1'): if not cmd_parts[0].lower().endswith('.ps1'):
cmd_parts[0] = '%s.ps1' % cmd_parts[0] cmd_parts[0] = '%s.ps1' % cmd_parts[0]
script = _build_file_cmd(cmd_parts) script = self._build_file_cmd(cmd_parts)
if rm_tmp: if rm_tmp:
rm_tmp = _escape(rm_tmp) rm_tmp = self._escape(rm_tmp)
script = '%s; Remove-Item "%s" -Force -Recurse;' % (script, rm_tmp) script = '%s; Remove-Item "%s" -Force -Recurse;' % (script, rm_tmp)
return _encode_script(script) return self._encode_script(script)
def _escape(self, value, include_vars=False):
'''Return value escaped for use in PowerShell command.'''
# http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
# http://stackoverflow.com/questions/764360/a-list-of-string-replacements-in-python
subs = [('\n', '`n'), ('\r', '`r'), ('\t', '`t'), ('\a', '`a'),
('\b', '`b'), ('\f', '`f'), ('\v', '`v'), ('"', '`"'),
('\'', '`\''), ('`', '``'), ('\x00', '`0')]
if include_vars:
subs.append(('$', '`$'))
pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
substs = [s for p, s in subs]
replace = lambda m: substs[m.lastindex - 1]
return re.sub(pattern, replace, value)
def _encode_script(self, script, as_list=False):
'''Convert a PowerShell script to a single base64-encoded command.'''
script = '\n'.join([x.strip() for x in script.splitlines() if x.strip()])
encoded_script = base64.b64encode(script.encode('utf-16-le'))
cmd_parts = _common_args + ['-EncodedCommand', encoded_script]
if as_list:
return cmd_parts
return ' '.join(cmd_parts)
def _build_file_cmd(self, cmd_parts):
'''Build command line to run a file, given list of file name plus args.'''
return ' '.join(_common_args + ['-ExecutionPolicy', 'Unrestricted', '-File'] + ['"%s"' % x for x in cmd_parts])
...@@ -73,6 +73,9 @@ class Display: ...@@ -73,6 +73,9 @@ class Display:
def vvvvv(self, msg, host=None): def vvvvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=4) return self.verbose(msg, host=host, caplevel=4)
def vvvvvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=5)
def verbose(self, msg, host=None, caplevel=2): def verbose(self, msg, host=None, caplevel=2):
# FIXME: this needs to be implemented # FIXME: this needs to be implemented
#msg = utils.sanitize_output(msg) #msg = utils.sanitize_output(msg)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment