2014-11-14 23:14:08 +01:00
|
|
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
|
2017-08-20 17:20:30 +02:00
|
|
|
# (c) 2017 Ansible Project
|
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
2017-09-08 20:08:31 +02:00
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
|
|
|
DOCUMENTATION = """
|
2017-08-20 17:20:30 +02:00
|
|
|
author: Ansible Core Team
|
2020-10-06 18:37:16 +02:00
|
|
|
name: paramiko
|
2017-08-20 17:20:30 +02:00
|
|
|
short_description: Run tasks via python ssh (paramiko)
|
|
|
|
description:
|
|
|
|
- Use the python ssh implementation (Paramiko) to connect to targets
|
|
|
|
- The paramiko transport is provided because many distributions, in particular EL6 and before do not support ControlPersist
|
|
|
|
in their SSH implementations.
|
|
|
|
- This is needed on the Ansible control machine to be reasonably efficient with connections.
|
|
|
|
Thus paramiko is faster for most users on these platforms.
|
|
|
|
Users with ControlPersist capability can consider using -c ssh or configuring the transport in the configuration file.
|
2017-11-16 19:49:57 +01:00
|
|
|
- This plugin also borrows a lot of settings from the ssh plugin as they both cover the same protocol.
|
2017-08-20 17:20:30 +02:00
|
|
|
version_added: "0.1"
|
|
|
|
options:
|
|
|
|
remote_addr:
|
|
|
|
description:
|
|
|
|
- Address of the remote target
|
|
|
|
default: inventory_hostname
|
|
|
|
vars:
|
|
|
|
- name: ansible_host
|
|
|
|
- name: ansible_ssh_host
|
|
|
|
- name: ansible_paramiko_host
|
|
|
|
remote_user:
|
|
|
|
description:
|
|
|
|
- User to login/authenticate as
|
2017-12-07 15:26:52 +01:00
|
|
|
- Can be set from the CLI via the C(--user) or C(-u) options.
|
2017-08-20 17:20:30 +02:00
|
|
|
vars:
|
|
|
|
- name: ansible_user
|
|
|
|
- name: ansible_ssh_user
|
|
|
|
- name: ansible_paramiko_user
|
2017-11-16 19:49:57 +01:00
|
|
|
env:
|
|
|
|
- name: ANSIBLE_REMOTE_USER
|
|
|
|
- name: ANSIBLE_PARAMIKO_REMOTE_USER
|
|
|
|
version_added: '2.5'
|
|
|
|
ini:
|
|
|
|
- section: defaults
|
|
|
|
key: remote_user
|
|
|
|
- section: paramiko_connection
|
|
|
|
key: remote_user
|
|
|
|
version_added: '2.5'
|
|
|
|
password:
|
|
|
|
description:
|
|
|
|
- Secret used to either login the ssh server or as a passphrase for ssh keys that require it
|
2017-12-07 15:26:52 +01:00
|
|
|
- Can be set from the CLI via the C(--ask-pass) option.
|
2017-11-16 19:49:57 +01:00
|
|
|
vars:
|
|
|
|
- name: ansible_password
|
|
|
|
- name: ansible_ssh_pass
|
2019-02-11 16:43:10 +01:00
|
|
|
- name: ansible_ssh_password
|
2017-11-16 19:49:57 +01:00
|
|
|
- name: ansible_paramiko_pass
|
2019-02-11 16:43:10 +01:00
|
|
|
- name: ansible_paramiko_password
|
2017-11-16 19:49:57 +01:00
|
|
|
version_added: '2.5'
|
|
|
|
host_key_auto_add:
|
|
|
|
description: 'TODO: write it'
|
|
|
|
env: [{name: ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD}]
|
|
|
|
ini:
|
|
|
|
- {key: host_key_auto_add, section: paramiko_connection}
|
|
|
|
type: boolean
|
|
|
|
look_for_keys:
|
|
|
|
default: True
|
|
|
|
description: 'TODO: write it'
|
|
|
|
env: [{name: ANSIBLE_PARAMIKO_LOOK_FOR_KEYS}]
|
|
|
|
ini:
|
|
|
|
- {key: look_for_keys, section: paramiko_connection}
|
|
|
|
type: boolean
|
|
|
|
proxy_command:
|
|
|
|
default: ''
|
|
|
|
description:
|
|
|
|
- Proxy information for running the connection via a jumphost
|
|
|
|
- Also this plugin will scan 'ssh_args', 'ssh_extra_args' and 'ssh_common_args' from the 'ssh' plugin settings for proxy information if set.
|
|
|
|
env: [{name: ANSIBLE_PARAMIKO_PROXY_COMMAND}]
|
|
|
|
ini:
|
|
|
|
- {key: proxy_command, section: paramiko_connection}
|
|
|
|
pty:
|
|
|
|
default: True
|
|
|
|
description: 'TODO: write it'
|
|
|
|
env:
|
|
|
|
- name: ANSIBLE_PARAMIKO_PTY
|
|
|
|
ini:
|
|
|
|
- section: paramiko_connection
|
|
|
|
key: pty
|
|
|
|
type: boolean
|
|
|
|
record_host_keys:
|
|
|
|
default: True
|
|
|
|
description: 'TODO: write it'
|
|
|
|
env: [{name: ANSIBLE_PARAMIKO_RECORD_HOST_KEYS}]
|
|
|
|
ini:
|
|
|
|
- section: paramiko_connection
|
|
|
|
key: record_host_keys
|
|
|
|
type: boolean
|
|
|
|
host_key_checking:
|
|
|
|
description: 'Set this to "False" if you want to avoid host key checking by the underlying tools Ansible uses to connect to the host'
|
|
|
|
type: boolean
|
|
|
|
default: True
|
|
|
|
env:
|
|
|
|
- name: ANSIBLE_HOST_KEY_CHECKING
|
|
|
|
- name: ANSIBLE_SSH_HOST_KEY_CHECKING
|
|
|
|
version_added: '2.5'
|
|
|
|
- name: ANSIBLE_PARAMIKO_HOST_KEY_CHECKING
|
|
|
|
version_added: '2.5'
|
|
|
|
ini:
|
|
|
|
- section: defaults
|
|
|
|
key: host_key_checking
|
|
|
|
- section: paramiko_connection
|
|
|
|
key: host_key_checking
|
|
|
|
version_added: '2.5'
|
|
|
|
vars:
|
|
|
|
- name: ansible_host_key_checking
|
|
|
|
version_added: '2.5'
|
|
|
|
- name: ansible_ssh_host_key_checking
|
|
|
|
version_added: '2.5'
|
|
|
|
- name: ansible_paramiko_host_key_checking
|
|
|
|
version_added: '2.5'
|
2018-05-16 14:59:01 +02:00
|
|
|
use_persistent_connections:
|
|
|
|
description: 'Toggles the use of persistence for connections'
|
|
|
|
type: boolean
|
|
|
|
default: False
|
|
|
|
env:
|
|
|
|
- name: ANSIBLE_USE_PERSISTENT_CONNECTIONS
|
|
|
|
ini:
|
|
|
|
- section: defaults
|
|
|
|
key: use_persistent_connections
|
2017-08-20 17:20:30 +02:00
|
|
|
# TODO:
|
2017-11-16 19:49:57 +01:00
|
|
|
#timeout=self._play_context.timeout,
|
2017-08-20 17:20:30 +02:00
|
|
|
"""
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
import os
|
|
|
|
import socket
|
|
|
|
import tempfile
|
|
|
|
import traceback
|
|
|
|
import fcntl
|
|
|
|
import sys
|
2015-12-24 22:01:41 +01:00
|
|
|
import re
|
2015-04-24 08:47:56 +02:00
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
from termios import tcflush, TCIFLUSH
|
2021-05-11 19:33:51 +02:00
|
|
|
from ansible.module_utils.compat.version import LooseVersion
|
2014-11-14 23:14:08 +01:00
|
|
|
from binascii import hexlify
|
2015-04-24 08:47:56 +02:00
|
|
|
|
2019-01-23 17:32:25 +01:00
|
|
|
from ansible.errors import (
|
|
|
|
AnsibleAuthenticationFailure,
|
|
|
|
AnsibleConnectionFailure,
|
|
|
|
AnsibleError,
|
|
|
|
AnsibleFileNotFound,
|
|
|
|
)
|
2019-04-04 04:35:59 +02:00
|
|
|
from ansible.module_utils.compat.paramiko import PARAMIKO_IMPORT_ERR, paramiko
|
2017-03-23 21:35:05 +01:00
|
|
|
from ansible.module_utils.six import iteritems
|
|
|
|
from ansible.module_utils.six.moves import input
|
2015-09-15 17:57:54 +02:00
|
|
|
from ansible.plugins.connection import ConnectionBase
|
2018-11-21 00:06:51 +01:00
|
|
|
from ansible.utils.display import Display
|
2015-06-02 17:41:30 +02:00
|
|
|
from ansible.utils.path import makedirs_safe
|
2018-11-09 07:59:30 +01:00
|
|
|
from ansible.module_utils._text import to_bytes, to_native, to_text
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2018-11-21 00:06:51 +01:00
|
|
|
display = Display()
|
2015-11-11 16:10:14 +01:00
|
|
|
|
2016-09-07 07:54:17 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
AUTHENTICITY_MSG = """
|
2014-11-14 23:14:08 +01:00
|
|
|
paramiko: The authenticity of host '%s' can't be established.
|
|
|
|
The %s key fingerprint is %s.
|
|
|
|
Are you sure you want to continue connecting (yes/no)?
|
|
|
|
"""
|
|
|
|
|
2015-12-24 22:01:41 +01:00
|
|
|
# SSH Options Regex
|
|
|
|
SETTINGS_REGEX = re.compile(r'(\w+)(?:\s*=\s*|\s+)(.+)')
|
|
|
|
|
2015-05-13 17:58:46 +02:00
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
class MyAddPolicy(object):
|
|
|
|
"""
|
|
|
|
Based on AutoAddPolicy in paramiko so we can determine when keys are added
|
2017-11-09 21:04:40 +01:00
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
and also prompt for input.
|
|
|
|
|
|
|
|
Policy for automatically adding the hostname and new host key to the
|
|
|
|
local L{HostKeys} object, and saving it. This is used by L{SSHClient}.
|
|
|
|
"""
|
|
|
|
|
2015-09-02 19:22:35 +02:00
|
|
|
def __init__(self, new_stdin, connection):
|
2015-04-24 08:47:56 +02:00
|
|
|
self._new_stdin = new_stdin
|
2015-09-02 19:22:35 +02:00
|
|
|
self.connection = connection
|
2017-11-16 19:49:57 +01:00
|
|
|
self._options = connection._options
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
def missing_host_key(self, client, hostname, key):
|
|
|
|
|
2017-11-16 19:49:57 +01:00
|
|
|
if all((self._options['host_key_checking'], not self._options['host_key_auto_add'])):
|
2016-11-28 17:31:12 +01:00
|
|
|
|
2017-11-09 21:04:40 +01:00
|
|
|
fingerprint = hexlify(key.get_fingerprint())
|
|
|
|
ktype = key.get_name()
|
|
|
|
|
2018-05-16 14:59:01 +02:00
|
|
|
if self.connection.get_option('use_persistent_connections') or self.connection.force_persistence:
|
2017-11-09 21:04:40 +01:00
|
|
|
# don't print the prompt string since the user cannot respond
|
|
|
|
# to the question anyway
|
|
|
|
raise AnsibleError(AUTHENTICITY_MSG[1:92] % (hostname, ktype, fingerprint))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-09-04 06:42:01 +02:00
|
|
|
self.connection.connection_lock()
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
old_stdin = sys.stdin
|
2015-04-24 08:47:56 +02:00
|
|
|
sys.stdin = self._new_stdin
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
# clear out any premature input on sys.stdin
|
|
|
|
tcflush(sys.stdin, TCIFLUSH)
|
|
|
|
|
2016-09-03 05:32:14 +02:00
|
|
|
inp = input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint))
|
2014-11-14 23:14:08 +01:00
|
|
|
sys.stdin = old_stdin
|
2015-04-24 08:47:56 +02:00
|
|
|
|
2015-09-04 06:42:01 +02:00
|
|
|
self.connection.connection_unlock()
|
2015-09-02 19:22:35 +02:00
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
if inp not in ['yes', 'y', '']:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("host connection rejected by user")
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
key._added_by_ansible_this_time = True
|
|
|
|
|
|
|
|
# existing implementation below:
|
|
|
|
client._host_keys.add(hostname, key.get_name(), key)
|
|
|
|
|
|
|
|
# host keys are actually saved in close() function below
|
|
|
|
# in order to control ordering.
|
|
|
|
|
|
|
|
|
|
|
|
# keep connection objects on a per host basis to avoid repeated attempts to reconnect
|
|
|
|
|
|
|
|
SSH_CONNECTION_CACHE = {}
|
|
|
|
SFTP_CONNECTION_CACHE = {}
|
|
|
|
|
2015-11-11 16:10:14 +01:00
|
|
|
|
2015-04-24 08:47:56 +02:00
|
|
|
class Connection(ConnectionBase):
|
2014-11-14 23:14:08 +01:00
|
|
|
''' SSH based connections with Paramiko '''
|
|
|
|
|
2016-03-16 19:22:50 +01:00
|
|
|
transport = 'paramiko'
|
2018-04-26 23:10:28 +02:00
|
|
|
_log_channel = None
|
2015-04-24 01:54:48 +02:00
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
def _cache_key(self):
|
2019-02-27 00:01:39 +01:00
|
|
|
return "%s__%s__" % (self._play_context.remote_addr, self._play_context.remote_user)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-04-24 08:47:56 +02:00
|
|
|
def _connect(self):
|
2014-11-14 23:14:08 +01:00
|
|
|
cache_key = self._cache_key()
|
|
|
|
if cache_key in SSH_CONNECTION_CACHE:
|
|
|
|
self.ssh = SSH_CONNECTION_CACHE[cache_key]
|
|
|
|
else:
|
|
|
|
self.ssh = SSH_CONNECTION_CACHE[cache_key] = self._connect_uncached()
|
2021-04-29 21:11:02 +02:00
|
|
|
|
|
|
|
self._connected = True
|
2014-11-14 23:14:08 +01:00
|
|
|
return self
|
|
|
|
|
2018-04-26 23:10:28 +02:00
|
|
|
def _set_log_channel(self, name):
|
|
|
|
'''Mimic paramiko.SSHClient.set_log_channel'''
|
|
|
|
self._log_channel = name
|
|
|
|
|
2015-12-24 22:10:42 +01:00
|
|
|
def _parse_proxy_command(self, port=22):
|
2015-12-24 22:01:41 +01:00
|
|
|
proxy_command = None
|
|
|
|
# Parse ansible_ssh_common_args, specifically looking for ProxyCommand
|
2016-01-11 18:55:25 +01:00
|
|
|
ssh_args = [
|
2016-10-26 19:38:08 +02:00
|
|
|
getattr(self._play_context, 'ssh_extra_args', '') or '',
|
|
|
|
getattr(self._play_context, 'ssh_common_args', '') or '',
|
|
|
|
getattr(self._play_context, 'ssh_args', '') or '',
|
2016-01-11 18:55:25 +01:00
|
|
|
]
|
2020-04-28 16:36:22 +02:00
|
|
|
|
|
|
|
args = self._split_ssh_args(' '.join(ssh_args))
|
|
|
|
for i, arg in enumerate(args):
|
|
|
|
if arg.lower() == 'proxycommand':
|
|
|
|
# _split_ssh_args split ProxyCommand from the command itself
|
|
|
|
proxy_command = args[i + 1]
|
|
|
|
else:
|
|
|
|
# ProxyCommand and the command itself are a single string
|
|
|
|
match = SETTINGS_REGEX.match(arg)
|
|
|
|
if match:
|
|
|
|
if match.group(1).lower() == 'proxycommand':
|
|
|
|
proxy_command = match.group(2)
|
|
|
|
|
|
|
|
if proxy_command:
|
|
|
|
break
|
2015-12-24 22:01:41 +01:00
|
|
|
|
2017-11-28 18:00:22 +01:00
|
|
|
proxy_command = proxy_command or self.get_option('proxy_command')
|
2015-12-24 22:01:41 +01:00
|
|
|
|
2015-12-23 21:57:24 +01:00
|
|
|
sock_kwarg = {}
|
2015-12-24 22:01:41 +01:00
|
|
|
if proxy_command:
|
2015-12-23 21:57:24 +01:00
|
|
|
replacers = {
|
|
|
|
'%h': self._play_context.remote_addr,
|
|
|
|
'%p': port,
|
2019-02-27 00:01:39 +01:00
|
|
|
'%r': self._play_context.remote_user
|
2015-12-23 21:57:24 +01:00
|
|
|
}
|
|
|
|
for find, replace in replacers.items():
|
|
|
|
proxy_command = proxy_command.replace(find, str(replace))
|
|
|
|
try:
|
|
|
|
sock_kwarg = {'sock': paramiko.ProxyCommand(proxy_command)}
|
|
|
|
display.vvv("CONFIGURE PROXY COMMAND FOR CONNECTION: %s" % proxy_command, host=self._play_context.remote_addr)
|
|
|
|
except AttributeError:
|
|
|
|
display.warning('Paramiko ProxyCommand support unavailable. '
|
|
|
|
'Please upgrade to Paramiko 1.9.0 or newer. '
|
|
|
|
'Not using configured ProxyCommand')
|
|
|
|
|
2015-12-24 22:10:42 +01:00
|
|
|
return sock_kwarg
|
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
def _connect_uncached(self):
|
|
|
|
''' activates the connection object '''
|
|
|
|
|
2019-04-04 04:35:59 +02:00
|
|
|
if paramiko is None:
|
|
|
|
raise AnsibleError("paramiko is not installed: %s" % to_native(PARAMIKO_IMPORT_ERR))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2019-02-27 00:01:39 +01:00
|
|
|
port = self._play_context.port or 22
|
|
|
|
display.vvv("ESTABLISH PARAMIKO SSH CONNECTION FOR USER: %s on PORT %s TO %s" % (self._play_context.remote_user, port, self._play_context.remote_addr),
|
2017-03-23 02:50:28 +01:00
|
|
|
host=self._play_context.remote_addr)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
ssh = paramiko.SSHClient()
|
|
|
|
|
2018-04-26 23:10:28 +02:00
|
|
|
# override paramiko's default logger name
|
|
|
|
if self._log_channel is not None:
|
|
|
|
ssh.set_log_channel(self._log_channel)
|
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
self.keyfile = os.path.expanduser("~/.ssh/known_hosts")
|
|
|
|
|
2017-11-28 18:00:22 +01:00
|
|
|
if self.get_option('host_key_checking'):
|
2016-01-14 11:01:49 +01:00
|
|
|
for ssh_known_hosts in ("/etc/ssh/ssh_known_hosts", "/etc/openssh/ssh_known_hosts"):
|
|
|
|
try:
|
2017-06-02 13:14:11 +02:00
|
|
|
# TODO: check if we need to look at several possible locations, possible for loop
|
2016-01-14 11:01:49 +01:00
|
|
|
ssh.load_system_host_keys(ssh_known_hosts)
|
|
|
|
break
|
|
|
|
except IOError:
|
2017-06-02 13:14:11 +02:00
|
|
|
pass # file was not found, but not required to function
|
2014-11-14 23:14:08 +01:00
|
|
|
ssh.load_system_host_keys()
|
|
|
|
|
2019-01-09 01:25:17 +01:00
|
|
|
ssh_connect_kwargs = self._parse_proxy_command(port)
|
2015-12-24 22:10:42 +01:00
|
|
|
|
2015-09-02 19:22:35 +02:00
|
|
|
ssh.set_missing_host_key_policy(MyAddPolicy(self._new_stdin, self))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-05-29 17:00:21 +02:00
|
|
|
conn_password = self.get_option('password') or self._play_context.password
|
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
allow_agent = True
|
|
|
|
|
2020-05-29 17:00:21 +02:00
|
|
|
if conn_password is not None:
|
2014-11-14 23:14:08 +01:00
|
|
|
allow_agent = False
|
|
|
|
|
|
|
|
try:
|
2015-04-24 08:47:56 +02:00
|
|
|
key_filename = None
|
2015-07-21 18:12:22 +02:00
|
|
|
if self._play_context.private_key_file:
|
|
|
|
key_filename = os.path.expanduser(self._play_context.private_key_file)
|
2015-04-24 08:47:56 +02:00
|
|
|
|
2019-01-09 01:25:17 +01:00
|
|
|
# paramiko 2.2 introduced auth_timeout parameter
|
|
|
|
if LooseVersion(paramiko.__version__) >= LooseVersion('2.2.0'):
|
|
|
|
ssh_connect_kwargs['auth_timeout'] = self._play_context.timeout
|
|
|
|
|
2015-04-24 08:47:56 +02:00
|
|
|
ssh.connect(
|
2018-02-02 16:08:40 +01:00
|
|
|
self._play_context.remote_addr.lower(),
|
2019-02-27 00:01:39 +01:00
|
|
|
username=self._play_context.remote_user,
|
2015-04-24 08:47:56 +02:00
|
|
|
allow_agent=allow_agent,
|
2017-11-28 18:00:22 +01:00
|
|
|
look_for_keys=self.get_option('look_for_keys'),
|
2015-04-24 08:47:56 +02:00
|
|
|
key_filename=key_filename,
|
2020-05-29 17:00:21 +02:00
|
|
|
password=conn_password,
|
2015-07-21 18:12:22 +02:00
|
|
|
timeout=self._play_context.timeout,
|
2015-04-27 07:28:25 +02:00
|
|
|
port=port,
|
2019-01-09 01:25:17 +01:00
|
|
|
**ssh_connect_kwargs
|
2015-04-24 08:47:56 +02:00
|
|
|
)
|
2017-04-28 19:57:32 +02:00
|
|
|
except paramiko.ssh_exception.BadHostKeyException as e:
|
|
|
|
raise AnsibleConnectionFailure('host key mismatch for %s' % e.hostname)
|
2019-01-23 17:32:25 +01:00
|
|
|
except paramiko.ssh_exception.AuthenticationException as e:
|
2019-10-31 20:39:53 +01:00
|
|
|
msg = 'Failed to authenticate: {0}'.format(to_text(e))
|
2019-01-23 17:32:25 +01:00
|
|
|
raise AnsibleAuthenticationFailure(msg)
|
2015-04-27 17:33:29 +02:00
|
|
|
except Exception as e:
|
2018-11-09 07:59:30 +01:00
|
|
|
msg = to_text(e)
|
|
|
|
if u"PID check failed" in msg:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
|
2018-11-09 07:59:30 +01:00
|
|
|
elif u"Private key file is encrypted" in msg:
|
2014-11-14 23:14:08 +01:00
|
|
|
msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
|
2019-02-27 00:01:39 +01:00
|
|
|
self._play_context.remote_user, self._play_context.remote_addr, port, msg)
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleConnectionFailure(msg)
|
2014-11-14 23:14:08 +01:00
|
|
|
else:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleConnectionFailure(msg)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
return ssh
|
|
|
|
|
2015-09-24 22:29:36 +02:00
|
|
|
def exec_command(self, cmd, in_data=None, sudoable=True):
|
2014-11-14 23:14:08 +01:00
|
|
|
''' run a command on the remote host '''
|
|
|
|
|
2015-09-24 22:29:36 +02:00
|
|
|
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
|
2015-06-04 20:27:18 +02:00
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
if in_data:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("Internal Error: this module does not support optimized module pipelining")
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
bufsize = 4096
|
|
|
|
|
|
|
|
try:
|
|
|
|
self.ssh.get_transport().set_keepalive(5)
|
|
|
|
chan = self.ssh.get_transport().open_session()
|
2015-04-27 17:33:29 +02:00
|
|
|
except Exception as e:
|
2018-11-09 07:59:30 +01:00
|
|
|
text_e = to_text(e)
|
|
|
|
msg = u"Failed to open session"
|
|
|
|
if text_e:
|
|
|
|
msg += u": %s" % text_e
|
|
|
|
raise AnsibleConnectionFailure(to_native(msg))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-04-24 08:47:56 +02:00
|
|
|
# sudo usually requires a PTY (cf. requiretty option), therefore
|
2018-08-10 01:34:23 +02:00
|
|
|
# we give it one by default (pty=True in ansible.cfg), and we try
|
2016-04-12 14:34:24 +02:00
|
|
|
# to initialise from the calling environment when sudoable is enabled
|
2017-11-28 18:00:22 +01:00
|
|
|
if self.get_option('pty') and sudoable:
|
2015-04-24 08:47:56 +02:00
|
|
|
chan.get_pty(term=os.getenv('TERM', 'vt100'), width=int(os.getenv('COLUMNS', 0)), height=int(os.getenv('LINES', 0)))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-11-11 16:10:14 +01:00
|
|
|
display.vvv("EXEC %s" % cmd, host=self._play_context.remote_addr)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2016-09-07 07:54:17 +02:00
|
|
|
cmd = to_bytes(cmd, errors='surrogate_or_strict')
|
2016-03-19 19:13:38 +01:00
|
|
|
|
2016-09-03 05:32:14 +02:00
|
|
|
no_prompt_out = b''
|
|
|
|
no_prompt_err = b''
|
|
|
|
become_output = b''
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-04-24 08:47:56 +02:00
|
|
|
try:
|
|
|
|
chan.exec_command(cmd)
|
Become plugins (#50991)
* [WIP] become plugins
Move from hardcoded method to plugins for ease of use, expansion and overrides
- load into connection as it is going to be the main consumer
- play_context will also use to keep backwards compat API
- ensure shell is used to construct commands when needed
- migrate settings remove from base config in favor of plugin specific configs
- cleanup ansible-doc
- add become plugin docs
- remove deprecated sudo/su code and keywords
- adjust become options for cli
- set plugin options from context
- ensure config defs are avaialbe before instance
- refactored getting the shell plugin, fixed tests
- changed into regex as they were string matching, which does not work with random string generation
- explicitly set flags for play context tests
- moved plugin loading up front
- now loads for basedir also
- allow pyc/o for non m modules
- fixes to tests and some plugins
- migrate to play objects fro play_context
- simiplify gathering
- added utf8 headers
- moved option setting
- add fail msg to dzdo
- use tuple for multiple options on fail/missing
- fix relative plugin paths
- shift from play context to play
- all tasks already inherit this from play directly
- remove obsolete 'set play'
- correct environment handling
- add wrap_exe option to pfexec
- fix runas to noop
- fixed setting play context
- added password configs
- removed required false
- remove from doc building till they are ready
future development:
- deal with 'enable' and 'runas' which are not 'command wrappers' but 'state flags' and currently hardcoded in diff subsystems
* cleanup
remove callers to removed func
removed --sudo cli doc refs
remove runas become_exe
ensure keyerorr on plugin
also fix backwards compat, missing method is attributeerror, not ansible error
get remote_user consistently
ignore missing system_tmpdirs on plugin load
correct config precedence
add deprecation
fix networking imports
backwards compat for plugins using BECOME_METHODS
* Port become_plugins to context.CLIARGS
This is a work in progress:
* Stop passing options around everywhere as we can use context.CLIARGS
instead
* Refactor make_become_commands as asked for by alikins
* Typo in comment fix
* Stop loading values from the cli in more than one place
Both play and play_context were saving default values from the cli
arguments directly. This changes things so that the default values are
loaded into the play and then play_context takes them from there.
* Rename BECOME_PLUGIN_PATH to DEFAULT_BECOME_PLUGIN_PATH
As alikins said, all other plugin paths are named
DEFAULT_plugintype_PLUGIN_PATH. If we're going to rename these, that
should be done all at one time rather than piecemeal.
* One to throw away
This is a set of hacks to get setting FieldAttribute defaults to command
line args to work. It's not fully done yet.
After talking it over with sivel and jimi-c this should be done by
fixing FieldAttributeBase and _get_parent_attribute() calls to do the
right thing when there is a non-None default.
What we want to be able to do ideally is something like this:
class Base(FieldAttributeBase):
_check_mode = FieldAttribute([..] default=lambda: context.CLIARGS['check'])
class Play(Base):
# lambda so that we have a chance to parse the command line args
# before we get here. In the future we might be able to restructure
# this so that the cli parsing code runs before these classes are
# defined.
class Task(Base):
pass
And still have a playbook like this function:
---
- hosts:
tasks:
- command: whoami
check_mode: True
(The check_mode test that is added as a separate commit in this PR will
let you test variations on this case).
There's a few separate reasons that the code doesn't let us do this or
a non-ugly workaround for this as written right now. The fix that
jimi-c, sivel, and I talked about may let us do this or it may still
require a workaround (but less ugly) (having one class that has the
FieldAttributes with default values and one class that inherits from
that but just overrides the FieldAttributes which now have defaults)
* Revert "One to throw away"
This reverts commit 23aa883cbed11429ef1be2a2d0ed18f83a3b8064.
* Set FieldAttr defaults directly from CLIARGS
* Remove dead code
* Move timeout directly to PlayContext, it's never needed on Play
* just for backwards compat, add a static version of BECOME_METHODS to constants
* Make the become attr on the connection public, since it's used outside of the connection
* Logic fix
* Nuke connection testing if it supports specific become methods
* Remove unused vars
* Address rebase issues
* Fix path encoding issue
* Remove unused import
* Various cleanups
* Restore network_cli check in _low_level_execute_command
* type improvements for cliargs_deferred_get and swap shallowcopy to default to False
* minor cleanups
* Allow the su plugin to work, since it doesn't define a prompt the same way
* Fix up ksu become plugin
* Only set prompt if build_become_command was called
* Add helper to assist connection plugins in knowing they need to wait for a prompt
* Fix tests and code expectations
* Doc updates
* Various additional minor cleanups
* Make doas functional
* Don't change connection signature, load become plugin from TaskExecutor
* Remove unused imports
* Add comment about setting the become plugin on the playcontext
* Fix up tests for recent changes
* Support 'Password:' natively for the doas plugin
* Make default prompts raw
* wording cleanups. ci_complete
* Remove unrelated changes
* Address spelling mistake
* Restore removed test, and udpate to use new functionality
* Add changelog fragment
* Don't hard fail in set_attributes_from_cli on missing CLI keys
* Remove unrelated change to loader
* Remove internal deprecated FieldAttributes now
* Emit deprecation warnings now
2019-02-11 18:27:44 +01:00
|
|
|
if self.become and self.become.expect_prompt():
|
2015-09-04 15:30:31 +02:00
|
|
|
passprompt = False
|
2016-02-09 23:08:33 +01:00
|
|
|
become_sucess = False
|
|
|
|
while not (become_sucess or passprompt):
|
2015-11-11 16:10:14 +01:00
|
|
|
display.debug('Waiting for Privilege Escalation input')
|
2015-09-04 15:30:31 +02:00
|
|
|
|
|
|
|
chunk = chan.recv(bufsize)
|
2015-11-11 16:10:14 +01:00
|
|
|
display.debug("chunk is: %s" % chunk)
|
2015-09-04 15:30:31 +02:00
|
|
|
if not chunk:
|
2017-03-29 15:02:28 +02:00
|
|
|
if b'unknown user' in become_output:
|
2019-11-17 20:32:56 +01:00
|
|
|
n_become_user = to_native(self.become.get_option('become_user',
|
|
|
|
playcontext=self._play_context))
|
|
|
|
raise AnsibleError('user %s does not exist' % n_become_user)
|
2015-08-07 22:26:23 +02:00
|
|
|
else:
|
2015-09-04 15:30:31 +02:00
|
|
|
break
|
2017-06-02 13:14:11 +02:00
|
|
|
# raise AnsibleError('ssh connection closed waiting for password prompt')
|
2015-09-04 15:30:31 +02:00
|
|
|
become_output += chunk
|
2016-02-09 23:08:33 +01:00
|
|
|
|
|
|
|
# need to check every line because we might get lectured
|
|
|
|
# and we might get the middle of a line in a chunk
|
|
|
|
for l in become_output.splitlines(True):
|
2019-02-11 20:44:54 +01:00
|
|
|
if self.become.check_success(l):
|
2016-02-09 23:08:33 +01:00
|
|
|
become_sucess = True
|
|
|
|
break
|
2019-02-11 20:44:54 +01:00
|
|
|
elif self.become.check_password_prompt(l):
|
2016-02-09 23:08:33 +01:00
|
|
|
passprompt = True
|
|
|
|
break
|
|
|
|
|
2015-09-04 15:30:31 +02:00
|
|
|
if passprompt:
|
2019-11-17 20:32:56 +01:00
|
|
|
if self.become:
|
|
|
|
become_pass = self.become.get_option('become_pass', playcontext=self._play_context)
|
|
|
|
chan.sendall(to_bytes(become_pass, errors='surrogate_or_strict') + b'\n')
|
2015-07-19 08:23:53 +02:00
|
|
|
else:
|
2017-12-12 23:13:27 +01:00
|
|
|
raise AnsibleError("A password is required but none was supplied")
|
2015-09-04 15:30:31 +02:00
|
|
|
else:
|
|
|
|
no_prompt_out += become_output
|
|
|
|
no_prompt_err += become_output
|
2015-04-24 08:47:56 +02:00
|
|
|
except socket.timeout:
|
|
|
|
raise AnsibleError('ssh timed out waiting for privilege escalation.\n' + become_output)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2016-09-03 05:32:14 +02:00
|
|
|
stdout = b''.join(chan.makefile('rb', bufsize))
|
|
|
|
stderr = b''.join(chan.makefile_stderr('rb', bufsize))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2015-09-24 17:56:20 +02:00
|
|
|
return (chan.recv_exit_status(), no_prompt_out + stdout, no_prompt_out + stderr)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
def put_file(self, in_path, out_path):
|
|
|
|
''' transfer a file from local to remote '''
|
|
|
|
|
2015-06-04 20:27:18 +02:00
|
|
|
super(Connection, self).put_file(in_path, out_path)
|
|
|
|
|
2015-11-11 16:10:14 +01:00
|
|
|
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2016-09-07 07:54:17 +02:00
|
|
|
if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleFileNotFound("file or module does not exist: %s" % in_path)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
self.sftp = self.ssh.open_sftp()
|
2015-04-27 17:33:29 +02:00
|
|
|
except Exception as e:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("failed to open a SFTP connection (%s)" % e)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
try:
|
2016-09-07 07:54:17 +02:00
|
|
|
self.sftp.put(to_bytes(in_path, errors='surrogate_or_strict'), to_bytes(out_path, errors='surrogate_or_strict'))
|
2014-11-14 23:14:08 +01:00
|
|
|
except IOError:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("failed to transfer file to %s" % out_path)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
def _connect_sftp(self):
|
|
|
|
|
2019-02-27 00:01:39 +01:00
|
|
|
cache_key = "%s__%s__" % (self._play_context.remote_addr, self._play_context.remote_user)
|
2014-11-14 23:14:08 +01:00
|
|
|
if cache_key in SFTP_CONNECTION_CACHE:
|
|
|
|
return SFTP_CONNECTION_CACHE[cache_key]
|
|
|
|
else:
|
2015-05-13 17:58:46 +02:00
|
|
|
result = SFTP_CONNECTION_CACHE[cache_key] = self._connect().ssh.open_sftp()
|
2014-11-14 23:14:08 +01:00
|
|
|
return result
|
|
|
|
|
|
|
|
def fetch_file(self, in_path, out_path):
|
|
|
|
''' save a remote file to the specified path '''
|
|
|
|
|
2015-06-04 20:27:18 +02:00
|
|
|
super(Connection, self).fetch_file(in_path, out_path)
|
|
|
|
|
2015-11-11 16:10:14 +01:00
|
|
|
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._play_context.remote_addr)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
self.sftp = self._connect_sftp()
|
2015-04-27 17:33:29 +02:00
|
|
|
except Exception as e:
|
2017-05-19 18:56:55 +02:00
|
|
|
raise AnsibleError("failed to open a SFTP connection (%s)" % to_native(e))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
try:
|
2016-09-07 07:54:17 +02:00
|
|
|
self.sftp.get(to_bytes(in_path, errors='surrogate_or_strict'), to_bytes(out_path, errors='surrogate_or_strict'))
|
2014-11-14 23:14:08 +01:00
|
|
|
except IOError:
|
2015-04-24 08:47:56 +02:00
|
|
|
raise AnsibleError("failed to transfer file from %s" % in_path)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
def _any_keys_added(self):
|
|
|
|
|
2015-09-03 08:23:27 +02:00
|
|
|
for hostname, keys in iteritems(self.ssh._host_keys):
|
|
|
|
for keytype, key in iteritems(keys):
|
2014-11-14 23:14:08 +01:00
|
|
|
added_this_time = getattr(key, '_added_by_ansible_this_time', False)
|
|
|
|
if added_this_time:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def _save_ssh_host_keys(self, filename):
|
|
|
|
'''
|
|
|
|
not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks
|
|
|
|
don't complain about it :)
|
|
|
|
'''
|
|
|
|
|
|
|
|
if not self._any_keys_added():
|
|
|
|
return False
|
|
|
|
|
|
|
|
path = os.path.expanduser("~/.ssh")
|
2015-06-02 17:41:30 +02:00
|
|
|
makedirs_safe(path)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
with open(filename, 'w') as f:
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
for hostname, keys in iteritems(self.ssh._host_keys):
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
for keytype, key in iteritems(keys):
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
# was f.write
|
|
|
|
added_this_time = getattr(key, '_added_by_ansible_this_time', False)
|
|
|
|
if not added_this_time:
|
|
|
|
f.write("%s %s %s\n" % (hostname, keytype, key.get_base64()))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
for hostname, keys in iteritems(self.ssh._host_keys):
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2020-01-06 19:09:57 +01:00
|
|
|
for keytype, key in iteritems(keys):
|
|
|
|
added_this_time = getattr(key, '_added_by_ansible_this_time', False)
|
|
|
|
if added_this_time:
|
|
|
|
f.write("%s %s %s\n" % (hostname, keytype, key.get_base64()))
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2018-11-27 22:48:57 +01:00
|
|
|
def reset(self):
|
2020-12-09 19:57:56 +01:00
|
|
|
if not self._connected:
|
|
|
|
return
|
2018-11-27 22:48:57 +01:00
|
|
|
self.close()
|
|
|
|
self._connect()
|
|
|
|
|
2014-11-14 23:14:08 +01:00
|
|
|
def close(self):
|
|
|
|
''' terminate the connection '''
|
|
|
|
|
|
|
|
cache_key = self._cache_key()
|
|
|
|
SSH_CONNECTION_CACHE.pop(cache_key, None)
|
|
|
|
SFTP_CONNECTION_CACHE.pop(cache_key, None)
|
|
|
|
|
2016-11-28 18:49:40 +01:00
|
|
|
if hasattr(self, 'sftp'):
|
|
|
|
if self.sftp is not None:
|
|
|
|
self.sftp.close()
|
2014-11-14 23:14:08 +01:00
|
|
|
|
2017-11-28 18:00:22 +01:00
|
|
|
if self.get_option('host_key_checking') and self.get_option('record_host_keys') and self._any_keys_added():
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
# add any new SSH host keys -- warning -- this could be slow
|
2015-09-02 19:22:35 +02:00
|
|
|
# (This doesn't acquire the connection lock because it needs
|
|
|
|
# to exclude only other known_hosts writers, not connections
|
|
|
|
# that are starting up.)
|
2017-06-02 13:14:11 +02:00
|
|
|
lockfile = self.keyfile.replace("known_hosts", ".known_hosts.lock")
|
2014-11-14 23:14:08 +01:00
|
|
|
dirname = os.path.dirname(self.keyfile)
|
2015-06-02 17:41:30 +02:00
|
|
|
makedirs_safe(dirname)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
KEY_LOCK = open(lockfile, 'w')
|
|
|
|
fcntl.lockf(KEY_LOCK, fcntl.LOCK_EX)
|
|
|
|
|
|
|
|
try:
|
|
|
|
# just in case any were added recently
|
|
|
|
|
|
|
|
self.ssh.load_system_host_keys()
|
|
|
|
self.ssh._host_keys.update(self.ssh._system_host_keys)
|
|
|
|
|
|
|
|
# gather information about the current key file, so
|
|
|
|
# we can ensure the new file has the correct mode/owner
|
|
|
|
|
2017-06-02 13:14:11 +02:00
|
|
|
key_dir = os.path.dirname(self.keyfile)
|
2016-07-01 22:39:02 +02:00
|
|
|
if os.path.exists(self.keyfile):
|
|
|
|
key_stat = os.stat(self.keyfile)
|
|
|
|
mode = key_stat.st_mode
|
|
|
|
uid = key_stat.st_uid
|
|
|
|
gid = key_stat.st_gid
|
|
|
|
else:
|
|
|
|
mode = 33188
|
|
|
|
uid = os.getuid()
|
|
|
|
gid = os.getgid()
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
# Save the new keys to a temporary file and move it into place
|
|
|
|
# rather than rewriting the file. We set delete=False because
|
|
|
|
# the file will be moved into place rather than cleaned up.
|
|
|
|
|
|
|
|
tmp_keyfile = tempfile.NamedTemporaryFile(dir=key_dir, delete=False)
|
2016-07-01 22:39:02 +02:00
|
|
|
os.chmod(tmp_keyfile.name, mode & 0o7777)
|
|
|
|
os.chown(tmp_keyfile.name, uid, gid)
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
self._save_ssh_host_keys(tmp_keyfile.name)
|
|
|
|
tmp_keyfile.close()
|
|
|
|
|
|
|
|
os.rename(tmp_keyfile.name, self.keyfile)
|
|
|
|
|
2018-11-27 22:48:57 +01:00
|
|
|
except Exception:
|
2014-11-14 23:14:08 +01:00
|
|
|
|
|
|
|
# unable to save keys, including scenario when key was invalid
|
|
|
|
# and caught earlier
|
|
|
|
traceback.print_exc()
|
|
|
|
fcntl.lockf(KEY_LOCK, fcntl.LOCK_UN)
|
|
|
|
|
|
|
|
self.ssh.close()
|
2018-11-27 22:48:57 +01:00
|
|
|
self._connected = False
|