def addremovekey(self, command):
        """ Add or remove key based on command
        """
        provider = self._module.params.get("provider") or {}
        node = provider.get('host')
        if node is None:
            return False

        user = provider.get('username')
        if user is None:
            return False

        password = provider.get('password')
        ssh_keyfile = provider.get('ssh_keyfile')

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if not ssh_keyfile:
            ssh.connect(node, username=user, password=password)
        else:
            ssh.connect(node, username=user, allow_agent=True)
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('%s \r' %
                                                             (command))
        readmsg = ssh_stdout.read(
            100)  # We need to read a bit to actually apply for some reason
        if ('already' in readmsg) or ('removed' in readmsg) or ('really'
                                                                in readmsg):
            ssh_stdin.write('yes\r')
        ssh_stdout.read(
            1)  # We need to read a bit to actually apply for some reason
        ssh.close()

        return readmsg
    def copy_key_to_node(self, base64keyfile):
        """ Copy key to IOS-XR node. We use SFTP because older IOS-XR versions don't handle SCP very well.
        """
        provider = self._module.params.get("provider") or {}
        node = provider.get('host')
        if node is None:
            return False

        user = provider.get('username')
        if user is None:
            return False

        password = provider.get('password')
        ssh_keyfile = provider.get('ssh_keyfile')

        if self._module.params['aggregate']:
            name = 'aggregate'
        else:
            name = self._module.params['name']

        src = base64keyfile
        dst = '/harddisk:/publickey_%s.b64' % (name)

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if not ssh_keyfile:
            ssh.connect(node, username=user, password=password)
        else:
            ssh.connect(node, username=user, allow_agent=True)
        sftp = ssh.open_sftp()
        sftp.put(src, dst)
        sftp.close()
        ssh.close()
コード例 #3
0
    def addremovekey(self, command):
        """ Add or remove key based on command
        """
        if (
            self._module.params["host"] is None
            or self._module.params["provider"]["host"] is None
        ):
            return False

        if (
            self._module.params["username"] is None
            or self._module.params["provider"]["username"] is None
        ):
            return False

        user = (
            self._module.params["username"]
            or self._module.params["provider"]["username"]
        )
        node = (
            self._module.params["host"]
            or self._module.params["provider"]["host"]
        )
        password = (
            self._module.params["password"]
            or self._module.params["provider"]["password"]
        )
        ssh_keyfile = (
            self._module.params["ssh_keyfile"]
            or self._module.params["provider"]["ssh_keyfile"]
        )

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if not ssh_keyfile:
            ssh.connect(node, username=user, password=password)
        else:
            ssh.connect(node, username=user, allow_agent=True)
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(
            "%s \r" % (command)
        )
        readmsg = ssh_stdout.read(
            100
        )  # We need to read a bit to actually apply for some reason
        if (
            ("already" in readmsg)
            or ("removed" in readmsg)
            or ("really" in readmsg)
        ):
            ssh_stdin.write("yes\r")
        ssh_stdout.read(
            1
        )  # We need to read a bit to actually apply for some reason
        ssh.close()

        return readmsg
コード例 #4
0
    def copy_key_to_node(self, base64keyfile):
        """ Copy key to IOS-XR node. We use SFTP because older IOS-XR versions don't handle SCP very well.
        """
        if (
            self._module.params["host"] is None
            or self._module.params["provider"]["host"] is None
        ):
            return False

        if (
            self._module.params["username"] is None
            or self._module.params["provider"]["username"] is None
        ):
            return False

        if self._module.params["aggregate"]:
            name = "aggregate"
        else:
            name = self._module.params["name"]

        src = base64keyfile
        dst = "/harddisk:/publickey_%s.b64" % (name)

        user = (
            self._module.params["username"]
            or self._module.params["provider"]["username"]
        )
        node = (
            self._module.params["host"]
            or self._module.params["provider"]["host"]
        )
        password = (
            self._module.params["password"]
            or self._module.params["provider"]["password"]
        )
        ssh_keyfile = (
            self._module.params["ssh_keyfile"]
            or self._module.params["provider"]["ssh_keyfile"]
        )

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if not ssh_keyfile:
            ssh.connect(node, username=user, password=password)
        else:
            ssh.connect(node, username=user, allow_agent=True)
        sftp = ssh.open_sftp()
        sftp.put(src, dst)
        sftp.close()
        ssh.close()
コード例 #5
0
def generate_cert(module, ip_address, key_filename, password, cert_cn,
                  cert_friendly_name, signed_by, rsa_nbits):
    stdout = ""

    client = paramiko.SSHClient()

    # add policy to accept all host keys, I haven't found
    # a way to retrieve the instance SSH key fingerprint from AWS
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    if not key_filename:
        client.connect(ip_address, username="******", password=password)
    else:
        client.connect(ip_address, username="******", key_filename=key_filename)

    shell = client.invoke_shell()
    # wait for the shell to start
    buff = wait_with_timeout(module, shell, ">")
    stdout += buff

    # generate self-signed certificate
    if isinstance(cert_cn, list):
        cert_cn = cert_cn[0]
    cmd = 'request certificate generate signed-by {0} certificate-name {1} name {2} algorithm RSA rsa-nbits {3}\n'.format(
        signed_by, cert_friendly_name, cert_cn, rsa_nbits)
    shell.send(cmd)

    # wait for the shell to complete
    buff = wait_with_timeout(module, shell, ">")
    stdout += buff

    # exit
    shell.send('exit\n')

    if 'Success' not in buff:
        module.fail_json(msg="Error generating self signed certificate: " +
                         stdout)

    client.close()
    return stdout
コード例 #6
0
    def __init__(self, module, clustername, username, password, look_for_keys,
                 key_filename, log_path):
        """ Initialize module with what we need for initial connection
        :param clustername: name of the SVC cluster
        :type clustername: string
        :param username: SVC username
        :type username: string
        :param password: Password for user
        :type password: string
        :param look_for_keys: whether to look for keys or not
        :type look_for_keys: boolean
        :param key_filename: SSH client private key file
        :type key_filename: string
        :param log_path: log file
        :type log_path: string
        """
        self.module = module
        self.clustername = clustername
        self.username = username
        self.password = password
        self.look_for_keys = look_for_keys
        self.key_filename = key_filename

        self.is_client_connected = False

        # logging setup
        log = get_logger(self.__class__.__name__, log_path)
        self.log = log.info

        self.client_type = 'paramiko'
        if paramiko is None:
            self.module.fail_json(msg='paramiko is not installed')
        self.client = paramiko.SSHClient()

        # connect via SSH
        self.is_client_connected = self._svc_connect()
        if not self.is_client_connected:
            self.module.fail_json(msg='Failed to connect')
コード例 #7
0
def transfer_file_to_device(module, dest):
    file_size = os.path.getsize(module.params['local_file'])

    if not enough_space(module):
        module.fail_json(
            msg='Could not transfer file. Not enough space on device.')

    hostname = module.params['host']
    username = module.params['username']
    password = module.params['password']
    port = module.params['connect_ssh_port']

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname,
                username=username,
                password=password,
                port=port)

    full_remote_path = '{0}{1}'.format(module.params['file_system'], dest)
    scp = SCPClient(ssh.get_transport())
    try:
        scp.put(module.params['local_file'], full_remote_path)
    except Exception:
        time.sleep(10)
        temp_size = verify_remote_file_exists(
            module, dest, file_system=module.params['file_system'])
        if int(temp_size) == int(file_size):
            pass
        else:
            module.fail_json(msg='Could not transfer file. There was an error '
                             'during transfer. Please make sure remote '
                             'permissions are set.',
                             temp_size=temp_size,
                             file_size=file_size)
    scp.close()
    ssh.close()
    return True
コード例 #8
0
def set_panwfw_password(module, ip_address, key_filename, newpassword,
                        username):
    stdout = ""

    ssh = paramiko.SSHClient()

    # add policy to accept all host keys, I haven't found
    # a way to retrieve the instance SSH key fingerprint from AWS
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(ip_address, username=username, key_filename=key_filename)
    shell = ssh.invoke_shell()

    # wait for the shell to start
    buff = wait_with_timeout(module, shell, ">")
    stdout += buff

    # step into config mode
    shell.send('configure\n')
    # wait for the config prompt
    buff = wait_with_timeout(module, shell, "#")
    stdout += buff

    if module.check_mode:
        # exit and close connection
        shell.send('exit\n')
        ssh.close()
        return False, 'Connection test successful. Password left intact.'

    # set admin password
    shell.send('set mgt-config users ' + username + ' password\n')

    # wait for the password prompt
    buff = wait_with_timeout(module, shell, ":")
    stdout += buff

    # enter password for the first time
    shell.send(newpassword + '\n')

    # wait for the password prompt
    buff = wait_with_timeout(module, shell, ":")
    stdout += buff

    # enter password for the second time
    shell.send(newpassword + '\n')

    # wait for the config mode prompt
    buff = wait_with_timeout(module, shell, "#")
    stdout += buff

    # commit !
    shell.send('commit\n')

    # wait for the prompt
    buff = wait_with_timeout(module, shell, "#", 120)
    stdout += buff

    if 'success' not in buff:
        module.fail_json(msg="Error setting " + username + " password: " +
                         stdout)

    # exit
    shell.send('exit\n')

    ssh.close()

    return True, stdout
コード例 #9
0
ファイル: paramiko_ssh.py プロジェクト: mrlesmithjr/ansible-1
    def _connect_uncached(self):
        ''' activates the connection object '''

        if paramiko is None:
            raise AnsibleError("paramiko is not installed: %s" % to_native(PARAMIKO_IMPORT_ERR))

        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),
                    host=self._play_context.remote_addr)

        ssh = paramiko.SSHClient()

        # override paramiko's default logger name
        if self._log_channel is not None:
            ssh.set_log_channel(self._log_channel)

        self.keyfile = os.path.expanduser("~/.ssh/known_hosts")

        if self.get_option('host_key_checking'):
            for ssh_known_hosts in ("/etc/ssh/ssh_known_hosts", "/etc/openssh/ssh_known_hosts"):
                try:
                    # TODO: check if we need to look at several possible locations, possible for loop
                    ssh.load_system_host_keys(ssh_known_hosts)
                    break
                except IOError:
                    pass  # file was not found, but not required to function
            ssh.load_system_host_keys()

        ssh_connect_kwargs = self._parse_proxy_command(port)

        ssh.set_missing_host_key_policy(MyAddPolicy(self._new_stdin, self))

        conn_password = self.get_option('password') or self._play_context.password

        allow_agent = True

        if conn_password is not None:
            allow_agent = False

        try:
            key_filename = None
            if self._play_context.private_key_file:
                key_filename = os.path.expanduser(self._play_context.private_key_file)

            # paramiko 2.2 introduced auth_timeout parameter
            if LooseVersion(paramiko.__version__) >= LooseVersion('2.2.0'):
                ssh_connect_kwargs['auth_timeout'] = self._play_context.timeout

            # paramiko 1.15 introduced banner timeout parameter
            if LooseVersion(paramiko.__version__) >= LooseVersion('1.15.0'):
                ssh_connect_kwargs['banner_timeout'] = self.get_option('banner_timeout')

            ssh.connect(
                self._play_context.remote_addr.lower(),
                username=self._play_context.remote_user,
                allow_agent=allow_agent,
                look_for_keys=self.get_option('look_for_keys'),
                key_filename=key_filename,
                password=conn_password,
                timeout=self._play_context.timeout,
                port=port,
                **ssh_connect_kwargs
            )
        except paramiko.ssh_exception.BadHostKeyException as e:
            raise AnsibleConnectionFailure('host key mismatch for %s' % e.hostname)
        except paramiko.ssh_exception.AuthenticationException as e:
            msg = 'Failed to authenticate: {0}'.format(to_text(e))
            raise AnsibleAuthenticationFailure(msg)
        except Exception as e:
            msg = to_text(e)
            if u"PID check failed" in msg:
                raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
            elif u"Private key file is encrypted" in msg:
                msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
                    self._play_context.remote_user, self._play_context.remote_addr, port, msg)
                raise AnsibleConnectionFailure(msg)
            else:
                raise AnsibleConnectionFailure(msg)

        return ssh