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()
Ejemplo n.º 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
Ejemplo n.º 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()
Ejemplo n.º 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
Ejemplo n.º 6
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
Ejemplo n.º 7
0
 def _svc_connect(self):
     """
     Initialize a SSH connection with properties
     which were set up in constructor.
     :return: True or False
     """
     self.client.load_system_host_keys()
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     try:
         self.client.connect(hostname=self.clustername,
                             username=self.username,
                             password=self.password,
                             look_for_keys=self.look_for_keys,
                             key_filename=self.key_filename)
         return True
     except paramiko.BadHostKeyException as e:
         self.log("BadHostKeyException %s", e)
     except paramiko.AuthenticationException as e:
         self.log("AuthenticationException %s", e)
     except paramiko.SSHException as e:
         self.log("SSHException %s", e)
     except Exception as e:
         self.log("SSH connection failed %s", e)
     return False
Ejemplo n.º 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