Пример #1
0
def enable_snmpd(password):
    from ovirtnode.ovirtfunctions import ovirt_store_config

    system.service("snmpd", "stop")

    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser|awk '{print $4}'" % conf
    oldpwd, stderr = process.pipe(cmd)
    oldpwd = oldpwd.stdout.read().strip()
    process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    f = open(snmp_conf, "a")
    # create user account
    f.write("createUser root SHA %s AES\n" % password)
    f.close()
    system.service("snmpd", "start")
    # change existing password
    if len(oldpwd) > 0:
        pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
                           "SHA -A %s localhost passwd %s %s -x AES") %
                          (oldpwd, oldpwd, password))
        process.check_call(pwd_change_cmd)
        # Only reached when no excepion occurs
        process.call("rm -rf /tmp/snmpd.conf")
    ovirt_store_config(snmp_conf)
Пример #2
0
def enable_snmpd(password):
    system.service("snmpd", "stop")

    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser| grep -v '^#' | awk '{print $4}'" % conf
    oldpwd = process.pipe(cmd, shell=True).strip()

    # change existing password
    if len(oldpwd) > 0:
        system.service("snmpd", "start")
        pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
                           "SHA -A %s localhost passwd %s %s -x AES") %
                          (oldpwd, oldpwd, password))
        process.check_call(pwd_change_cmd, shell=True)
        # Only reached when no excepion occurs
        process.call(["rm", "-rf", "/tmp/snmpd.conf"])
        system.service("snmpd", "stop")

    if not any([x for x in open('/etc/snmp/snmpd.conf').readlines()
                if 'rwuser root' in x]):
        with open('/etc/snmp/snmpd.conf', 'a') as f:
            f.write("rwuser root")
    fs.Config().persist("/etc/snmp/snmpd.conf")

    cfg = fs.File(snmp_conf)
    # create user account
    cfg.write("createUser root SHA %s AES\n" % password)
    system.service("snmpd", "start")
    fs.Config().persist(snmp_conf)

    firewall.open_port(port="161", proto="udp")
Пример #3
0
            def commit(self):
                def scrub(f):
                    if Config().exists(f):
                        Config().unpersist(f)
                        # Unlinking causes problems with satellite5. Why?
                        # os.unlink(f)
                # find old SAM/Sat 6 registrations
                if Config().exists("/etc/rhsm/rhsm.conf"):
                    try:
                        process.call(["subscription-manager",
                                      "remove", "--all"])
                        process.call(["subscription-manager", "clean"])
                        Config().unpersist("/etc/rhsm/rhsm.conf")
                    except process.CalledProcessError:
                        raise RuntimeError("Couldn't remove old configuration!"
                                           " Check the output of "
                                           "subscription-manager remove --all")

                # First two are Sat5/RHN classic, last two are SAM/Sat6
                configs = ["/etc/sysconfig/rhn/systemid",
                           "/etc/sysconfig/rhn/up2date",
                           "/var/lib/rhsm/cache/installed_products.json",
                           "/var/lib/rhsm/facts/facts.json"]
                configs.extend(glob.glob("/etc/pki/consumer/*pem*"))

                [scrub(f) for f in configs]

                # Don't rely on Vars.location, since it may not be set, but we
                # should remove this regardless
                cert_path = "/etc/rhsm/ca/candlepin-local.pem"
                if os.path.exists(cert_path):
                    Config().unpersist(cert_path)
                    os.unlink(cert_path)
                Config().unpersist("/etc/cron.d/rhn-virtualization.cron")
Пример #4
0
def enable_snmpd(password):
    from ovirtnode.ovirtfunctions import ovirt_store_config

    system.service("snmpd", "stop")

    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser|awk '{print $4}'" % conf
    oldpwd, stderr = process.pipe(cmd)
    oldpwd = oldpwd.stdout.read().strip()
    process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    f = open(snmp_conf, "a")
    # create user account
    f.write("createUser root SHA %s AES\n" % password)
    f.close()
    system.service("snmpd", "start")
    # change existing password
    if len(oldpwd) > 0:
        pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
                           "SHA -A %s localhost passwd %s %s -x AES") %
                          (oldpwd, oldpwd, password))
        process.check_call(pwd_change_cmd)
        # Only reached when no excepion occurs
        process.call("rm -rf /tmp/snmpd.conf")
    ovirt_store_config(snmp_conf)
Пример #5
0
    def has_link(self):
        """Determin if L1 is up on a given interface

        Args:
            ifname: The interface to be checked
        Returns:
            True if L1 (the-link-is-up) is detected (depends on driver support)
        """

        if not self.exists():
            raise UnknownNicError("Unknown network interface: '%s'" %
                                  self.ifname)

        if is_nm_managed(self.ifname):
            try:
                device = _nm_client.get_device_by_iface(self.ifname)
                if device:
                    return device.get_carrier()
            except:
                LOGGER.debug("Failed to retrieve carrier with NM")

        # Fallback
        process.call(["ip", "link", "set", "dev", self.ifname, "up"])

        content = File("/sys/class/net/%s/carrier" % self.ifname).read()
        has_carrier = "1" in content

        return has_carrier
Пример #6
0
            def commit(self):
                def scrub(f):
                    if Config().exists(f):
                        Config().unpersist(f)
                        # Unlinking causes problems with satellite5. Why?
                        # os.unlink(f)
                # find old SAM/Sat 6 registrations
                if Config().exists("/etc/rhsm/rhsm.conf"):
                    try:
                        process.call(["subscription-manager",
                                      "remove", "--all"])
                        process.call(["subscription-manager", "clean"])
                        Config().unpersist("/etc/rhsm/rhsm.conf")
                    except process.CalledProcessError:
                        raise RuntimeError("Couldn't remove old configuration!"
                                           " Check the output of "
                                           "subscription-manager remove --all")

                # First two are Sat5/RHN classic, last two are SAM/Sat6
                configs = ["/etc/sysconfig/rhn/systemid",
                           "/etc/sysconfig/rhn/up2date",
                           "/var/lib/rhsm/cache/installed_products.json",
                           "/var/lib/rhsm/facts/facts.json"]
                configs.extend(glob.glob("/etc/pki/consumer/*pem*"))

                [scrub(f) for f in configs]

                # Don't rely on Vars.location, since it may not be set, but we
                # should remove this regardless
                cert_path = "/etc/rhsm/ca/candlepin-local.pem"
                if os.path.exists(cert_path):
                    Config().unpersist(cert_path)
                    os.unlink(cert_path)
Пример #7
0
 def change_password(oldpwd):
     system.service("snmpd", "start")
     pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv " +
                        "-a SHA -A %s localhost passwd %s %s -x AES") %
                       (oldpwd, oldpwd, password))
     process.check_call(pwd_change_cmd, shell=True)
     # Only reached when no excepion occurs
     process.call(["rm", "-rf", "/tmp/snmpd.conf"])
Пример #8
0
    def _flush():
        """Let all pending operations finish and flush anything to any disks
        E.g. iscsi etc

        pipe() is used to capture the output of the calls
        """
        # Don't litter the screen with output, so get a handle to /dev/null
        with open(os.devnull, "wb") as DEVNULL:
            process.call(["udevadm", "settle"], stdout=DEVNULL, stderr=DEVNULL)
Пример #9
0
    def _flush():
        """Let all pending operations finish and flush anything to any disks
        E.g. iscsi etc

        pipe() is used to capture the output of the calls
        """
        # Don't litter the screen with output, so get a handle to /dev/null
        with open(os.devnull, 'wb') as DEVNULL:
            process.call(["udevadm", "settle"], stdout=DEVNULL, stderr=DEVNULL)
Пример #10
0
 def commit(self):
     from ovirt.node.utils import AugeasWrapper
     aug = AugeasWrapper()
     if OVIRT_VARS["OVIRT_SSH_PWAUTH"] == "yes":
         aug.set("/files/etc/ssh/sshd_config/PasswordAuthentication", "yes")
     elif OVIRT_VARS["OVIRT_SSH_PWAUTH"] == "no":
         aug.set("/files/etc/ssh/sshd_config/PasswordAuthentication", "no")
     Config().persist("/etc/ssh/sshd_config")
     process.call("service sshd restart &> /dev/null", shell=True)
Пример #11
0
 def commit(self):
     from ovirt.node.utils import AugeasWrapper
     aug = AugeasWrapper()
     if OVIRT_VARS["OVIRT_SSH_PWAUTH"] == "yes":
         aug.set("/files/etc/ssh/sshd_config/PasswordAuthentication",
                 "yes")
     elif OVIRT_VARS["OVIRT_SSH_PWAUTH"] == "no":
         aug.set("/files/etc/ssh/sshd_config/PasswordAuthentication",
                 "no")
     Config().persist("/etc/ssh/sshd_config")
     process.call("service sshd restart &> /dev/null", shell=True)
Пример #12
0
    def _flush():
        """Let all pending operations finish and flush anything to any disks
        E.g. iscsi etc

        pipe() is used to capture the output of the calls
        """
        # Don't litter the screen with output, so get a handle to /dev/null
        with open(os.devnull, 'wb') as DEVNULL:
            process.call(["partprobe"] + [x for x in glob.glob("/dev/mapper/*")
                                          if not re.match(r'.*\/control$', x)],
                         stdout=DEVNULL, stderr=DEVNULL)
            process.call(["udevadm", "settle"], stdout=DEVNULL, stderr=DEVNULL)
Пример #13
0
def setup_firewalld(port, proto):
    port_conf = ""
    rule_dict = {"port": port, "proto": proto}

    port_conf += FIREWALLD_PORT_XML % rule_dict
    port_dict = {"port_section": port_conf}
    with open(PLUGIN_XML_OUT, "w") as f:
        f.write(FIREWALLD_XML_TEMPLATE % port_dict)

    process.call(["firewall-cmd", "--reload"])
    process.call(
        ["firewall-cmd", "--permanent", "--add-service", "node-plugin"])
    process.check_call(["firewall-cmd", "--reload"])
Пример #14
0
def copy_dir_if_not_exist(orig, target):
    """function to copy missing directories from one location to another
    should only be used when syncing a directory structure from iso
    to disk like /var/log
    use case -- upgrade adds some service which logs to /var/log/<service>
    need to have the directory created, but it's not on iso upgrade
    """
    for f in os.listdir(orig):
        if os.path.isdir("%s/%s" % (orig, f)):
            if not os.path.exists("%s/%s" % (target, f)):
                process.call("cp -av %s/%s %s &>/dev/null" % (orig, f, target), shell=True)
            else:
                copy_dir_if_not_exist("%s/%s" % (orig, f), "%s/%s" % (target, f))
Пример #15
0
def copy_dir_if_not_exist(orig, target):
    """function to copy missing directories from one location to another
    should only be used when syncing a directory structure from iso
    to disk like /var/log
    use case -- upgrade adds some service which logs to /var/log/<service>
    need to have the directory created, but it's not on iso upgrade
    """
    for f in os.listdir(orig):
        if os.path.isdir("%s/%s" % (orig, f)):
            if not os.path.exists("%s/%s" % (target, f)):
                process.call("cp -av %s/%s %s &>/dev/null" % (orig, f, target))
            else:
                copy_dir_if_not_exist("%s/%s" % (orig, f),
                                      "%s/%s" % (target, f))
Пример #16
0
    def _flush():
        """Let all pending operations finish and flush anything to any disks
        E.g. iscsi etc

        pipe() is used to capture the output of the calls
        """
        # Don't litter the screen with output, so get a handle to /dev/null
        with open(os.devnull, 'wb') as DEVNULL:
            process.call(["partprobe"] + [
                x for x in glob.glob("/dev/mapper/*")
                if not re.match(r'.*\/control$', x)
            ],
                         stdout=DEVNULL,
                         stderr=DEVNULL)
            process.call(["udevadm", "settle"], stdout=DEVNULL, stderr=DEVNULL)
Пример #17
0
def _setup_firewalld(port, proto):
    port_conf = ""
    rule_dict = {"port": port,
                 "proto": proto
                 }

    port_conf += FIREWALLD_PORT_XML % rule_dict
    port_dict = {"port_section": port_conf}
    with open(PLUGIN_XML_OUT, "w") as f:
        f.write(FIREWALLD_XML_TEMPLATE % port_dict)

    process.call(["firewall-cmd", "--reload"])
    process.call(["firewall-cmd", "--permanent", "--add-service",
                  "node-plugin"])
    process.check_call(["firewall-cmd", "--reload"])
def run(args):
    # Instead of checking for an exception, return the actual return code
    # from ovirt-hosted-engine-setup in case we decide to check for some
    # real value on it in the future

    rc = process.call(["ovirt-hosted-engine-setup"] + args)
    if rc != 0:
        print("Something went wrong setting up hosted engine, or the "
              "setup process was cancelled.\n\nPress any key to continue...")
        getch()
    sys.exit(rc)
Пример #19
0
            def _remove_devices(self):
                process.call(["killall", "dhclient"])

                vlans = utils.network.Vlans()
                vifs = vlans.all_vlan_devices()
                self.logger.debug("Attempting to delete all vlans: %s" % vifs)
                for vifname in vifs:
                    vlans.delete(vifname)
                    if NicConfig(vifname).exists():
                        NicConfig(vifname).delete()

                # FIXME we are removing ALL bridges
                bridges = Bridges()
                for bifname in bridges.ifnames():
                    bridges.delete(bifname)
                    if NicConfig(bifname).exists():
                        NicConfig(bifname).delete()

                bonds = Bonds()
                bonds.delete_all()
def run(args):
    # Instead of checking for an exception, return the actual return code
    # from ovirt-hosted-engine-setup in case we decide to check for some
    # real value on it in the future

    rc = process.call(["ovirt-hosted-engine-setup"] + args)
    if rc != 0:
        print("Something went wrong setting up hosted engine, or the "
              "setup process was cancelled.\n\nPress any key to continue...")
        getch()
    sys.exit(rc)
Пример #21
0
def enable_snmpd(password):
    system.service("snmpd", "stop")

    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser| grep -v '^#' | awk '{print $4}'" % conf
    oldpwd = process.pipe(cmd, shell=True).strip()

    process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf, shell=True)
    f = open(snmp_conf, "a")
    # create user account
    f.write("createUser root SHA %s AES\n" % password)
    f.close()

    # change existing password
    if len(oldpwd) > 0:
        system.service("snmpd", "start")
        pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
                           "SHA -A %s localhost passwd %s %s -x AES") %
                          (oldpwd, oldpwd, password))
        process.check_call(pwd_change_cmd, shell=True)
        # Only reached when no excepion occurs
        process.call(["rm", "-rf", "/tmp/snmpd.conf"])
        system.service("snmpd", "stop")
    fs.Config().persist(snmp_conf)

    if not any([
            x for x in open('/etc/snmp/snmpd.conf').readlines()
            if 'rwuser root' in x
    ]):
        with open('/etc/snmp/snmpd.conf', 'a') as f:
            f.write("rwuser root")
    fs.Config().persist("/etc/snmp/snmpd.conf")

    system.service("snmpd", "start")
Пример #22
0
 def delete(self, ifname):
     if not self.is_bridge(ifname):
         raise RuntimeError("Can no delete '%s', is no bridge" % ifname)
     process.call("ifconfig %s down" % ifname)
     process.call("ip link delete %s type bridge" % ifname)
Пример #23
0
def poweroff():
    """Poweroff the system
    """
    process.call("poweroff")
Пример #24
0
def reboot():
    """Reboot the system
    """
    process.call("reboot")
Пример #25
0
 def delete(self, ifname):
     if not self.is_bridge(ifname):
         raise RuntimeError("Can no delete '%s', is no bridge" % ifname)
     process.call(["ip", "link", "set", "dev", ifname, "down"])
     process.call(["brctl", "delbr", ifname])
Пример #26
0
 def delete(self, ifname):
     if not self.is_vlan_device(ifname):
         raise RuntimeError("Can no delete '%s', is no vlan device" %
                            ifname)
     process.call(["ip", "link", "del", ifname])
Пример #27
0
def reset():
    process.call(["reset"])
Пример #28
0
def poweroff():
    """Poweroff the system
    """
    process.call("poweroff")
Пример #29
0
def reboot():
    """Reboot the system
    """
    process.call("reboot")
Пример #30
0
 def delete(self, ifname):
     if not self.is_bridge(ifname):
         raise RuntimeError("Can no delete '%s', is no bridge" % ifname)
     process.call("ifconfig %s down" % ifname)
     process.call("ip link delete %s type bridge" % ifname)
Пример #31
0
 def delete_all(self):
     """Deletes all bond devices
     """
     process.call(["rmmod", "bonding"], shell=False)
Пример #32
0
 def delete(self, ifname):
     if not self.is_vlan_device(ifname):
         raise RuntimeError("Can no delete '%s', is no vlan device" %
                            ifname)
     process.call(["vconfig", "rem", ifname])
Пример #33
0
 def delete(self, ifname):
     if not self.is_vlan_device(ifname):
         raise RuntimeError("Can no delete '%s', is no vlan device" %
                            ifname)
     process.call(["vconfig", "rem", ifname])
Пример #34
0
 def delete(self, ifname):
     if not self.is_bridge(ifname):
         raise RuntimeError("Can no delete '%s', is no bridge" % ifname)
     process.call(["ip", "link", "set", "dev", ifname, "down"])
     process.call(["brctl", "delbr", ifname])
Пример #35
0
            def commit(self):
                cfg = RHN().retrieve()
                self.logger.debug(cfg)
                rhntype = cfg["rhntype"]
                serverurl = cfg["url"]
                cacert = cfg["ca_cert"]
                activationkey = cfg["activationkey"]
                username = cfg["username"]
                profilename = cfg["profile"]
                proxy = cfg["proxy"]
                proxyuser = cfg["proxyuser"]

                # novirtinfo: rhn-virtualization daemon refreshes virtinfo
                extra_args = ['--novirtinfo', '--norhnsd', '--nopackages',
                              '--force']
                args = ['/usr/sbin/rhnreg_ks']
                if rhntype == "rhn":
                    sys.path.append("/usr/share/rhn/up2date_client")
                    import rhnreg
                    rhnreg.cfg.set("serverURL", RHN_XMLRPC_ADDR)
                    rhnreg.cfg.set("sslCACert", RHN_SSL_CERT)
                    rhnreg.cfg.save()
                    self.logger.info("ran update")
                if serverurl:
                    cacert = cacert if cacert is not None else serverurl + \
                        "/pub/RHN-ORG-TRUSTED-SSL-CERT"
                    if not serverurl.endswith("/XMLRPC"):
                        serverurl = serverurl + "/XMLRPC"
                    args.append('--serverUrl')
                    args.append(serverurl)
                    location = "/etc/sysconfig/rhn/%s" % \
                               os.path.basename(cacert)
                    if cacert:
                        if not os.path.exists(cacert):
                            self.logger.info("Downloading CA cert.....")
                            self.logger.debug("From: %s To: %s" %
                                              (cacert, location))
                            RHN().retrieveCert(cacert, location)
                        if os.path.isfile(location):
                            if os.stat(location).st_size > 0:
                                args.append('--sslCACert')
                                args.append(location)
                                Config().persist(location)
                            else:
                                raise RuntimeError("Error Downloading \
                                                   CA cert!")
                if activationkey:
                    args.append('--activationkey')
                    args.append(activationkey)
                elif username:
                    args.append('--username')
                    args.append(username)
                    if password:
                        args.append('--password')
                        args.append(password)
                else:
                    # skip RHN registration when neither activationkey
                    # nor username/password is supplied
                    self.logger.debug("No activationkey or "
                                      "username+password given")
                    return

                if profilename:
                    args.append('--profilename')
                    args.append(profilename)

                if proxy:
                    args.append('--proxy')
                    args.append(proxy)
                    if proxyuser:
                        args.append('--proxyUser')
                        args.append(proxyuser)
                        if proxypass:
                            args.append('--proxyPassword')
                            args.append(proxypass)
                args.extend(extra_args)

                self.logger.info("Registering to RHN account.....")
                conf = Config()
                conf.unpersist("/etc/sysconfig/rhn/systemid")
                conf.unpersist("/etc/sysconfig/rhn/up2date")
                logged_args = list(args)
                remove_values_from_args = ["--password", "--proxyPassword"]
                for idx, arg in enumerate(logged_args):
                    if arg in remove_values_from_args:
                        logged_args[idx+1] = "XXXXXXX"
                logged_args = str(logged_args)
                self.logger.debug(logged_args)
                try:
                    subprocess.check_call(args)
                    conf.persist("/etc/sysconfig/rhn/up2date")
                    conf.persist("/etc/sysconfig/rhn/systemid")
                    self.logger.info("System %s sucessfully registered to %s" %
                                     (profilename, serverurl))
                    # sync profile if reregistering, fixes problem with
                    # virt guests not showing
                    sys.path.append("/usr/share/rhn")
                    from virtualization import support
                    support.refresh(True)
                    # find old SAM/Sat 6 registrations
                    if Config().exists("/etc/rhsm/rhsm.conf"):
                        process.call(["subscription-manager",
                                      "remove", "--all"])
                        process.call(["subscription-manager", "clean"])
                        Config().unpersist("/etc/rhsm/rhsm.conf")
                except:
                    self.logger.exception("Failed to call: %s" % logged_args)
                    raise RuntimeError("Error registering to RHN account")
Пример #36
0
def reset():
    process.call(["reset"])
Пример #37
0
 def delete_all(self):
     """Deletes all bond devices
     """
     process.call(["rmmod", "bonding"], shell=False)