Ejemplo n.º 1
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.
        """
        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()
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
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
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
Ejemplo n.º 5
0
    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))

        allow_agent = True

        if self._play_context.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

            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=self._play_context.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