Exemplo n.º 1
0
def apply_configs(machine, templates, variables):
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(AutoAddPolicy())

    ssh.connect(machine, username='******')
    scp = SCPClient(ssh.get_transport())

    something_changed = False

    for template_name, template_dest in templates.items():
        template = env.get_template(template_name)
        new_contents = template.render(**variables).encode('utf-8')

        with NamedTemporaryFile() as tmp_file:
            scp.get(template_dest, tmp_file.name)
            old_contents = tmp_file.read()

        if old_contents != new_contents:
            something_changed = True
            scp.putfo(BytesIO(new_contents), template_dest)

    scp.close()

    if something_changed:
        ssh.exec_command('reload_config')

    print(machine, '[changed]' if something_changed else '[ok]')

    ssh.close()
Exemplo n.º 2
0
 def upload(self, fl, remote_path):
     scp = SCPClient(self.shell.get_transport())
     if not hasattr(fl, 'getvalue'):
         fl_memory = BytesIO(fl.read())
         fl.seek(0)
         fl = fl_memory
     scp.putfo(fl, remote_path)
     scp.close()
Exemplo n.º 3
0
 def put(self, data, remote_path):
     # SFTP would be nice, but OpenWrt only supports SCP
     scp = SCPClient(
         self.client.get_transport())  # https://github.com/jbardin/scp.py
     data_file = io.BytesIO()  # in-memory file-like object
     data_file.write(data)
     data_file.seek(0)
     scp.putfo(data_file, remote_path)
     scp.close()
     data_file.close()
Exemplo n.º 4
0
def create_cloudinit_userdata(pve_node_name, vm):
    node_config = vm.platform.config['proxmox']['nodes'][pve_node_name]

    user = vm.template.config[
        'user'] if 'user' in vm.template.config and vm.template.config[
            'user'] is not None else 'debian'

    data = {
        'hostname': vm.name,
        'fqdn': '{}.{}'.format(vm.name, vm.platform.config['domain']),
        'user': user,
        'ssh_authorized_keys':
        vm.platform.config['proxmox']['ssh_authorized_keys'],
        'chpasswd': {
            'expire': False
        },
        'users': ['default'],
        'package_upgrade': True,
        'runcmd': get_run_cmd(vm),
        'bootcmd': ['echo "nameserver 1.1.1.1" > /etc/resolv.conf'],
        'power_state': {
            'mode': 'poweroff',
            'timeout': 240,
            'condition': True
        }
    }
    userdata_file = '{}/cloudinit_user_{}.yaml'.format(
        node_config['userdata_location'], vm.state['proxmox']['id'])
    not_really_a_file = io.StringIO(node_config['private_ssh_key'])
    private_key = paramiko.Ed25519Key.from_private_key(not_really_a_file)
    not_really_a_file.close()

    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys(
    )  # TODO Server '195.154.87.154' not found in known_hosts if removed
    ssh.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())  # TODO Is this good?
    ssh.connect(node_config['ip'],
                username=node_config['ssh_user'],
                pkey=private_key)
    scp = SCPClient(ssh.get_transport())

    fl = io.StringIO()
    fl.write('#cloud-config\n')
    yaml.dump(data, fl, default_flow_style=False)
    fl.seek(0)
    scp.putfo(fl, userdata_file)
    scp.close()
    fl.close()

    return True
Exemplo n.º 5
0
 def stream(self, content, destination):
     if self.__status != 'error':
         scp = SCPClient(self.__connector.get_transport())
         fl = io.BytesIO()
         fl.write(content)
         fl.seek(0)
         scp.putfo(fl, destination)
         fl.close()
         result = {}
         result['status'] = 'success'
         result[
             'message'] = "Streamed content to " + self.__user + "@" + self.__host + destination
         self.__results.append(result)
     return self
Exemplo n.º 6
0
    def upload_scp(self,
                   file_stream,
                   dest_pathname,
                   file_size=None,
                   dest_permissions="0601"):
        """Upload SCP.

        :param file_stream: filelike object: open file, StringIO, or other
            filelike object to read data from
        :param str dest_pathname: name of the file in the destination, with optional
            folder path prefix
        :param int file_size: size of the file, mandatory unless you are sure SFTP is
            available, in which case pass 0
        :param str dest_permissions: permission string as octal digits, e.g. 0601
        """
        scp = SCPClient(self._handler.get_transport())
        scp.putfo(
            fl=file_stream,
            remote_path=dest_pathname,
            mode=dest_permissions,
            size=file_size,
        )
        scp.close()
Exemplo n.º 7
0
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    counter = 0
    prevKey = None
    for server in sorted_ips:
        name = server[0]
        ip = server[1]
        ssh.connect(ip, username="******")
        print("Connected to", name, "with ip", server)
        scp = SCPClient(ssh.get_transport(), progress=progress)
        if name == "cepa0":
            fl = io.BytesIO()
            fl.write(b'test')
            fl.seek(0)
            print("Put dummy key")
            scp.putfo(fl, repo_dir + dummy)
        else:
            # Push the last server key
            prev_server_key = prefix + str(counter - 1) + suffix
            print("Put " + prev_server_key)
            scp.put(prev_server_key, input_key) # Catch exception
            ssh.exec_command("mv " + input_key + " " + repo_dir)

        # Pull the current server key
        curr_server_key = prefix + str(counter) + suffix
        print("Pull " + curr_server_key)
        scp.get(repo_dir + server_key)
        os.rename(server_key, curr_server_key)

        counter += 1
Exemplo n.º 8
0
 def put_file(self, fileobj: "io.BytesIO", path: "str", on_progress=None):
     with self._ssh_connect() as ssh:
         scp = SCPClient(ssh.get_transport(), progress=on_progress)
         scp.putfo(fileobj, path)