Exemple #1
0
    def configure_dhcp_files(self):
        for _dir in [
                os.path.dirname(ztp_opts_conf),
                os.path.dirname(ztp_hosts_conf)
        ]:
            if not os.path.isdir(_dir):
                os.mkdir(_dir)
                utils.set_perm(_dir, user='******', group='rwx', other='rx')

        # -- get dhcp-range= line from wired-dhcp.conf and override it in ztp.conf with shorter lease time for ztp
        with open('/etc/ConsolePi/dnsmasq.d/wired-dhcp/wired-dhcp.conf') as f:
            dhcp_main_lines = f.readlines()

        line = [
            f"{','.join(_line.split(',')[0:-1])},{ztp_lease_time}\n"
            for _line in dhcp_main_lines
            if _line.strip().startswith('dhcp-range=')
        ]
        if line and len(line) == 1:
            self.ztp_main_lines.insert(0, line[0])
        else:
            print(
                "!! Error occured getting dhcp-range from wired-dhcp.conf lease-time will not be updated for ZTP"
            )

        for _file, _lines in zip(
            [ztp_main_conf, ztp_hosts_conf, ztp_opts_conf], [
                self.ztp_main_lines, self.ztp_host_lines,
                utils.unique(self.ztp_opt_lines)
            ]):
            with open(_file, "w") as f:
                f.writelines(_lines)

            # assign file to consolepi group and makes group writable.  Makes troubleshooting easier
            utils.set_perm(_file, other='r')
Exemple #2
0
    def dhcp_append(self, ztp: Ztp):
        if self.prep_dhcp:
            self.ztp_main_lines = utils.unique(self.ztp_main_lines +
                                               ztp.main_lines)
            self.ztp_host_lines += ztp.host_lines
            self.ztp_opt_lines += ztp.opt_lines

        if hasattr(ztp, 'cfg_file_name'):
            self.ztp_clifile_data[ztp.cfg_file_name] = ztp.conf
Exemple #3
0
def _write_to_file(fp, current: list, new: list):
    new = utils.unique(new)
    if 'ztp-opts' in fp.name:   # Overwrite the existing file contents
        for line_num, line in enumerate(new):
            fp.write(line)
    else:                       # Append to existing file for ztp-hosts.conf
        for line_num, line in enumerate(new):
            if line not in current:
                fp.write(line)
            else:
                log.info(f"Skipping write for content on line {line_num} ({line[0:20]}...) as the line already exists")
Exemple #4
0
    def get_hosts(self):
        '''Parse user defined hosts.json for inclusion in menu

        returns dict with formatted keys prepending /host/
        '''
        # utils = self.utils
        hosts = self.cfg_yml.get('HOSTS')
        if not hosts:  # fallback to legacy json config
            hosts = self.get_json_file(self.static.get('REM_HOSTS_FILE'))
            if not hosts:
                return {}

        # generate remote command used in menu
        for h in hosts:
            if hosts[h].get('method').lower() == 'ssh':
                port = 22 if ':' not in hosts[h]['address'] else hosts[h]['address'].split(':')[1]
                _user_str = '' if not hosts[h].get('username') else f'{hosts[h].get("username")}@'
                hosts[h]['cmd'] = f"sudo -u {self.loc_user} ssh -t {_user_str}{hosts[h]['address'].split(':')[0]} -p {port}"
            elif hosts[h].get('method').lower() == 'telnet':
                port = 23 if ':' not in hosts[h]['address'] else hosts[h]['address'].split(':')[1]
                _user_str = '' if not hosts[h].get('username') else f'-l {hosts[h].get("username")}'
                hosts[h]['cmd'] = f"sudo -u {self.loc_user} telnet {_user_str} {hosts[h]['address'].split(':')[0]} {port}"

        groups = [hosts[h].get('group', 'user-defined') for h in hosts]
        host_dict = {'main': {}, 'rshell': {}}

        for g in utils.unique(groups):
            host_dict['main'][g] = {f'/host/{h.split("/")[-1]}': hosts[h] for h in hosts
                                    if hosts[h].get('show_in_main', False) and hosts[h].get('group', 'user-defined') == g}
            if not host_dict['main'][g]:
                del host_dict['main'][g]
            host_dict['rshell'][g] = {f'/host/{h.split("/")[-1]}': hosts[h] for h in hosts
                                      if not hosts[h].get('show_in_main', False) and hosts[h].get('group', 'user-defined') == g}
            if not host_dict['rshell'][g]:
                del host_dict['rshell'][g]

        host_dict['_methods'] = utils.unique([hosts[h]['method'] for h in hosts])
        host_dict['_host_list'] = [f'/host/{h.split("/")[-1]}' for h in hosts]

        return host_dict
Exemple #5
0
    def get_hosts(self):
        '''Parse user defined hosts for inclusion in menu

        returns dict with formatted keys prepending /host/
        '''
        # utils = self.utils
        hosts = self.cfg_yml.get('HOSTS')
        if not hosts:  # fallback to legacy json config
            hosts = self.get_json_file(self.static.get('REM_HOSTS_FILE'))
            if not hosts:
                return {}

        # generate remote command used in menu
        for h in hosts:
            hosts[h]["method"] = hosts[h].get('method', 'ssh').lower()
            if hosts[h][
                    "method"] == 'ssh':  # method defaults to ssh if not provided
                port = 22 if ':' not in hosts[h]['address'] else hosts[h][
                    'address'].split(':')[1]
                _user_str = '' if not hosts[h].get(
                    'username') else f'{hosts[h].get("username")}@'
                key_file = None
                if hosts[h].get("key") and self.loc_user is not None:
                    if utils.valid_file(
                            f"/home/{self.loc_user}/.ssh/{hosts[h]['key']}"):
                        user_key = Path(
                            f"/home/{self.loc_user}/.ssh/{hosts[h]['key']}")
                        if utils.valid_file(
                                f"/etc/ConsolePi/.ssh/{hosts[h]['key']}"):
                            mstr_key = Path(
                                f"/etc/ConsolePi/.ssh/{hosts[h]['key']}")
                            if mstr_key.stat().st_mtime > user_key.stat(
                            ).st_mtime:
                                shutil.copy(mstr_key, user_key)
                                shutil.chown(user_key,
                                             user=self.loc_user,
                                             group=self.loc_user)
                                user_key.chmod(0o600)
                                log.info(
                                    f"{hosts[h]['key']} Updated from ConsolePi global .ssh key_dir to "
                                    f"{str(user_key.parent)} for use with {h}...",
                                    show=True)
                            key_file = str(user_key)
                    elif utils.valid_file(hosts[h]['key']):
                        key_file = hosts[h]['key']
                    elif utils.valid_file(
                            f"/etc/ConsolePi/.ssh/{hosts[h]['key']}"):
                        user_ssh_dir = Path(f"/home/{self.loc_user}/.ssh/")
                        if user_ssh_dir.is_dir:
                            shutil.copy(
                                f"/etc/ConsolePi/.ssh/{hosts[h]['key']}",
                                user_ssh_dir)
                            user_key = Path(
                                f"{user_ssh_dir}/{hosts[h]['key']}")
                            shutil.chown(user_key,
                                         user=self.loc_user,
                                         group=self.loc_user)
                            user_key.chmod(0o600)
                            log.info(
                                f"{hosts[h]['key']} imported from ConsolePi global .ssh key_dir to "
                                f"{str(user_ssh_dir)} for use with {h}...",
                                show=True)
                            key_file = str(user_key)
                hosts[h]['cmd'] = f"sudo -u {self.loc_user} ssh{' ' if not key_file else f' -i {key_file} '}" \
                                  f"-t {_user_str}{hosts[h]['address'].split(':')[0]} -p {port}"
                # hosts[h]['cmd'] = f"sudo -u {self.loc_user} ssh -t {_user_str}{hosts[h]['address'].split(':')[0]} -p {port}"
            elif hosts[h].get('method').lower() == 'telnet':
                port = 23 if ':' not in hosts[h]['address'] else hosts[h][
                    'address'].split(':')[1]
                _user_str = '' if not hosts[h].get(
                    'username') else f'-l {hosts[h].get("username")}'
                hosts[h][
                    'cmd'] = f"sudo -u {self.loc_user} telnet {_user_str} {hosts[h]['address'].split(':')[0]} {port}"

        groups = [hosts[h].get('group', 'user-defined') for h in hosts]
        host_dict = {'main': {}, 'rshell': {}}

        for g in utils.unique(groups):
            host_dict['main'][g] = {
                f'/host/{h.split("/")[-1]}': hosts[h]
                for h in hosts if hosts[h].get('show_in_main', False)
                and hosts[h].get('group', 'user-defined') == g
            }
            if not host_dict['main'][g]:
                del host_dict['main'][g]
            host_dict['rshell'][g] = {
                f'/host/{h.split("/")[-1]}': hosts[h]
                for h in hosts if not hosts[h].get('show_in_main', False)
                and hosts[h].get('group', 'user-defined') == g
            }
            if not host_dict['rshell'][g]:
                del host_dict['rshell'][g]

        host_dict['_methods'] = utils.unique(
            [hosts[h].get('method', 'ssh') for h in hosts])
        host_dict['_host_list'] = [f'/host/{h.split("/")[-1]}' for h in hosts]

        return host_dict
Exemple #6
0
 def dhcp_append(self, ztp: Ztp):
     self.ztp_main_lines = utils.unique(self.ztp_main_lines +
                                        ztp.main_lines)
     self.ztp_host_lines += ztp.host_lines
     self.ztp_opt_lines += ztp.opt_lines