Exemple #1
0
def nfsrv():
    pacman(S='nfs-utils', _in='y')
    makedirs('/srv/nfs4')
    with open('/etc/exports', 'a') as f:
        f.write('\n  /srv/nfs4        192.168.0.*(rw,sync,fsid=0,no_wdelay,no_root_squash,no_subtree_check)\n\n')
    systemctl('enable', 'nfs-server')
    systemctl('start', 'nfs-server')
Exemple #2
0
def status_service(service_name: str,
                   *,
                   get_sudo: bool = False,
                   run_as: RunAsEnum = RunAsEnum.user) -> None:
    """

    Args:
        service_name:
        :param service_name:
        :param run_as:
        :param get_sudo:
    """
    project_service_name = f"{PROJECT_NAME}_service_{service_name}"
    print(f"Status for {project_service_name}")
    try:
        with ContextWrapper(
                sh.contrib.sudo,
                construction_kwargs=dict(
                    password=(getpass.getpass(
                        prompt=f"[sudo] password for {getpass.getuser()}: ")
                              if get_sudo else None),
                    _with=True,
                ),
                enabled=get_sudo,
        ):
            sh.systemctl((["--user"] if run_as == RunAsEnum.user else []) +
                         ["status", f"{project_service_name}.service"])
    except sh.ErrorReturnCode_3 as e:
        print(e, e.stdout)
Exemple #3
0
def enable_service(service_name: str,
                   *,
                   get_sudo: bool = False,
                   run_as: RunAsEnum = RunAsEnum.user) -> None:
    """

    Args:
        service_name:
        :param service_name:
        :param run_as:
        :param get_sudo:
    """
    project_service_name = f"{PROJECT_NAME}_service_{service_name}"
    print(f"Enabling {project_service_name}")
    with ContextWrapper(
            sh.contrib.sudo,
            construction_kwargs=dict(
                password=(getpass.getpass(
                    prompt=f"[sudo] password for {getpass.getuser()}: ")
                          if get_sudo else None),
                _with=True,
            ),
            enabled=get_sudo,
    ):
        sh.systemctl((["--user"] if run_as == RunAsEnum.user else []) +
                     [f"enable", f"{project_service_name}.service"])
        start_service(service_name, get_sudo=False, run_as=run_as)
Exemple #4
0
def ensure_service() -> bool:
    """Poke SystemD to ensure docker is running"""
    try:
        systemctl('is-active', 'docker', _fg=True)
        return False
    except ErrorReturnCode:
        systemctl.start('docker', _fg=True)
        return True
Exemple #5
0
 def is_active(bg=False):
     try:
         sh.systemctl(
             "--no-page",
             "is-active",
             self.name,
             _bg=bg,
             _piped=True)
         return True
     except ErrorReturnCode:
         return False
def update_dhcpd_if_needed():
    """
    Updates dhcpd config and restarts daemon if needed.

    Idempotent function.
    """
    if dhcpd_update_needed():
        set_dhcpd_config(dhcpd_config())
        sh.systemctl('restart', 'dhcpd@primary')

    return True
Exemple #7
0
    def install(self):
        """Installs the service on the local machine

        This is where we deploy the service files to their relevant
        locations and perform any other required actions to configure
        the service and make it ready to be `start`ed.
        """
        super(SystemD, self).install()

        self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
        self.deploy_service_file(self.env_file_path, self.env_file_dest)
        sh.systemctl.enable(self.name)
        sh.systemctl('daemon-reload')
def update_config(next_inst, region_amis):
    # Update /etc/gitlab-runner/config.toml with new configuration.
    sed("-i", f"s/amazonec2-zone=[a-f]/amazonec2-zone={next_inst.zone}/g",
        "/etc/gitlab-runner/config.toml")
    sed(
        "-i",
        f"s/amazonec2-ami=ami-[a-z0-9]*/amazonec2-ami={region_amis[next_inst.region]}/g",
        "/etc/gitlab-runner/config.toml")
    sed(
        "-i",
        f"s/amazonec2-instance-type=[a-z0-9]*.[a-z0-9]*/amazonec2-instance-type={next_inst.instance}/g",
        "/etc/gitlab-runner/config.toml")
    systemctl("restart", "gitlab-runner")
    syslog.syslog(f"min_bid_price.py - Moved CI to {next_inst}")
Exemple #9
0
    def uninstall(self):
        """Uninstalls the service.

        This is supposed to perform any cleanup operations required to
        remove the service. Files, links, whatever else should be removed.
        This method should also run when implementing cleanup in case of
        failures. As such, idempotence should be considered.
        """
        sh.systemctl.disable(self.name)
        sh.systemctl('daemon-reload')
        if os.path.isfile(self.svc_file_dest):
            os.remove(self.svc_file_dest)
        if os.path.isfile(self.env_file_dest):
            os.remove(self.env_file_dest)
Exemple #10
0
def systemctl_show(service):
    cmd = sh.systemctl('show', '--no-page', service)
    out = cmd.stdout.decode('utf-8')

    lines = out.splitlines()
    pairs = [tuple(line.split('=', 1)) for line in lines if line]
    return dict(pairs)
Exemple #11
0
 def is_running(self):
     try:
         status = sh.systemctl('is-active', 'kubelet')
     except sh.ErrorReturnCode_3:
         return False
     else:
         return status.strip().lower() == 'active'
Exemple #12
0
def absent(unit_path, name):
    changed = False

    try:
        sh.systemctl("stop", name)
        changed = True
        logger.info("Stopped")
    except sh.ErrorReturnCode:
        pass

    if os.path.exists(unit_path):
        sh.rm(unit_path)
        sh.systemctl("daemon-reload")
        changed = True
        logger.info("Removed")

    return changed
Exemple #13
0
    def configCluster(self, cluster_name, *hostnames):
        self.cluster_name = cluster_name
        self.hostnames = hostnames

        #pcs cluster 구성 command
        pcs('host', 'auth', '-u', 'hacluster', '-p', 'password', *self.hostnames)
        pcs('cluster', 'setup', self.cluster_name, *self.hostnames)
        pcs('cluster', 'start', '--all')
        systemctl('enable', '--now', 'corosync.service')
        systemctl('enable', '--now', 'pacemaker.service')
        pcs('property', 'set', 'stonith-enabled=false')

        ret_val = {'cluster name :':self.cluster_name, 'hosts': self.hostnames}
        ret = createReturn(code=200, val=ret_val)
        print(json.dumps(json.loads(ret), indent=4))

        return ret       
def systemctl_failed_units():
    """
    Returns string output of failed units list, or None if none.
    """
    command_output = repr(systemctl('list-units', '--state=failed'))
    if '0 loaded units listed' in command_output:
        return None
    else:
        return command_output
Exemple #15
0
def remove_service(
    service_name: str,
    *,
    remove_app_user: bool = True,
    get_sudo: bool = False,
    run_as: RunAsEnum = RunAsEnum.user,
) -> None:
    """

    Args:
        :param get_sudo:
        :param service_name:
        :param remove_app_user:
        :param run_as:
    """

    try:
        # get_sudo = not run_as == RunAsEnum.user
        with ContextWrapper(
                sh.contrib.sudo,
                construction_kwargs=dict(
                    password=(getpass.getpass(
                        prompt=f"[sudo] password for {getpass.getuser()}: ")
                              if get_sudo else None),
                    _with=True,
                ),
                enabled=get_sudo,
        ):
            disable_service(service_name, get_sudo=False, run_as=run_as)
            project_service_name = f"{PROJECT_NAME}_service_{service_name}"
            target_service_file_path = target_service_path(
                project_service_name, run_as=run_as)
            print(f"Removing {target_service_file_path}")

            sh.rm(target_service_file_path)
            sh.systemctl("daemon-reload")

            if run_as == RunAsEnum.app_user and remove_app_user:
                # DO CLEAN UP!
                remove_user(service_name + "_user",
                            get_sudo=False,
                            run_as=run_as)
    except sh.ErrorReturnCode_1:
        pass
Exemple #16
0
def systemctl_list():
    cmd = sh.systemctl('list-units', '-t', 'service', '--full', '--all', '--plain', '--no-legend')
    out = cmd.stdout.decode('utf-8')

    lines = out.splitlines()
    rows = [line.strip().split(maxsplit=4) for line in lines if line]

    keys = ['Id', 'LoadState', 'ActiveState', 'SubState', 'Description']
    records = [dict(zip(keys, row)) for row in rows]

    return records
Exemple #17
0
 def _get_systemctl_version():
     """Returns systemctl's version if it exists.
     """
     try:
         output = sh.systemctl('--version').split('\n')[0]
     except:
         return
     version = re.search(r'(\d+)', str(output))
     if version:
         return str(version.group())
     return None
Exemple #18
0
 def get(self):
     services = []
     service_info = systemctl('--no-legend', '--no-pager', t='service')
     for s in service_info:
         i = s.split()
         services.append(
             dict(name=i[0],
                  load=i[1],
                  active=i[2],
                  sub=i[3],
                  description=i[4]))
     return services
Exemple #19
0
 def is_installed(bg=False):
     try:
         sh.grep(
             sh.systemctl(
                 "--no-page",
                 "list-unit-files",
                 _bg=bg,
                 _piped=True),
             self.name)
         return True
     except Exception:
         return False
Exemple #20
0
 def get(self):
     services = []
     service_info = systemctl('--no-legend', '--no-pager', t='service')
     for s in service_info:
         i = s.split()
         services.append(dict(
             name=i[0],
             load=i[1],
             active=i[2],
             sub=i[3],
             description=i[4]))
     return services
Exemple #21
0
def present(unit_path, name, content):
    changed = False

    if not os.path.exists(unit_path):
        with open(unit_path, "w") as f:
            f.write(content)
            changed = True
        logger.info("Created new")
    else:
        current = sh.cat(unit_path)
        if current.strip() != content.strip():
            with open(unit_path, "w") as f:
                f.write(content)
                changed = True
            logger.info("Content changed")

    is_running = False

    try:
        sh.systemctl("is-active", name)
        is_running = True
    except sh.ErrorReturnCode:
        pass

    if changed:
        sh.systemctl("daemon-reload")

    if is_running and changed:
        logger.info("Restarting because changed and is running")
        sh.systemctl("restart", name)

    return changed
Exemple #22
0
 def do_command(bg=False):
     try:
         output = sh.systemctl(
             args, _bg=bg, _no_out=True)
         self.logger.debug(
             "SService '%s' %s" % (self.name, command))
         return output.exit_code
     except ErrorReturnCode as e:
         self.logger.debug(
             "SService '%s' %s failed" %
             (self.service, command))
         self.logger.debug(str(e))
         return e.exit_code
 def do_command(bg=False):
     try:
         output = sh.systemctl("--no-page",
                               command,
                               "{}.service".format(self.service_name),
                               _bg=bg,
                               _no_out=True)
         self._logger.info("Service '%s' %s" %
                           (self.service_name, command))
         return output.exit_code
     except ErrorReturnCode as e:
         self._logger.info("Service '%s' %s failed" %
                           (self.service_name, command))
         self._logger.debug(str(e))
         return e.exit_code
Exemple #24
0
def auto_upgrades_enabled():
    """
    Checks if auto-updates are enabled on a system.
    :return: boolean
    """
    if is_debian():  # For apt-based distros.
        import apt_pkg
        apt_pkg.init_config()
        config = apt_pkg.config
        if 'Unattended-Upgrade' in config and 'APT::Periodic' in config:
            apt_periodic = config.subtree('APT::Periodic')
            unattended_upgrade = apt_periodic.get('Unattended-Upgrade')
            update_package_lists = apt_periodic.get('Update-Package-Lists')
            allowed_origins = config.subtree('Unattended-Upgrade').value_list(
                'Allowed-Origins')  # Ubuntu
            origins_pattern = config.subtree('Unattended-Upgrade').value_list(
                'Origins-Pattern')  # Debian

            return unattended_upgrade == '1' and \
                update_package_lists == '1' and \
                (('${distro_id}:${distro_codename}' in allowed_origins
                  and '${distro_id}:${distro_codename}-security' in allowed_origins)
                 or 'origin=Debian,codename=${distro_codename},label=Debian-Security' in origins_pattern)
        return False
    elif is_amazon_linux2():  # For Amazon Linux 2.
        # 1. check if yum-cron installed
        # 2. check if it's running
        # 3. check if it has proper values in its config file
        import rpm
        try:
            from sh import systemctl
        except ImportError:
            # No systemd - probably yum-cron is not running
            # TODO: use "service" executable which also works without systemd and on older systems
            return False
        ts = rpm.ts()
        package_iterator = ts.dbMatch('name', 'yum-cron')
        if package_iterator.count() > 0:  # Package is installed.
            result = systemctl(['is-active', 'yum-cron'],
                               _ok_code=[0, 3]).stdout.decode().strip()
            if result == 'active':
                config = open('/etc/yum/yum-cron.conf').read()
                if '\ndownload_updates = yes' in config and '\napply_updates = yes' in config:
                    return True
        return False
    return None
Exemple #25
0
def items():
    items = {
        "Suspend": lambda: sh.systemctl("suspend"),
        "Shutdown":
        lambda: confirm("Shutdown?", sh.systemctl.bake("poweroff")),
        "Reboot": lambda: confirm("Reboot?", sh.systemctl.bake("reboot")),
        "Logout": lambda: confirm("Logout?", sh.wm_msg.bake("end")),
        "Lock": lambda: sh.lockscreen(),
        "Hibernate":
        lambda: confirm("Hibernate?", sh.systemctl.bake("hibernate"))
    }

    if which("lockscreen") is None:
        del items["Lock"]

    #if which("wmctl") is None: # TODO
    #    del items["Logout"]
    return items
Exemple #26
0
    def status(self, name=''):
        """Returns a list of the statuses of the `name` service, or
        if name is omitted, a list of the status of all services for this
        specific init system.

        There should be a standardization around the status fields.
        There currently isn't.

        `self.services` is set in `base.py`
        """
        super(SystemD, self).status(name=name)

        svc_list = sh.systemctl('--no-legend', '--no-pager', t='service')
        svcs_info = [self._parse_service_info(svc) for svc in svc_list]
        if name:
            names = (name, name + '.service')
            # return list of one item for specific service
            svcs_info = [s for s in svcs_info if s['name'] in names]
        self.services['services'] = svcs_info
        return self.services
def tornet(slot):
    """
    Starts/newid's tornet as needed.
    """
    # newid if service is running, enable/start if not.
    # The 1 prefix is intentional.
    tornet_port = '1{}'.format(slot)
    tornet_service = 'tornet@{}'.format(tornet_port)

    # Yuck.
    try:
        sh.systemctl('status', '--no-pager', tornet_service)
        tornet_running = True
    except sh.ErrorReturnCode_3:
        tornet_running = False

    if tornet_running is True:
        carml_path = 'unix:/run/tornet-{}/control'.format(tornet_port)
        # FIXME: We should use carml as an import, not like this.
        sh.carml('-c', carml_path, 'newid')
        return True
    else:
        # Start and enable service. FIXME: enable --now doesn't work?
        sh.systemctl('enable', tornet_service)
        sh.systemctl('start', tornet_service)

        # Wait at most, 300 seconds~ for Tor to come online.
        tries = 1
        while tries < 300:
            tries = tries + 1
            # journalctl doesn't support something like -u service -S
            # started.
            # Instead, we do the best we can and make some reasonable
            # assumptions.
            output = sh.journalctl('--no-pager', '-b', '-S', '1 minute ago',
                                   '-u', tornet_service)
            if 'Bootstrapped 100%' in output:
                return True
            else:
                sleep(1)

        raise ValueError('Tor service failed to start.')
Exemple #28
0
def vbox():
    pacman('-S', 'virtualbox-guest-modules-arch', 'virtualbox-guest-utils', _in='y')
    systemctl('enable', 'vboxservice')
Exemple #29
0
def install_service(
    service_entry_point_path: Path,
    service_name: str,
    *,
    description: str = None,
    auto_enable: bool = True,
    run_as: RunAsEnum = RunAsEnum.user,
    # get_sudo: bool = False,
    restart: RestartServiceEnum = RestartServiceEnum.on_failure,
) -> None:
    """
    Args:
        :param restart:
        :param service_entry_point_path:
        :param service_name:
        :param description:
        :param auto_enable:
        :param run_as:
    """
    assert (service_entry_point_path.is_file()
            and service_entry_point_path.name.endswith(".py"))
    project_service_name = f"{PROJECT_NAME}_service_{service_name}"
    user = getpass.getuser()

    systemd_service_file_path = target_service_path(project_service_name,
                                                    run_as=run_as)
    print(f"Installing {systemd_service_file_path}")
    get_sudo = run_as != RunAsEnum.user
    with ContextWrapper(
            sh.contrib.sudo,
            construction_kwargs=dict(
                password=(getpass.getpass(
                    prompt=f"[sudo] password for {user}: ")
                          if get_sudo else None),
                _with=True,
            ),
            enabled=get_sudo,
    ):
        if run_as == RunAsEnum.app_user:
            service_user = service_name + "_user"
            make_user(service_user, get_sudo=False)
            service_target = "default.target"
            service_group = service_user
        elif run_as == RunAsEnum.root:
            service_user = "******"
            service_target = "multi-user.target"
            service_group = service_user
        elif run_as == RunAsEnum.user:
            service_user = user
            service_target = "default.target"
            service_group = service_user
        else:
            raise ValueError

        sh.touch(systemd_service_file_path)
        group_name = str(sh.id(["-g", "-n", service_user])).strip("\n")
        assert service_group == group_name
        current_owner = sh.ls("-l", systemd_service_file_path).split(" ")[2]
        if current_owner != service_user:  # SETTING UP PERMISSIONS
            print(
                f"Changing owner of service file from {current_owner} to {service_user}"
            )
            if run_as == RunAsEnum.root:
                group_name = ""
            else:
                print(f"with common group {group_name}")
                # group_id = sh.id(["-g", service_user])
                sh.usermod(["-a", "-G", group_name,
                            user])  # TODO: Polluting groups of user
        sh.chown(
            [f"{user}:{group_name}", service_entry_point_path]
        )  # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group.
        sh.chown(
            [f"{user}:{group_name}", systemd_service_file_path]
        )  # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group.

        print("writing service file")
        if not description:
            description = f"heimdallr service for {service_name}"
        with open(systemd_service_file_path, "w") as f:
            f.writelines(
                SERVICE_TEMPLATE.format(
                    service_name=project_service_name,
                    service_user=service_user,
                    executable=sys.executable,
                    description=description,
                    service_entry_point_path=service_entry_point_path,
                    service_target=service_target,
                    service_group=service_group,
                    restart=restart.value,
                ))
        sh.chown(
            [f"{service_user}:{group_name}", systemd_service_file_path]
        )  # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group.
        sh.chmod(["664", systemd_service_file_path])
        sh.chmod(["774", service_entry_point_path])
        sh.systemctl("daemon-reload")  # TODO: Requires sudo?

        if auto_enable:
            enable_service(service_name, get_sudo=False, run_as=run_as)
Exemple #30
0
def tor_has_bootstrapped() -> bool:
    try:
        sh.systemctl("is-active", "tails-tor-has-bootstrapped.target")
        return True
    except sh.ErrorReturnCode:
        return False
def virtual_machine_destroy(machine_id):
    logging.info('Destroying {}'.format(machine_id))
    systemctl('stop', 'runqemu_start_{}.path'.format(machine_id))
    systemctl('disable', 'runqemu_start_{}.path'.format(machine_id))
    systemctl('stop', 'runqemu_stop_{}.path'.format(machine_id))
    systemctl('disable', 'runqemu_stop_{}.path'.format(machine_id))
    path = '/etc/systemd/system/runqemu_start_{}.path'.format(machine_id)
    os.remove(path)
    path = '/etc/systemd/system/runqemu_stop_{}.path'.format(machine_id)
    os.remove(path)
    runqemu_service = 'runqemu@{}'.format(machine_id)
    systemctl('stop', runqemu_service)
    systemctl('disable', runqemu_service)
    # Not disabling the tornet service anymore, at least for now.
    # If we do add this back, need to be careful to only do it when
    # the VM is in fact using tornet.
    # Another option is carml's newid feature.
    # slot = hedron.virtual_machine_info(machine_id)['slot']
    # tornet_service = 'tornet@1{}'.format(slot)
    # systemctl('stop', tornet_service)
    # systemctl('disable', tornet_service)
    directory = os.path.join('/home/vmmanagement', machine_id)
    rmtree(directory)
    # This is last for a reason.
    rmtree('/var/tmp/runqemu/{}'.format(machine_id))
    return True
Exemple #32
0
################                                      #####################
################               SYSTEMD                #####################
################                                      #####################
###########################################################################

if not vmreload:
	tr('systemd')

	for i in glob.glob(vms('systemd/*')):
		tgt = '/etc/systemd/system/%s' % os.path.basename(i)
		if os.path.exists(tgt):
			os.unlink(tgt)
		shutil.copy(i, tgt)
		if 'target' not in i:
			systemctl.enable(os.path.basename(i))
	systemctl('daemon-reload')
	tr('systemd - done')

###########################################################################
################                                      #####################
################              VM SERVICE              #####################
################                                      #####################
###########################################################################

if not vmreload:
	tr('vm service')

	shutil.copy(vms('vm_service.py'), '/sbin/')
	shutil.copy(vms('ping.py'), '/lib64/python2.7/site-packages/')

	tr('vm service - done')
Exemple #33
0
def configure_samba(upn, password, domain, reset=False):
    backup_complete = False
    smbcfgfile = '/etc/samba/smb.conf'
    # Make a backup of the Samba config file
    if not os.path.isfile(smbcfgfile):
        # If there is no existing / default smb.conf file, first create one
        #   so that we can both keep a backup and be able to restore if config fails
        create_samba_default_config(smbcfgfile + '.bak')
    else:
        shutil.copy(smbcfgfile, smbcfgfile + '.bak')
    backup_complete = True

    try:
        if not reset:
            # get AD workgroup
            workgroup = get_netbios(upn, password, domain)

            # Setup the Samba confguration file
            cfg = ConfigObj()
            cfg.filename = smbcfgfile

            cfg['global'] = {}
            cfg['global']['workgroup'] = workgroup.lower() if workgroup else ''
            cfg['global']['server string'] = 'StrongLink Samba Server'
            cfg['global']['log file'] = '/var/log/samba/log.%m'
            cfg['global']['log level'] = '3'
            cfg['global']['max log size'] = '50'
            cfg['global']['security'] = 'ads'
            cfg['global']['encrypt passwords'] = 'yes'
            cfg['global']['passdb backend'] = 'tdbsam'
            cfg['global']['kerberos method'] = 'secrets and keytab'
            cfg['global']['realm'] = domain.lower()
            cfg['global']['vfs objects'] = 'acl_xattr'
            cfg['global']['map acl inherit'] = 'yes'
            cfg['global']['store dos attributes'] = 'yes'
            cfg['global']['deadtime'] = '10'
            cfg['global']['client signing'] = 'auto'
            cfg['global']['server signing'] = 'auto'
            cfg['global']['dns proxy'] = 'no'
            cfg['global']['load printers'] = 'no'
            cfg['global']['printing'] = 'bsd'
            cfg['global']['printcap name'] = '/dev/null'
            cfg['global']['disable spoolss'] = 'yes'
            cfg['global']['map untrusted to domain'] = 'yes'

            cfg.write()
        # When removing a domain, rewrite the default StrongLink samba config
        else:
            create_samba_default_config(smbcfgfile)

        # Reload SMB
        sh.systemctl('restart','smb')

    except Exception as exc:
        # Something nasty happened when we tried to reconfigure samba
        #   so we need to restore our last backup file
        logger.error("Error configuring Samba, restoring backup config: {}".format(str(exc)))
        if backup_complete:
            shutil.copy(smbcfgfile + '.bak', smbcfgfile)
            # Reload SMB
            sh.systemctl('restart','smb')
        raise ConfigSambaException
Exemple #34
0
def configure_sssd(upn, password, domain, reset=False):
    backup_complete = False
    sssdcfgfile = '/etc/sssd/sssd.conf'

    if not os.path.isfile(sssdcfgfile):
        # Create a default sssd.conf if one does not currently exist
        logger.info("Creating default SSSD config")
        create_default_sssd_config(sssdcfgfile + '.bak')
    else:
        # Make a backup of the sssd config file
        logger.info("Backing up SSSD config")
        shutil.copy(sssdcfgfile, sssdcfgfile + '.bak')
    backup_complete = True

    try:
        # Stop SSSD and clear caches
        logger.info("Stoping sssd service and clearing caches")
        sh.systemctl('stop','sssd')
        for f in glob.glob('/var/lib/sss/db/*'):
            os.remove(f)

        if not reset:
            # get_sid
            sid = get_sid(upn, password, domain)
            logger.info("configure_sssd: Got sid: {}".format(str(sid)))
            # Edit the sssd.conf with IdMap Details
            sssdcfg = ConfigObj(sssdcfgfile)

            logger.info("Setting SSSD config for domain: {}".format(str(domain)))
            domain_key = 'domain/'+domain

            # Check to see if key passed in was correct case
            # If not, try to find a key that matches caseless

            if domain_key not in sssdcfg:
                matches = [k for k in sssdcfg if k.lower() == domain_key.lower()]
                if len(matches) > 1:
                    logger.error("Exact key match not found, but multiple similar keys: {} --- Using {}".format(str(matches), str(matches[0])))
                elif len(matches) == 1:
                    logger.info("Found good match for domain {} on sssd key {}".format(str(domain_key), str(matches[0])))
                else:
                    logger.error("Found NO good matches for domain {}".format(str(domain_key)))
                    raise Exception("No matching domain")
                domain_key = matches[0]

            sssdcfg[domain_key]['ldap_id_mapping'] = useIdMap
            if useIdMap:
                sssdcfg[domain_key]['ldap_idmap_range_min'] = 1000000
                sssdcfg[domain_key]['ldap_idmap_range_size'] = 2000000
                sssdcfg[domain_key]['ldap_idmap_default_domain_sid'] = sid
            else:
                sssdcfg[domain_key].pop('ldap_idmap_range_min', None)
                sssdcfg[domain_key].pop('ldap_idmap_range_size', None)
                sssdcfg[domain_key].pop('ldap_idmap_default_domain_sid', None)
        else:
            # Default sssd.conf would go here
            create_default_sssd_config(sssdcfgfile)

        sssdcfg.write()

        # Restart sssd
        sh.systemctl('restart', 'sssd')

    except Exception as exc:
        logger.error("Error configuring sssd, restoring backup config: {}".format(str(exc)))
        if backup_complete:
            # Something nasty happened when we tried to reconfigure sssd.conf
            #   so we need to restore our last backup file
            shutil.copy(sssdcfgfile + '.bak', sssdcfgfile)

            # Restart SSSD now that we've restored out backup
            sh.systemctl('restart', 'sssd')
        raise ConfigSSSDException
Exemple #35
0
def setup_networking(ob_num: int):
    """Sets up networking.

    Installs some debs manually that are required for configuring networking,
    since we don't yet have networking and can't apt install them. Then configures
    DNS and network interfaces, then bounces the network interfaces.
    """
    print(" === Setting up networking === ")

    # Install network management packages manually via dpkg, since we can't apt
    # install them without networking already setup.
    print("Installing dependencies for setting up networking...")
    dpkg("-i", *glob("./*.deb"))

    print("Configuring resolved...")
    # Default to the Mikrotik router for DNS, with a fallback of Google's DNS
    sed("-i", "s/^#DNS=$/DNS=172.27.31.254 8.8.8.8/g",
        "/etc/systemd/resolved.conf")
    sed("-i", "s/^#FallbackDNS=$/FallbackDNS=8.8.8.8 8.8.4.4/g",
        "/etc/systemd/resolved.conf")
    systemctl("restart", "systemd-resolved")

    # Not sure if still used, but some things might be expecting orange boxen to
    # have this configuration file.
    with open("/etc/orange-box.conf", "w") as f:
        f.writelines([f"orangebox_number={ob_num}"])

    # Disable the external ethernet port (en*) and use both of the internal
    # ones (enx*). The enx* interfaces map to vlan1 and vlan2, which in turn
    # get mapped to `172.27.{orange box #}.X` and `172.27.{orange box # + 2}.X`,
    # respectively. They are both bridged to the wireless network that the
    # orange box is connected to, hence not needing en* connected.
    print("Writing network configuration...")
    interfaces = list(
        sorted(
            Path(iface).name for iface in glob("/sys/class/net/*")
            if Path(iface).name.startswith("en")))
    internal_ips = [f"172.27.{ob_num}.1", f"172.27.{ob_num + 2}.1"]
    gateway_ips = [f"172.27.{ob_num + 1}.254", f"172.27.{ob_num + 3}.254"]
    sh.ip("addr", "flush", "dev", interfaces[1])
    sh.ifconfig(interfaces[1], f"{internal_ips[1]}/23")
    systemctl("stop", "NetworkManager")
    systemctl("disable", "NetworkManager")

    with open("/etc/network/interfaces", "w") as f:
        f.write(
            textwrap.dedent(f"""
            # These are generated by orange-box build scripts
            auto lo
            iface lo inet loopback

            auto {interfaces[0]}
            iface {interfaces[0]} inet manual

            auto {interfaces[1]}
            iface {interfaces[1]} inet manual

            auto {interfaces[2]}
            iface {interfaces[2]} inet manual

            auto br0
            iface br0 inet static
              address {internal_ips[0]}
              netmask 255.255.254.0
              gateway {gateway_ips[0]}
              dns-nameservers {internal_ips[0]} {gateway_ips[0]}
              bridge_ports {interfaces[1]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0

            auto br1
            iface br1 inet static
              address {internal_ips[1]}
              netmask 255.255.254.0
              bridge_ports {interfaces[2]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0"""))

    print("Restarting network interfaces...")
    bridges = ["br0", "br1"]

    # Take down all of the interfaces
    for iface in interfaces + bridges:
        sh.ifdown("--force", iface)

    # Bring up all interfaces except enp*
    for iface in interfaces[1:] + bridges:
        sh.ifup("--force", iface)

    print("Waiting for network to come up...")
    for _ in range(60):
        try:
            ping("-c1", "8.8.8.8")
            break
        except sh.ErrorReturnCode_1:
            print(" - Still waiting for 8.8.8.8...")
    else:
        print("Waited too long for network to come up.")
        print("Please fix the network.")
        sys.exit(1)

    print("Waiting for DNS to come up...")
    for _ in range(60):
        try:
            ping("-c1", "launchpad.net")
            break
        except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2):
            print(" - Still waiting for launchpad.net...")
    else:
        print("Waited too long for DNS to come up.")
        print("Please fix the DNS.")
        sys.exit(1)
Exemple #36
0
def sshd():
    pacman(S='openssh', _in='y')
    sed('s/#PermitRootLogin prohibit-password/PermitRootLogin yes/g', i='/etc/ssh/sshd_config')
    systemctl('enable', 'sshd')
    systemctl('start', 'sshd')
Exemple #37
0
def is_system_exists():
    try:
        sh.systemctl('--version')
        return True
    except:
        return False