示例#1
0
    def init_augeas(self):
        """ Initialize the actual Augeas instance """

        try:
            import augeas
        except ImportError:  # pragma: no cover
            raise errors.NoInstallationError("Problem in Augeas installation")

        self.aug = augeas.Augeas(
            # specify a directory to load our preferred lens from
            loadpath=constants.AUGEAS_LENS_DIR,
            # Do not save backup (we do it ourselves), do not load
            # anything by default
            flags=(augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD
                   | augeas.Augeas.ENABLE_SPAN))
示例#2
0
 def init_augeas(self):
     """ Initialize the actual Augeas instance """
     import augeas
     self.aug = augeas.Augeas(
         # specify a directory to load our preferred lens from
         loadpath=constants.AUGEAS_LENS_DIR,
         # Do not save backup (we do it ourselves), do not load
         # anything by default
         flags=(augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD
                | augeas.Augeas.ENABLE_SPAN))
     # See if any temporary changes need to be recovered
     # This needs to occur before VirtualHost objects are setup...
     # because this will change the underlying configuration and potential
     # vhosts
     self.recovery_routine()
示例#3
0
文件: util.py 项目: digicert/certbot
    def setUp(self, test_dir="debian_apache_2_4/multiple_vhosts",
              config_root="debian_apache_2_4/multiple_vhosts/apache2",
              vhost_root="debian_apache_2_4/multiple_vhosts/apache2/sites-available"):
        super(ParserTest, self).setUp(test_dir, config_root, vhost_root)

        zope.component.provideUtility(display_util.FileDisplay(sys.stdout,
                                                               False))

        from certbot_apache_win._internal.parser import ApacheParser
        self.aug = augeas.Augeas(
            flags=augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD)
        with mock.patch("certbot_apache_win._internal.parser.ApacheParser."
                        "update_runtime_variables"):
            self.parser = ApacheParser(
                self.config_path, self.vhost_path, configurator=self.config)
示例#4
0
    def test10TextRetrieve(self):
        hosts = "192.168.0.1 rtr.example.com router\n"
        a = augeas.Augeas(root=MYROOT)
        r = a.set("/raw/hosts", hosts)
        r = a.text_store("Hosts.lns", "/raw/hosts", "/t1")
        r = a.text_retrieve("Hosts.lns", "/raw/hosts", "/t1", "/out/hosts")
        hosts_out = a.get("/out/hosts")
        self.assertEqual(hosts, hosts_out)

        # Test bad lens name
        try:
            r = a.text_store("Notthere.lns", "/raw/hosts", "/t2")
        except ValueError as e:
            error = e
        self.assertTrue(isinstance(error, ValueError))
示例#5
0
 def test04Grub(self):
     "test default setting of grub entry"
     a = augeas.Augeas(root=MYROOT)
     num = 0
     for entry in a.match("/files/etc/grub.conf/title"):
         num += 1
     self.assertEqual(num, 2)
     default = int(a.get("/files/etc/grub.conf/default"))
     self.assertEqual(default, 0)
     a.set("/files/etc/grub.conf/default", str(1))
     a.save()
     default = int(a.get("/files/etc/grub.conf/default"))
     self.assertEqual(default, 1)
     a.set("/files/etc/grub.conf/default", str(0))
     a.save()
示例#6
0
def _get_home_page_url(conf_file):
    """Get the default application for the domain."""
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)
    aug.set('/augeas/load/Httpd/lens', 'Httpd.lns')
    aug.set('/augeas/load/Httpd/incl[last() + 1]', conf_file)
    aug.load()

    aug.defvar('conf', '/files' + conf_file)

    for match in aug.match('/files' + conf_file +
                           '/directive["RedirectMatch"]'):
        if aug.get(match + "/arg[1]") == '''"^/$"''':
            return aug.get(match + "/arg[2]").strip('"')

    return None
示例#7
0
    def setUp(
        self,
        test_dir="debian_apache_2_4/multiple_vhosts",
        config_root="debian_apache_2_4/multiple_vhosts/apache2",
        vhost_root="debian_apache_2_4/multiple_vhosts/apache2/sites-available"
    ):
        super().setUp(test_dir, config_root, vhost_root)

        from certbot_apache._internal.parser import ApacheParser
        self.aug = augeas.Augeas(flags=augeas.Augeas.NONE
                                 | augeas.Augeas.NO_MODL_AUTOLOAD)
        with mock.patch("certbot_apache._internal.parser.ApacheParser."
                        "update_runtime_variables"):
            self.parser = ApacheParser(self.config_path,
                                       self.vhost_path,
                                       configurator=self.config)
示例#8
0
def _write_osaport_to_cfgfile(device_id, osa_portno):
    """
    write osa port number into ifcfg file for the corresponding interface
    this method creates ifcfg file with defualt params if file doesn't exist
    Args:
        device_id: first bus id of the network triplet
        osa_portno: OSA port number
    """
    wok_log.info('In _write_osaport_to_cfgfile() method. Updating osa port'
                 ' number "%s" for device "%s"' % (osa_portno, device_id))
    ifcfg_file_path = '/' + ifcfg_path.replace('<deviceid>', device_id)
    if not os.path.isfile(ifcfg_file_path):
        wok_log.info('ifcfg file is not there for interface "%s". creating'
                     ' ifcfg file with default values and osa port numer "%s' %
                     (device_id, osa_portno))
        # if the ifcfg file doesn't exist, follow persist interface to create
        # ifcfg file and write persistence params
        return _persist_interface(device_id, osa_portno)

    ifcfg_file_pattern = ifcfg_path.replace('<deviceid>', device_id) + '/'
    wok_log.info('Update osa port number "%s" in file "%s" usaing augeas' %
                 (osa_portno, ifcfg_file_path))
    try:
        parser = augeas.Augeas('/')
        parser.load()
        wok_log.info('Get current osa port number "%s" from file "%s"' %
                     (osa_portno, ifcfg_file_path))
        optns = _form_cfg_options_attr(
            osa_portno, parser.get(ifcfg_file_pattern + OPTIONS))
        parser.set(ifcfg_file_pattern + OPTIONS, optns)
        parser.save()
        wok_log.info('Updated osa port number "%s" in file "%s"' %
                     (osa_portno, ifcfg_file_path))
    except Exception as e:
        wok_log.error('Failed to write osa port number to ifcfg file '
                      'using augeas tool. Error: %s' % e.message)
        raise OperationFailed(
            'GS390XIONW002E', {
                'device': device_id,
                'ifcfg_file_path': ifcfg_file_path,
                'error': e.message
            })
    finally:
        if parser:
            del parser
        wok_log.info('End of _write_osaport_to_cfgfile(%s, %s) method' %
                     (device_id, osa_portno))
    def __init__(self, *args, **kwargs):
        super(AugeasConfigurator, self).__init__(*args, **kwargs)

        self.aug = augeas.Augeas(
            # specify a directory to load our preferred lens from
            loadpath=constants.AUGEAS_LENS_DIR,
            # Do not save backup (we do it ourselves), do not load
            # anything by default
            flags=(augeas.Augeas.NONE | augeas.Augeas.NO_MODL_AUTOLOAD))
        self.save_notes = ""

        # See if any temporary changes need to be recovered
        # This needs to occur before VirtualHost objects are setup...
        # because this will change the underlying configuration and potential
        # vhosts
        self.reverter = reverter.Reverter(self.config)
        self.recovery_routine()
示例#10
0
    def setUp(
            self,
            test_dir="debian_apache_2_4/two_vhost_80",
            config_root="debian_apache_2_4/two_vhost_80/apache2",
            vhost_root="debian_apache_2_4/two_vhost_80/apache2/sites-available"
    ):
        super(ParserTest, self).setUp(test_dir, config_root, vhost_root)

        zope.component.provideUtility(display_util.FileDisplay(sys.stdout))

        from letsencrypt_apache.parser import ApacheParser
        self.aug = augeas.Augeas(flags=augeas.Augeas.NONE
                                 | augeas.Augeas.NO_MODL_AUTOLOAD)
        with mock.patch("letsencrypt_apache.parser.ApacheParser."
                        "update_runtime_variables"):
            self.parser = ApacheParser(self.aug, self.config_path,
                                       self.vhost_path)
示例#11
0
    def test15Copy(self):
        a = augeas.Augeas(root=MYROOT)

        orig_path = '/tmp/src/copy_test/a'
        copy_path = '/tmp/dst/copy_test/a'
        orig_value = 'test value'

        a.set(orig_path, orig_value)

        matches = a.match(orig_path)
        self.failUnless(matches)

        a.copy(orig_path, copy_path)

        matches = a.match(copy_path)
        self.failUnless(matches)
        self.assertEqual(a.get(copy_path), a.get(orig_path))
示例#12
0
def _write_ifcfg_params(interface):
    """
    method to write mandatory attributes to ifcfg file
    of corresponding network device using augeas module
    to persist it

    :param interface: network device id
    :return: None
    """
    wok_log.info('updating mandatory params to ifcfg file of '
                 'network device %s to persist it' % interface)
    configured_devices = _get_configured_devices(key=UNIQUE_COL_NAME)
    device_info = configured_devices[ENCCW + interface]
    sub_channels = ','.join(device_info['device_ids'])
    device_name = device_info['name']
    cfgmap = {
        DEVICE: device_name,
        ONBOOT: 'yes',
        SUBCHANNELS: sub_channels,
        NETTYPE: 'qeth',
        TYPE: ETHERNET
    }
    ifcfg_file_pattern = ifcfg_path.replace('<deviceid>', interface) + '/'
    ifcfg_file_path = '/' + ifcfg_path.replace('<deviceid>', interface)
    parser = None
    try:
        parser = augeas.Augeas('/')
        parser.load()
        for key, value in cfgmap.iteritems():
            path = ifcfg_file_pattern + key
            parser.set(path, value)
        parser.save()
    except Exception as e:
        wok_log.error('Failed to write device attributes to ifcfg file '
                      'using augeas tool. Error: %s' % e.message)
        raise OperationFailed(
            'GS390XIONW002E', {
                'device': interface,
                'ifcfg_file_path': ifcfg_file_path,
                'error': e.message
            })
    finally:
        if parser:
            del parser
    wok_log.info('successfully updated mandatory params in ifcfg '
                 'file of network device %s' % interface)
示例#13
0
 def test21Ns_attr(self):
     "test ns_attr, ns_label, ns_value, ns_count, ns_path"
     a = augeas.Augeas(root=MYROOT)
     a.defvar("hosts", "/files/etc/hosts/*")
     a.defvar("hosts_1", "/files/etc/hosts/1/*")
     (value, label, file_path) = a.ns_attr("hosts_1", 2)
     self.assertEqual(label, "alias")
     self.assertEqual(value, "localhost")
     self.assertEqual(file_path, "/files/etc/hosts")
     value = a.ns_value("hosts_1", 1)
     self.assertEqual(value, "localhost.localdomain")
     (label, index) = a.ns_label("hosts_1", 1)
     self.assertEqual(label, "canonical")
     self.assertEqual(index, 0)
     count = a.ns_count("hosts")
     self.assertEqual(count, 4)
     path = a.ns_path("hosts", 2)
     self.assertEqual(path, "/files/etc/hosts/1")
示例#14
0
 def test06SetMultiple(self):
     "Set multiple nodes at once"
     # Tests based on unit tests of aug_setm from augeas
     a = augeas.Augeas(root=MYROOT)
     #Change base nodes when SUB is None
     r = a.setm("/augeas/version/save/*", None, "changed")
     self.assertEquals(4, r)
     
     r = a.match("/augeas/version/save/*[. = 'changed']")
     self.assertEquals(4, len(r))
     
     # Only change existing nodes 
     r = a.setm("/augeas/version/save", "mode", "again")
     self.assertEquals(4, r)
     
     r = a.match("/augeas/version/save/*")
     self.assertEquals(4, len(r))
     
     r = a.match("/augeas/version/save/*[. = 'again']")
     self.assertEquals(4, len(r))
     
     # Create a new node 
     r = a.setm("/augeas/version/save", "mode[last() + 1]", "newmode")
     self.assertEquals(1, r)
     
     r = a.match("/augeas/version/save/*")
     self.assertEquals(5, len(r));
     
     r = a.match("/augeas/version/save/*[. = 'again']")
     self.assertEquals(4, len(r))
     
     r = a.match("/augeas/version/save/*[last()][. = 'newmode']")
     self.assertEquals(1, len(r))
     
     # Noexistent base 
     r = a.setm("/augeas/version/save[last()+1]", "mode", "newmode")
     self.assertEquals(0, r)
     
     # Invalid path expressions 
     self.assertRaises(ValueError, a.setm, "/augeas/version/save[]", "mode", "invalid")
     self.assertRaises(ValueError, a.setm, "/augeas/version/save/*", "mode[]", "invalid")
示例#15
0
def generate_apache_configuration(conf_file, domain_name):
    """Generate Diaspora's apache configuration with the given domain name"""
    open(conf_file, 'w').close()

    diaspora_domain_name = ".".join(["diaspora", domain_name])

    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)

    aug.set('/augeas/load/Httpd/lens', 'Httpd.lns')
    aug.set('/augeas/load/Httpd/incl[last() + 1]', conf_file)
    aug.load()

    aug.defvar('conf', '/files' + conf_file)

    aug.set('$conf/VirtualHost', None)
    aug.defvar('vh', '$conf/VirtualHost')
    aug.set('$vh/arg', diaspora_domain_name)
    aug.set('$vh/directive[1]', 'ServerName')
    aug.set('$vh/directive[1]/arg', diaspora_domain_name)
    aug.set('$vh/directive[2]', 'DocumentRoot')
    aug.set('$vh/directive[2]/arg', '"/var/lib/diaspora/public/"')

    aug.set('$vh/Location', None)
    aug.set('$vh/Location/arg', '"/"')
    aug.set('$vh/Location/directive[1]', 'ProxyPass')
    aug.set('$vh/Location/directive[1]/arg',
            '"unix:/var/run/diaspora/diaspora.sock|http://localhost/"')

    aug.set('$vh/Location[last() + 1]', None)
    aug.set('$vh/Location[last()]/arg', '"/assets"')
    aug.set('$vh/Location[last()]/directive[1]', 'ProxyPass')
    aug.set('$vh/Location[last()]/directive[1]/arg', '!')

    aug.set('$vh/Directory', None)
    aug.set('$vh/Directory/arg', '/var/lib/diaspora/public/')
    aug.set('$vh/Directory/directive[1]', 'Require')
    aug.set('$vh/Directory/directive[1]/arg[1]', 'all')
    aug.set('$vh/Directory/directive[1]/arg[2]', 'granted')

    aug.save()
    def __init__(self, direc=None):
        """Initialize Augeas Configurator.

        :param dict direc: location of save directories
            (used mostly for testing)

        """
        super(AugeasConfigurator, self).__init__()

        if not direc:
            direc = {
                "backup": CONFIG.BACKUP_DIR,
                "temp": CONFIG.TEMP_CHECKPOINT_DIR,
                "progress": CONFIG.IN_PROGRESS_DIR
            }

        self.direc = direc
        # TODO: this instantiation can be optimized to only load
        #       relevant files - I believe -> NO_MODL_AUTOLOAD
        # Set Augeas flags to save backup
        self.aug = augeas.Augeas(flags=augeas.Augeas.NONE)
        self.save_notes = ""
示例#17
0
def add_apt_source_line(
    uri,
    component,
    distribution,
    the_type,
    augeas_root="/",
):
    sources_dir_path = os.path.join(augeas_root, "etc/apt/sources.list.d")
    sources_file_path = os.path.join(augeas_root, "etc/apt/sources.list")
    __validate_apt_source_function_params_augeas_root__(
        augeas_root, sources_dir_path, sources_file_path)
    __validate_apt_source_function_params_type__(the_type)

    a = augeas.Augeas(root=augeas_root)
    a.set(
        "/files/etc/apt/sources.list/01/distribution", distribution
    )  # checkout http://augeas.net/tour.html if you find the 01 label for adding entries confusing (it simply is...)
    a.set("/files/etc/apt/sources.list/01/type", the_type)
    a.set("/files/etc/apt/sources.list/01/uri", uri)
    a.set("/files/etc/apt/sources.list/01/component", component)
    a.save()
    a.close()
示例#18
0
    def test08Span(self):
        "test span"
        data = [ {"expr": "/files/etc/hosts/1/ipaddr", "f": "hosts",
                  "ls": 0, "le": 0, "vs": 104, "ve": 113, "ss": 104, "se": 113},
                 {"expr": "/files/etc/hosts/1", "f": "hosts",
                  "ls": 0, "le": 0, "vs": 0, "ve": 0, "ss": 104, "se": 155},
                 {"expr": "/files/etc/hosts/*[last()]", "f": "hosts",
                  "ls": 0, "le": 0, "vs": 0, "ve": 0, "ss": 155, "se": 202},
                 {"expr": "/files/etc/hosts/#comment[2]", "f": "hosts",
                  "ls": 0, "le": 0, "vs": 58, "ve": 103, "ss": 56, "se": 104},
                 {"expr": "/files/etc/hosts", "f": "hosts",
                  "ls": 0, "le": 0, "vs": 0, "ve": 0, "ss": 0, "se":202 },
                ]
        a = augeas.Augeas(root=MYROOT, flags=augeas.Augeas.ENABLE_SPAN)
        for d in data:
            r = a.span(d["expr"])
            self.assertEquals(os.path.basename(r[0]), d["f"])
            self.assertEquals(r[1], d["ls"])
            self.assertEquals(r[2], d["le"])
            self.assertEquals(r[3], d["vs"])
            self.assertEquals(r[4], d["ve"])
            self.assertEquals(r[5], d["ss"])
            self.assertEquals(r[6], d["se"])

        error = None
        try:
            a.span("/files")
        except ValueError as e:
            error = e
        self.assertTrue(isinstance(error, ValueError))

        error = None
        try:
            a.span("/random")
        except ValueError as e:
            error = e
        self.assertTrue(isinstance(error, ValueError))

        del a
示例#19
0
def get_sudoers(admin_check=True):
    """
    method to get user and groups mentioned in /etc/sudoers file
    if admin_check is True - return users and groups with admin privilege
    if False, return users and groups is mentioned in /etc/sudoers file
    :param admin_check: True/False (to check admin/just part of sudoers file)
    :return: list of users and groups
    """
    sudoers = []
    try:
        parser = augeas.Augeas()
        parser.load()
        users = parser.match(SUDOERS_CHECK)
        # sample ouput with augeas:
        # parser.match('etc/sudoers/spec/user')
        # [u'/files/etc/sudoers/spec[1]/user',
        #  u'/files/etc/sudoers/spec[2]/user',
        #  u'/files/etc/sudoers/spec[3]/user']
        # indicates /etc/sudoers file has 3 users/groups
        for user in users:
            name = parser.get(user)
            if isinstance(name, str):
                # augeas returns in unicode format
                name = name.encode('utf-8')
            if admin_check:
                user = user.rstrip('user') + 'host_group'
                # to check for commands and host
                # parser.get('etc/sudoers/spec[1]/host_group/host')
                # u'ALL'
                # parser.get('etc/sudoers/spec[1]/host_group/command')
                # Out[35]: u'ALL'
                if 'ALL' == parser.get(user + '/command') and\
                   'ALL' == parser.get(user + '/host'):
                    sudoers.append(name)
            else:
                sudoers.append(name)
    except Exception as e:
        raise OperationFailed('GINUSER0019E', {'error': e.__str__()})
    return sudoers
示例#20
0
def _hack_to_workaround_pyaug_issues(mgmtIface, cfg, engine_data):
    """Normally we must not use the Augeas() class directly.
    Instead we interact with the /etc/default/ovirt class through
    the ovirt.node.config.defaults module and it's classes.
    However, this hack is needed to workaround the problem that
    the augeas object is cachign some values, and will flush them to disk
    occasionally.
    This can only be fixed by removing all calls to augeas
    or by a different solution.
    """
    ag = augeas.Augeas()
    ag.set("/augeas/save/copy_if_rename_fails", "")
    ag.set("/files/etc/default/ovirt/MANAGED_IFNAMES",
           "\"%s\"" % ''.join(mgmtIface).encode('utf-8'))
    ag.set("/files/etc/default/ovirt/OVIRT_MANAGEMENT_SERVER",
           "\"%s\"" % cfg["mserver"])
    ag.set("/files/etc/default/ovirt/OVIRT_MANAGEMENT_PORT",
           "\"%s\"" % cfg["mport"])

    if engine_data is not None and engine_data != "":
        ag.set("/files/etc/default/ovirt/MANAGED_BY",
               engine_data.encode('utf-8'))
    ag.save()
示例#21
0
def get_augeas():
    """Return an instance of Augeaus for processing APT configuration."""
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)
    aug.set('/augeas/load/Aptsources/lens', 'Aptsources.lns')
    aug.set('/augeas/load/Aptsources/incl[last() + 1]', '/etc/apt/sources.list')
    aug.set('/augeas/load/Aptsources/incl[last() + 1]',
            '/etc/apt/sources.list.d/*.list')
    aug.load()

    # Currently, augeas does not handle Deb822 format, it error out.
    if aug.match('/augeas/files/etc/apt/sources.list/error') or \
       aug.match('/augeas/files/etc/apt/sources.list.d//error'):
        raise Exception('Error parsing sources list')

    # Starting with Apt 1.1, /etc/apt/sources.list.d/*.sources will
    # contain files with Deb822 format.  If they are found, error out
    # for now.  XXX: Provide proper support Deb822 format with a new
    # Augeas lens.
    if glob.glob('/etc/apt/sources.list.d/*.sources'):
        raise Exception('Can not handle Deb822 source files')

    return aug
示例#22
0
class AugeasWrapper(base.Base):
    _aug = _augeas.Augeas()

    def __init__(self):
        super(AugeasWrapper, self).__init__()
        #        self._aug = _augeas.Augeas() # Is broken
        self._aug.set("/augeas/save/copy_if_rename_fails", "")

    @staticmethod
    def force_reload():
        """Needs to be called when files were changed on-disk without using Aug
        """
        AugeasWrapper._aug.load()

    def get(self, p, strip_quotes=False):
        v = self._aug.get(p)
        # v can be many types str, bool, ...
        if type(v) in [str, unicode] and strip_quotes:
            v = unicode(v).strip("'\"")
        return v

    def set(self, p, v, do_save=True):
        self._aug.set(p, v)
        if do_save:
            self.save()

    def remove(self, p, do_save=True):
        self._aug.remove(p)
        if do_save:
            self.save()

    def save(self):
        return self._aug.save()

    def match(self, p):
        return self._aug.match(p)

    def load(self):
        return self._aug.load()

    def set_many(self, new_dict, basepath=""):
        """Set's many augpaths at once

        Args:
            new_dict: A dict with a mapping (path, value)
            basepath: An optional prefix for each path of new_dict
        """
        for key, value in new_dict.items():
            path = basepath + key
            self.set(path, value)
        return self.save()

    def remove_many(self, paths, basepath=None):
        """Removes many keys at once

        Args:
            paths: The paths to be removed
            basepath: An optional prefix for each path of new_dict
        """
        for key in paths:
            path = basepath + key
            self.remove(path, False)
        return self.save()

    def get_many(self, paths, strip_basepath=""):
        """Get all values for all the paths

        Args:
            paths: Paths from which to fetch the values
            strip_basepath: Prefix to be stripped from all paths
        """
        values = {}
        for path in paths:
            if strip_basepath:
                path = path[len(strip_basepath):]
            values[path] = self.get(path)
        return values
示例#23
0
    import augeas
except ImportError:
    augeas = None
from collections import namedtuple
import ctypes
import re
import shlex
import operator

if augeas:
    # Augeas C API `aug_span` function was introduced on the begining of 2011
    # but python-augeas 0.4 was released month before and doesn't contain bindings for it
    # This code is copied from current devel branch of python-augeas

    # check whether augeas library supports span
    if augeas.Augeas(flags=getattr(augeas.Augeas, 'NO_MODL_AUTOLOAD',
                                   0)).match('/augeas/span'):
        if not hasattr(augeas.Augeas, 'span'):

            class Augeas(augeas.Augeas):

                ENABLE_SPAN = 128

                def span(self, path):
                    """Get the span according to input file of the node associated with
                    PATH. If the node is associated with a file, un tuple of 5 elements is
                    returned: (filename, label_start, label_end, value_start, value_end,
                    span_start, span_end). If the node associated with PATH doesn't
                    belong to a file or is doesn't exists, ValueError is raised."""

                    if not isinstance(path, basestring):
                        raise TypeError("path MUST be a string!")
示例#24
0
 def test01Get(self):
     "test aug_get"
     a = augeas.Augeas(root=MYROOT)
     self.failUnless(a.get("/wrong/path") == None)
     del a
import augeas
import time

from pprint import pprint
from subprocess import call

# ------------------------------------------------------------------------------
# INIT
# ------------------------------------------------------------------------------

app = Flask(__name__)
app.config.from_pyfile('data/config.cfg')


augtool = augeas.Augeas()
system = System(augtool)
presentation = Presentation()
appcenter = AppCenter(presentation, app)
services = Services(app)
screenshots = Screenshots()

# let jinja also look in the installed_app folder
template_loader = ChoiceLoader([
        app.jinja_loader,
        FileSystemLoader([app.root_path+'/templates', app.root_path+'/installed_app']),
    ])
app.jinja_loader = template_loader


# ------------------------------------------------------------------------------
示例#26
0
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import augeas
import ethtool
import os
import platform

from netaddr import IPAddress
from wok.exception import InvalidParameter, OperationFailed
from wok.utils import wok_log

parser = augeas.Augeas("/")
IFCFGPATH = 'etc/sysconfig/network-scripts/'
filenameformat = 'ifcfg-<iname>'
# cfgfile keys

BASIC_INFO = "BASIC_INFO"
NAME = 'NAME'
DEVICE = 'DEVICE'
ONBOOT = 'ONBOOT'
TYPE = 'TYPE'
MACADDR = 'MACADDR'
HWADDR = 'HWADDR'
UUID = 'UUID'
# z parameters
SUBCHANNELS = 'SUBCHANNELS'
NETTYPE = 'NETTYPE'
示例#27
0
def get_served_domains():
    """

    Augeas path for zone files:
    ===========================
    augtool> print /files/var/bind/pri/local.zone
    /files/var/bind/pri/local.zone
    /files/var/bind/pri/local.zone/$TTL = "604800"
    /files/var/bind/pri/local.zone/@[1]
    /files/var/bind/pri/local.zone/@[1]/1
    /files/var/bind/pri/local.zone/@[1]/1/class = "IN"
    /files/var/bind/pri/local.zone/@[1]/1/type = "SOA"
    /files/var/bind/pri/local.zone/@[1]/1/mname = "localhost."
    /files/var/bind/pri/local.zone/@[1]/1/rname = "root.localhost."
    /files/var/bind/pri/local.zone/@[1]/1/serial = "2"
    /files/var/bind/pri/local.zone/@[1]/1/refresh = "604800"
    /files/var/bind/pri/local.zone/@[1]/1/retry = "86400"
    /files/var/bind/pri/local.zone/@[1]/1/expiry = "2419200"
    /files/var/bind/pri/local.zone/@[1]/1/minimum = "604800"
    /files/var/bind/pri/local.zone/@[2]
    /files/var/bind/pri/local.zone/@[2]/1
    /files/var/bind/pri/local.zone/@[2]/1/class = "IN"
    /files/var/bind/pri/local.zone/@[2]/1/type = "NS"
    /files/var/bind/pri/local.zone/@[2]/1/rdata = "localhost."
    /files/var/bind/pri/local.zone/@[3]
    /files/var/bind/pri/local.zone/@[3]/1
    /files/var/bind/pri/local.zone/@[3]/1/class = "IN"
    /files/var/bind/pri/local.zone/@[3]/1/type = "A"
    /files/var/bind/pri/local.zone/@[3]/1/rdata = "127.0.0.1"
    /files/var/bind/pri/local.zone/@[4]
    /files/var/bind/pri/local.zone/@[4]/1
    /files/var/bind/pri/local.zone/@[4]/1/class = "IN"
    /files/var/bind/pri/local.zone/@[4]/1/type = "AAAA"
    /files/var/bind/pri/local.zone/@[4]/1/rdata = "::1"

    Need to find the related functionality to parse the A records

    Retrieve from /etc/bind/db* zone files all the configured A records.
    Assuming zones files in ZONES_DIR are all used.
    :return: dictionary in the form 'domain_name': ['ip_address', 'ipv6_addr']
    """
    RECORD_TYPES = ('A', 'AAAA')
    aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
                        augeas.Augeas.NO_MODL_AUTOLOAD)
    aug.set('/augeas/load/Dns_Zone/lens', 'Dns_Zone.lns')

    zone_file_path = Path(ZONES_DIR)
    zone_files = [zf for zf in zone_file_path.iterdir() if zf.is_file()]

    # augeas load only required files
    for zone_file in zone_files:
        aug.set('/augeas/load/Dns_Zone/incl[last() + 1]', str(zone_file))

    aug.load()

    served_domains = defaultdict(list)
    for zone_file in zone_files:
        base_path = '/files/%s/@[{record_order}]/1/{field}' % zone_file
        count = 1
        mname = aug.get(base_path.format(record_order=count, field='mname'))
        while True:
            record_type = aug.get(
                base_path.format(record_order=count, field='type'))

            # no record type ends the search
            if record_type is None:
                break

            if record_type in RECORD_TYPES:
                served_domains[mname].append(
                    aug.get(base_path.format(record_order=count,
                                             field='rdata')))

            count += 1

    return served_domains
示例#28
0
 def setUp(self):  # pylint: disable=arguments-differ
     super(ParserInitTest, self).setUp()
     self.aug = augeas.Augeas(flags=augeas.Augeas.NONE
                              | augeas.Augeas.NO_MODL_AUTOLOAD)
import augeas

a = augeas.Augeas(root="/")
hosts = a.match("/files/etc/hosts/*")
assert (hosts is not None)
assert (len(hosts) == 2)

assert (a.get("/files/etc/hosts/1/ipaddr") == "127.0.0.1")
assert (a.get("/files/etc/hosts/1/canonical") == "localhost")
示例#30
0
if arch == "aarch64":
	epel="arm64-epel"
elif arch == "armv7hl":
	epel="arm-epel"

run_dnf(rootdir,"clean",["all"])
run_dnf(rootdir,"update",[" "])
print ("Running dnf: group install")
run_dnf(rootdir,"groupinstall",['Minimal Install'])
if args['extra'] is not None:
	print("Installing user defined packages...")
	run_dnf(rootdir,"install",lines)
print ("Running dnf: remove")
run_dnf(rootdir,"remove",["selinux","NetworkManager","firewalld","iptables","iw*firmware*","alsa*","linux-firmware","--setopt=tsflags=noscripts","--enable centos-sclo-rh-testing"])
#I guess network manager also removes this? 
run_dnf(rootdir,"install",["dhclient","emacs","makefile"])
			    
rootpwd=crypt.crypt("centos", crypt.mksalt(crypt.METHOD_SHA512))
aug=augeas.Augeas(root=rootdir)
aug.set("/files/etc/shadow/root/password",rootpwd)
aug.set("/files/etc/sysconfig/selinux/SELINUX","disabled")
aug.save()
aug.close()
#os.makedirs(rootdir+"/etc/sysconfig/network-scripts/ifcfg-eth0")
#shutil.copy(etc+"/ifcfg-eth0",rootdir+"/etc/sysconfig/network-scripts/ifcfg-eth0")
shutil.copy(etc+"/ifcfg-eth0",rootdir+"/etc/sysconfig/network-scripts/")
if arch=="armv7hl":
    os.remove(rootdir+"/etc/yum.repos.d/CentOS-armhfp-kernel.repo")