Ejemplo n.º 1
0
def _get_distro():
    try:
        distro_info = lsb_release.get_distro_information(True)
    except:
        distro_info = lsb_release.get_distro_information()
    distro_id = distro_info['ID']
    LOG.debug("get_distro: '%s'", distro_id)
    # start with a import, this gives us only a softwarecenter module
    module = __import__(distro_id, globals(), locals(), [], -1)
    # get the right class and instanciate it
    distro_class = getattr(module, distro_id)
    instance = distro_class()
    return instance
Ejemplo n.º 2
0
def install_dependencies():
    """
    Installs package dependencies for the supported distros.
    + focal
    + bionic
    :return:
    """
    if 'focal' == lsb_release.get_distro_information()['CODENAME']:
        _install_dependencies_focal()
    elif 'bionic' == lsb_release.get_distro_information()['CODENAME']:
        _install_dependencies_bionic()
    else:
        raise RuntimeError(
            f"No valid series found to install package dependencies for")
def get_codename_to_test():
    try:
        import distro
        if distro.id() == 'ubuntu-core':
            codename = 'focal'
            if distro.version() == '18':
                codename = 'bionic'
            elif distro.version() == '16':
                codename = 'xenial'
            return codename
        return distro.codename().split()[0].lower()
    except (ImportError, CalledProcessError):
        import lsb_release
        lsb_release.get_distro_information()["CODENAME"]
Ejemplo n.º 4
0
 def get_codename(self):
     """ The codename of the distro, e.g. lucid """
     # for tests and similar
     if "SOFTWARE_CENTER_DISTRO_CODENAME" in os.environ:
         distrocode = os.environ["SOFTWARE_CENTER_DISTRO_CODENAME"]
         LOG.warn("overriding distro codename to '%s'" % distrocode)
         return distrocode
     # normal behavior
     if not hasattr(self, "_distro_code_name"):
         try:
             distro_info = lsb_release.get_distro_information(True)
         except:
             distro_info = lsb_release.get_distro_information()
         self._distro_code_name = distro_info['CODENAME']
     return self._distro_code_name
Ejemplo n.º 5
0
def install_packages():
    """Install all packages listed in requirements.txt."""
    system_option = ''
    try:
        import lsb_release
        if lsb_release.get_distro_information()['ID'] in [
                'Raspbian', 'Debian'
        ]:
            system_option = '--system'
    except ImportError:
        pass

    cmd = ('{} -m pip install {} --install-option="--prefix=" -t lib '
           '-r requirements.txt --no-binary pymysensors,paho-mqtt, pyserial'.
           format(sys.executable, system_option))

    try:
        subprocess.check_call(cmd,
                              stderr=subprocess.STDOUT,
                              shell=True,
                              cwd=_BASE_DIR)
        return True
    except subprocess.CalledProcessError as e:
        print(e)
        return False
Ejemplo n.º 6
0
 def __init__(self):
     super(Settings, self).__init__()
     self.directory = ".resetter-cli/data"
     self.os_info = lsb_release.get_distro_information()
     self.euid = os.geteuid()
     self.detectRoot()
     self.manifests = '/usr/lib/resetter/data/manifests'
     self.userlists = '/usr/lib/resetter/data/userlists'
     if 'PKEXEC_UID' in os.environ:
         self.user = pwd.getpwuid(int(os.environ['PKEXEC_UID'])).pw_name
         working_dir = '/home/{}'.format(self.user)
         os.chdir(working_dir)
         print('Welcome {}'.format(self.user))
     elif self.euid == 0 and 'PKEXEC_UID' not in os.environ:
         self.user = os.environ['SUDO_USER']
         print('Welcome {}'.format(self.user))
     else:
         self.user = os.environ.get('USERNAME')
         print('Welcome {}\n'.format(self.user))
     self.createDirs()
     if os.path.isdir(self.directory):
         os.chdir(self.directory)
     else:
         print("ERROR: {} has not been created".format(self.directory))
     print(self.detectOS())
     self.manifest = ("{}/{}").format(self.manifests, self.detectOS()[0])
     self.userlist = ("{}/{}").format(self.userlists, self.detectOS()[1])
     self.window_title = self.detectOS()[2]
     self.filesExist(self.manifest, self.userlist)
     if os.path.exists(self.manifest):
         print('Using: {}\n'.format(self.manifest))
Ejemplo n.º 7
0
 def __init__(self):
     super(Settings, self).__init__()
     self.directory = '.resetter/data'
     self.os_info = lsb_release.get_distro_information()
     self.euid = os.geteuid()
     self.version = UsefulTools().getVersion()
     self.checkForUpdate()
     self.detectRoot()
     logdir = '/var/log/resetter'
     if not os.path.exists(logdir):
         os.makedirs(logdir)
     self.logger = logging.getLogger(__name__)
     self.logger.setLevel(logging.DEBUG)
     handler = logging.FileHandler('/var/log/resetter/resetter.log')
     handler.setLevel(logging.DEBUG)
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
     handler.setFormatter(formatter)
     self.logger.addHandler(handler)
     self.manifests = '/usr/lib/resetter/data/manifests'
     self.userlists = '/usr/lib/resetter/data/userlists'
     if 'PKEXEC_UID' in os.environ:
         self.user = pwd.getpwuid(int(os.environ['PKEXEC_UID'])).pw_name
         working_dir = '/home/{}'.format(self.user)
         os.chdir(working_dir)
     elif self.euid == 0 and 'PKEXEC_UID' not in os.environ:
         self.user = os.environ['SUDO_USER']
     self.createDirs()
     os.chdir(self.directory)
     self.desktop_environment = self.detectDesktopEnviron()
     self.manifest = 'manifests/{}'.format(self.detectOS()[0])
     self.userlist = 'userlists/{}'.format(self.detectOS()[1])
     self.window_title = self.detectOS()[2]
     self.filesExist(self.manifest, self.userlist)
Ejemplo n.º 8
0
    def __init__(self):
        super(Settings, self).__init__()
        self.directory = '.resetter/data'
        self.os_info = lsb_release.get_distro_information()
        self.euid = os.geteuid()
        self.version = UsefulTools().getVersion()
        self.checkForUpdate()
        self.detectRoot()
        logdir = '/var/log/resetter'
        if not os.path.exists(logdir):
            os.makedirs(logdir)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('/var/log/resetter/resetter.log')
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.manifests = '/usr/lib/resetter/data/manifests'
        self.userlists = '/usr/lib/resetter/data/userlists'
        if 'PKEXEC_UID' in os.environ:
            self.user = pwd.getpwuid(int(os.environ['PKEXEC_UID'])).pw_name
            working_dir = '/home/{}'.format(self.user)
            os.chdir(working_dir)
        elif self.euid == 0 and 'PKEXEC_UID' not in os.environ:
            self.user = os.environ['SUDO_USER']
        self.createDirs()
        os.chdir(self.directory)

        self.manifest = ("manifests/{}").format(self.detectOS()[0])
        self.userlist = ("userlists/{}").format(self.detectOS()[1])
        self.window_title = self.detectOS()[2]
        self.filesExist(self.manifest, self.userlist)
Ejemplo n.º 9
0
 def check_ubuntu_ros(self):
     data = {'indigo': ['13.10', '14.04'],
             'jade': ['14.04', '14.10', '15.04']}
     release = lsb_release.get_distro_information()['RELEASE']
     if release in data[self.select_ros_version.get()]:
         return True
     return False
Ejemplo n.º 10
0
def process_conf_file(original, new, uuid, number, recovery_text=''):
    """Replaces all instances of a partition, OS, and extra in a conf type file
       Generally used for things that need to touch grub"""
    if not os.path.isdir(os.path.split(new)[0]):
        os.makedirs(os.path.split(new)[0])
    import lsb_release
    release = lsb_release.get_distro_information()

    #starting with 10.10, we replace the whole drive string (/dev/sdX,gptY)
    #earlier releases are hardcoded to (hd0,Y)
    if float(release["RELEASE"]) >= 10.10:
        number = 'gpt' + number

    with open(original, "r") as base:
        with open(new, 'w', encoding='utf-8') as output:
            for line in base.readlines():
                if "#RECOVERY_TEXT#" in line:
                    line = line.replace("#RECOVERY_TEXT#", recovery_text)
                if "#UUID#" in line:
                    line = line.replace("#UUID#", uuid)
                if "#PARTITION#" in line:
                    line = line.replace("#PARTITION#", number)
                if "#OS#" in line:
                    line = line.replace("#OS#", "%s %s" % (release["ID"], release["RELEASE"]))
                output.write(line)
Ejemplo n.º 11
0
def get_lsb_release():
    ret_dict = {}
    try:
        import lsb_release
        ret_dict = lsb_release.get_distro_information()
    except ImportError:
        # Couldn't import lsb_release so try the lsb-release file
        try:
            with open("/etc/lsb-release") as lsb_file:
                lsb_reader = csv.reader(lsb_file, delimiter='=', quotechar='"')
                for row in lsb_reader:
                    key = row[0].lstrip('DISTRIB_')
                    ret_dict[key] = row[1]
        except IOError:
            # Couldn't read /etc/lsb-release so try lsb_release -a
            str_map = {'Distributor ID': 'ID',
                       'Description': 'DESCRIPTION',
                       'Release': 'RELEASE',
                       'Codename': 'CODENAME'}
            output = run_command(['lsb_release', '-a'])
            for line in output.split('\n'):
                match = re.match('^([^:]*):\t*(.*)$', line)
                if match and match.group(1) in str_map:
                    key = str_map[match.group(1)]
                    ret_dict[key] = match.group(2)
    if not ret_dict:
        ret_dict = {'error': "Couldn't get LSB information"}
    return ret_dict
Ejemplo n.º 12
0
def main():

    for d in requiredDirs:
        makeDir(d)

    def handleLinkPair(sourceName, linkName):
        printInfo("Creating link: " + linkName)
        removeFile(linkName)
        createLink(sourceName, linkName)

    for pair in linkPairs:
        handleLinkPair(pair[0], pair[1])

    # TODO: remove this once not using 16.04 anymore.
    deprecatedXenialPairs = [
        (os.path.join(scriptDir, 'konsole-stuff', 'config-16.04', 'konsolerc'),
         os.path.join(homeDir, '.kde', 'share', 'config', 'konsolerc')),

        (os.path.join(scriptDir, 'konsole-stuff', 'apps-16.04', 'konsole'),
         os.path.join(homeDir, '.kde', 'share', 'apps', 'konsole')),
    ]
    if lsb_release.get_distro_information()['CODENAME'] == 'xenial':
        for pair in deprecatedXenialPairs:
            handleLinkPair(pair[0], pair[1])

    return 0
Ejemplo n.º 13
0
 def _write_state_installed_pkgs(self, sourcedir, tar):
     cache = self._cache_cls(rootdir=sourcedir)
     s = ""
     foreign = ""
     distro_id = lsb_release.get_distro_information()['ID']
     for pkg in cache:
         if pkg.is_installed:
             # a version identifies the pacakge
             s += "%s %s %s\n" % (pkg.name, pkg.installed.version,
                                  int(pkg.is_auto_installed))
             if not pkg.candidate or not pkg.candidate.downloadable:
                 self.not_downloadable.add(pkg.name)
             elif not (pkg.installed.downloadable
                       and pkg.candidate.downloadable):
                 self.version_mismatch.add(pkg.name)
             for o in pkg.installed.origins:
                 if o.archive == "now" and o.origin == "":
                     continue
                 if o.origin != distro_id:
                     foreign += "%s %s %s\n" % (
                         pkg.name, pkg.installed.version,
                         o.origin if o.origin != "" else "unknown")
                 break
     # store the installed.pkgs
     tarinfo = tarfile.TarInfo("./var/lib/apt-clone/installed.pkgs")
     s = s.encode('utf-8')
     tarinfo.size = len(s)
     tarinfo.mtime = time.time()
     tar.addfile(tarinfo, BytesIO(s))
     # store the foreign packages
     tarinfo = tarfile.TarInfo("./var/lib/apt-clone/foreign.pkgs")
     foreign = foreign.encode('utf-8')
     tarinfo.size = len(foreign)
     tarinfo.mtime = time.time()
     tar.addfile(tarinfo, BytesIO(foreign))
Ejemplo n.º 14
0
def main():

    if not chef_is_configured():
        return

    import gi
    gi.require_version('Gtk', '3.0')
    gi.require_version('WebKit', '3.0')
    from gi.repository import Gtk
    from gecosfirstlogin_lib.FirstartEntry import FirstartEntry
    from assistant.FirstartWindow import FirstartWindow
    import os
    if lsb_release.get_distro_information()['DESCRIPTION'] == 'Gecos V2 Lite':
        time.sleep(3)
    entry = FirstartEntry()
    if entry.get_firstart() == True:
        return

    try:
        entry.set_firstart(1)
        entry.remove_flag()
        w = FirstartWindow()
        w.show()
        thread = DbusThread(w)
        thread.daemon = True
        thread.start()
        while thread.isAlive():
            time.sleep(0.09)
            while Gtk.events_pending():
                Gtk.main_iteration()
        Gtk.main()
    except Exception as e:
        fp = open("/tmp/gecos-first-login.err", "w")
        fp.write(str(e))
        fp.close()
def process_conf_file(original,
                      new,
                      uuid,
                      number,
                      recovery_text='',
                      recovery_type='hdd'):
    """Replaces all instances of a partition, OS, and extra in a conf type file
       Generally used for things that need to touch grub"""
    if not os.path.isdir(os.path.split(new)[0]):
        os.makedirs(os.path.split(new)[0])
    import lsb_release
    release = lsb_release.get_distro_information()

    #we use the whole drive string (/dev/sdX,gptY)
    number = 'gpt' + number

    with open(original, "r") as base:
        with open(new, 'w', encoding='utf-8') as output:
            for line in base.readlines():
                if "#RECOVERY_TEXT#" in line:
                    line = line.replace("#RECOVERY_TEXT#", recovery_text)
                if "#UUID#" in line:
                    line = line.replace("#UUID#", uuid)
                if "#PARTITION#" in line:
                    line = line.replace("#PARTITION#", number)
                if "#OS#" in line:
                    line = line.replace(
                        "#OS#", "%s %s" % (release["ID"], release["RELEASE"]))
                if "#REC_TYPE#" in line:
                    line = line.replace("#REC_TYPE#", recovery_type)
                output.write(line)
Ejemplo n.º 16
0
def main():

    if not chef_is_configured():
        return

    from gi.repository import Gtk
    from firstart_lib.FirstartEntry import FirstartEntry
    from assistant.FirstartWindow import FirstartWindow
    import os
    if lsb_release.get_distro_information()['DESCRIPTION'] == 'Gecos V2 Lite':
        time.sleep(3)
    entry = FirstartEntry()
    if entry.get_firstart() == True:
        return
    
    try:
        entry.set_firstart(1)
        entry.remove_flag()
        w = FirstartWindow()
        w.show()
        thread = DbusThread(w)
        thread.daemon = True
        thread.start()
        while thread.isAlive():
            time.sleep(0.09)
            while Gtk.events_pending():
                Gtk.main_iteration()
        Gtk.main()
    except Exception as e:
        fp = open("/tmp/gecos-first-login.err", "w")
        fp.write(str(e))
        fp.close()
    def __init__(self):

        self.distro = lsb_release.get_distro_information()
        self.host_addr = self.host_bt_address()
        self.paired_dir = self.get_paired_dir()
        self.old_paired_set = self.get_paired_set()
        self.new_paired_addr = set()
Ejemplo n.º 18
0
def log_startup_info():
    global _pre_log_buffer
    if len(_pre_log_buffer) > 0:
        _log.info('early startup log buffer:')
    for line in _pre_log_buffer:
        _log.info(' ' + line)
    del _pre_log_buffer
    _log.info('GNUmed client version [%s] on branch [%s]',
              current_client_version, current_client_branch)
    _log.info('Platform: %s', platform.uname())
    _log.info(('Python %s on %s (%s)' %
               (sys.version, sys.platform, os.name)).replace('\n', '<\\n>'))
    try:
        import lsb_release
        _log.info('lsb_release: %s', lsb_release.get_distro_information())
    except ImportError:
        pass
    _log.info('threading: %s', sys.thread_info)
    _log.info('os.getcwd(): [%s]', os.getcwd())
    _log.info('process environment:')
    for key, val in os.environ.items():
        _log.info(' %s: %s' % (('${%s}' % key).rjust(30), val))
    import sysconfig
    _log.info('sysconfig - platform [%s] python version [%s]:',
              sysconfig.get_platform(), sysconfig.get_python_version())
    paths = sysconfig.get_paths()
    for path in paths:
        _log.info(' %s: %s', path.rjust(30), paths[path])
    conf_vars = sysconfig.get_config_vars()
    for var in conf_vars:
        _log.info(' %s: %s', var.rjust(40), conf_vars[var])
Ejemplo n.º 19
0
 def _getOSVersionAndRelease():
     dist_info = lsb_release.get_distro_information()
     os_name = dist_info['ID']
     os_version = 'n/a'
     if 'CODENAME' in dist_info:
         os_version = dist_info['CODENAME']
     os_release = dist_info['RELEASE']
     return os_name, os_version, os_release
Ejemplo n.º 20
0
def write_source_list(server, file):
    if not "ubuntu" in lsb_release.get_distro_information()["ID"].lower():
        print("Non Ubuntu detected.")
        return False
    codename = lsb_release.get_distro_information()["CODENAME"]
    content = "deb " + server + "/ros/ubuntu " + codename + " main"

    try:
        if not os.path.exists(file) or not content in open(file).read():
            with open(file, "w+") as f:
                f.write(content)
                print("{file} written successfully.".format(file=file))
        else:
            print("Mirror already in {file}".format(file=file))
    except IOError as e:
        print("Sorry, unable to write file [{err}]".format(err=str(e)))
    return True
Ejemplo n.º 21
0
def getUbuntu():
    import lsb_release
    release = lsb_release.get_distro_information()['RELEASE']
    if release.startswith("14"):
        return Ubuntu()
    elif release.startswith('16'):
        return UbuntuSystemd()
    raise NotImplemented("Ubuntu version %s is not supported" % release)
Ejemplo n.º 22
0
 def _getOSVersionAndRelease():
     dist_info = lsb_release.get_distro_information()
     os_name = dist_info["ID"]
     os_version = "n/a"
     if "CODENAME" in dist_info:
         os_version = dist_info["CODENAME"]
     os_release = dist_info["RELEASE"]
     return os_name, os_version, os_release
Ejemplo n.º 23
0
def getUbuntu():
    import lsb_release
    release = lsb_release.get_distro_information()['RELEASE']
    if release.startswith("14"):
        return Ubuntu()
    elif release.startswith('16'):
        return UbuntuSystemd()
    raise NotImplemented("Ubuntu version %s is not supported" % release)
Ejemplo n.º 24
0
 def __init__(self, image=None, timeout=500, debug_file=None):
     self.image = image
     self.timeout = timeout
     self.debug_file = debug_file
     self.arch = check_output(['dpkg', '--print-architecture'],
                              universal_newlines=True).strip()
     self.qemu_config = QEMU_ARCH_CONFIG[self.arch]
     self.release = lsb_release.get_distro_information()["CODENAME"]
Ejemplo n.º 25
0
    def _getPlatform(self):

        '''Discovers the platform'''
        _platform = None

        if sys.platform.startswith("linux"):

            import lsb_release
            info = lsb_release.get_distro_information()['ID'].lower()

            bits = _useELFtrick("/sbin/init")
            
            if bits == 32:
                if info == 'ubuntu':
                    _platform = "ubuntu32"
                elif info == 'linuxmint':
                    _platform = "mint32"
                else:
                    _platform = "linux32"
            elif bits == 64 or bits==0:  #@todo does not work in python 3 anymore
                if info == 'ubuntu':
                    _platform = "ubuntu64"
                elif info == 'linuxmint':
                    _platform = "mint64"
                else:
                    _platform = "linux64"
            else:
                raise RuntimeError("dont find which nr bits in platform")
            
            # if os.path.exists("/proc/vmware"):
            #     _platform = PlatformType.ESX

        # elif sys.platform.startswith("sunos"):
        #     import commands
        #     _, bits = commands.getstatusoutput('isainfo -b')
        #     bits = int(bits)
        #     if bits == 32:
        #         _platform = PlatformType.SOLARIS32
        #     elif bits == 64:
        #         _platform = PlatformType.SOLARIS64
        #     else:
        #         _platform = PlatformType.UNKNOWN

        elif sys.platform.startswith("win"):
            _platform = "win64"

        elif sys.platform.startswith("cygwin"):
            _platform = "cygwin"

        elif sys.platform.startswith("darwin"):
            _platform = "darwin"

        else:
            raise RuntimeError("can't establish platform name")



        return _platform        
Ejemplo n.º 26
0
 def getVersion(self):
     """
     returns codename,descr,id,release
     known ids" raring, linuxmint
     """
     self.check()
     import lsb_release
     result=lsb_release.get_distro_information()        
     return result["CODENAME"].lower().strip(),result["DESCRIPTION"],result["ID"].lower().strip(),result["RELEASE"],
Ejemplo n.º 27
0
    def __init__(self, parent=None):
        super(EasyPPAInstall, self).__init__(parent)
        self.setWindowTitle("Easy PPA Install")
        self.searchEditText = QtGui.QLineEdit()
        self.searchEditText.setPlaceholderText("Search for applications")
        self.searchEditText.setMaximumWidth(200)
        self.searchbutton = QtGui.QPushButton()
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.closebutton = QtGui.QPushButton()
        self.closebutton = QtGui.QPushButton()
        self.closebutton.setText('Close')
        self.closebutton.setMaximumWidth(150)
        self.closebutton.clicked.connect(self.close)
        self.searchbutton.setText("Search")
        self.searchbutton.setMaximumWidth(100)
        self.progressbar = QtGui.QProgressBar()
        self.lbl1 = QtGui.QLabel()
        self.buttonRefresh = QtGui.QPushButton()
        self.buttonRefresh.setText("Refresh sources")
        self.isWrittenTo = False
        self.table = QtGui.QTableWidget()
        self.configureTable(self.table)
        self.searchbutton.clicked.connect(
            lambda: self.searchForPPA(self.table))
        self.buttonRefresh.clicked.connect(self.updateSources)
        self.table.verticalHeader().hide()
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.addWidget(self.searchEditText)
        self.horizontalLayout.addWidget(self.searchbutton)
        self.horizontalLayout.setAlignment(QtCore.Qt.AlignRight)
        self.horizontalLayout2 = QtGui.QHBoxLayout()
        self.horizontalLayout2.setAlignment(QtCore.Qt.AlignRight)
        self.horizontalLayout2.addWidget(self.progressbar)
        self.horizontalLayout2.addWidget(self.buttonRefresh)
        self.horizontalLayout2.addWidget(self.closebutton)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.table)
        self.verticalLayout.addWidget(self.lbl1)
        self.verticalLayout.addLayout(self.horizontalLayout2)
        self.os_info = lsb_release.get_distro_information()
        self.sources = sourceslist.SourcesList()

        self.aprogress = UIAcquireProgress(True)
        self.thread1 = QtCore.QThread()
        self.aprogress.moveToThread(self.thread1)
        self.thread1.started.connect(
            lambda: self.aprogress.play(0.0, False, ""))
        self.aprogress.finished.connect(self.thread1.quit)
        self.connect(self.aprogress,
                     QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"),
                     self.updateProgressBar2)

        self.ppa = []
        self.table_data = []
Ejemplo n.º 28
0
 def getVersion(self):
     """
     returns codename,descr,id,release
     known ids" raring, linuxmint
     """
     self.check()
     import lsb_release
     result = lsb_release.get_distro_information()
     return result["CODENAME"].lower().strip(), result["DESCRIPTION"], result["ID"].lower().strip(), result["RELEASE"],
def get_release_to_test():
    try:
        import distro
        if distro.id() == 'ubuntu-core':
            return '{}.04'.format(distro.version())
        return distro.version()
    except (ImportError, CalledProcessError):
        import lsb_release
        return lsb_release.get_distro_information()["RELEASE"]
Ejemplo n.º 30
0
 def __init__(self, template=None, rootfs=None):
     self.rootfs_url = rootfs
     self.template_url = template
     self.rootfs_tarball = None
     self.template_tarball = None
     self.name = 'testbed'
     self.image_alias = uuid4().hex
     self.default_remote = "ubuntu:"
     self.os_version = lsb_release.get_distro_information()["RELEASE"]
Ejemplo n.º 31
0
 def get_codename(self):
     """ The codename of the distro, e.g. lucid """
     # for tests and similar
     if "SOFTWARE_CENTER_DISTRO_CODENAME" in os.environ:
         return os.environ["SOFTWARE_CENTER_DISTRO_CODENAME"]
     # normal behavior
     if not hasattr(self, "_distro_code_name"):
         self._distro_code_name = \
                 lsb_release.get_distro_information()["CODENAME"]
     return self._distro_code_name
Ejemplo n.º 32
0
def issue():
    uname = platform.uname()[2]
    if lsb_release is not None:
        distinfo = lsb_release.get_distro_information()
        lsb = distinfo.get('DESCRIPTION', 'n/a')
    elif is_mac:
        lsb = 'OS X' + platform.mac_ver()[0]
    else:
        lsb = ' '.join(platform.dist())
    return lsb + '\n' + uname
Ejemplo n.º 33
0
 def get_codename(self):
     """ The codename of the distro, e.g. lucid """
     # for tests and similar
     if "SOFTWARE_CENTER_DISTRO_CODENAME" in os.environ:
         return os.environ["SOFTWARE_CENTER_DISTRO_CODENAME"]
     # normal behavior
     if not hasattr(self, "_distro_code_name"):
         self._distro_code_name = \
                 lsb_release.get_distro_information()["CODENAME"]
     return self._distro_code_name
Ejemplo n.º 34
0
def _get_distro():
    lsb_info = lsb_release.get_distro_information()
    distro_id = lsb_info["ID"]
    log.debug("get_distro: '%s'", distro_id)
    # start with a import, this gives us only a softwarecenter module
    module =  __import__(distro_id, globals(), locals(), [], -1)
    # get the right class and instanciate it
    distro_class = getattr(module, distro_id)
    instance = distro_class(lsb_info)
    return instance
Ejemplo n.º 35
0
def issue():
    uname = platform.uname()[2]
    if lsb_release is not None:
        distinfo = lsb_release.get_distro_information()
        lsb = distinfo.get('DESCRIPTION', 'n/a')
    elif is_mac:
        lsb = 'OS X' + platform.mac_ver()[0]
    else:
        lsb = ' '.join(platform.dist())
    return lsb + '\n' + uname
Ejemplo n.º 36
0
 def check(self, die=True):
     """
     check if ubuntu or mint (which is based on ubuntu)
     """
     if not self._checked:
         try:
             import lsb_release
             info = lsb_release.get_distro_information()['ID']
             release = lsb_release.get_distro_information()['RELEASE']
             if info != 'Ubuntu' and info != 'LinuxMint':
                 raise RuntimeError("Only ubuntu or mint supported.")
             if not release.startswith(self._version):
                 raise RuntimeError("Only ubuntu version 14.04 supported")
             self._checked = True
         except ImportError:
             self._checked = False
             if die:
                 raise RuntimeError("Only ubuntu or mint supported.")
     return self._checked
Ejemplo n.º 37
0
 def check(self, die=True):
     """
     check if ubuntu or mint (which is based on ubuntu)
     """
     if not self._checked:
         try:
             import lsb_release
             info = lsb_release.get_distro_information()['ID']
             release = lsb_release.get_distro_information()['RELEASE']
             if info != 'Ubuntu' and info != 'LinuxMint':
                 raise RuntimeError("Only ubuntu or mint supported.")
             if not release.startswith(self._version):
                 raise RuntimeError("Only ubuntu version 14.04 supported")
             self._checked = True
         except ImportError:
             self._checked = False
             if die:
                 raise RuntimeError("Only ubuntu or mint supported.")
     return self._checked
Ejemplo n.º 38
0
    def _getPlatform(self):
        '''Discovers the platform'''
        _platform = None

        if sys.platform.startswith("linux"):

            import lsb_release
            info = lsb_release.get_distro_information()['ID'].lower()

            bits = _useELFtrick("/sbin/init")

            if bits == 32:
                if info == 'ubuntu':
                    _platform = "ubuntu32"
                elif info == 'linuxmint':
                    _platform = "mint32"
                else:
                    _platform = "linux32"
            elif bits == 64 or bits == 0:  #@todo does not work in python 3 anymore
                if info == 'ubuntu':
                    _platform = "ubuntu64"
                elif info == 'linuxmint':
                    _platform = "mint64"
                else:
                    _platform = "linux64"
            else:
                raise RuntimeError("dont find which nr bits in platform")

            # if os.path.exists("/proc/vmware"):
            #     _platform = PlatformType.ESX

        # elif sys.platform.startswith("sunos"):
        #     import commands
        #     _, bits = commands.getstatusoutput('isainfo -b')
        #     bits = int(bits)
        #     if bits == 32:
        #         _platform = PlatformType.SOLARIS32
        #     elif bits == 64:
        #         _platform = PlatformType.SOLARIS64
        #     else:
        #         _platform = PlatformType.UNKNOWN

        elif sys.platform.startswith("win"):
            _platform = "win64"

        elif sys.platform.startswith("cygwin"):
            _platform = "cygwin"

        elif sys.platform.startswith("darwin"):
            _platform = "darwin"

        else:
            raise RuntimeError("can't establish platform name")

        return _platform
Ejemplo n.º 39
0
 def __init__(self, model, controller):
     self.title = self.title.format(
         lsb_release.get_distro_information()['RELEASE'])
     self.model = model
     self.controller = controller
     self.items = []
     back = back_btn(_("Back"), on_press=self.cancel)
     super().__init__(
         screen(self._build_choices(), [back],
                focus_buttons=False,
                excerpt=_(self.excerpt)))
Ejemplo n.º 40
0
def check_dist():
    """
    Determines what distro we're running under.
    """
    if os.path.exists("/etc/debian_version"):
        import lsb_release
        return lsb_release.get_distro_information()['ID'].lower()
    elif os.path.exists("/etc/SuSE-release"):
        return "suse"
    else:
        # valid for Fedora and all Red Hat / Fedora derivatives
        return "redhat"
Ejemplo n.º 41
0
def check_dist():
    """
    Determines what distro we're running under.  
    """
    if os.path.exists("/etc/debian_version"):
       import lsb_release
       return lsb_release.get_distro_information()['ID'].lower()
    elif os.path.exists("/etc/SuSE-release"):
       return "suse"
    else:
       # valid for Fedora and all Red Hat / Fedora derivatives
       return "redhat"
Ejemplo n.º 42
0
    def __init__(self, parent=None):
        super(EasyPPAInstall, self).__init__(parent)
        self.setWindowTitle("Easy PPA Install")
        self.searchEditText = QtGui.QLineEdit()
        self.searchEditText.setPlaceholderText("Search for applications")
        self.searchEditText.setMaximumWidth(200)
        self.searchbutton = QtGui.QPushButton()
        self.error_msg = QtGui.QMessageBox()
        self.error_msg.setIcon(QtGui.QMessageBox.Critical)
        self.error_msg.setWindowTitle("Error")
        self.closebutton = QtGui.QPushButton()
        self.closebutton = QtGui.QPushButton()
        self.closebutton.setText('Close')
        self.closebutton.setMaximumWidth(150)
        self.closebutton.clicked.connect(self.close)
        self.searchbutton.setText("Search")
        self.searchbutton.setMaximumWidth(100)
        self.progressbar = QtGui.QProgressBar()
        self.lbl1 = QtGui.QLabel()
        self.buttonRefresh = QtGui.QPushButton()
        self.buttonRefresh.setText("Refresh sources")
        self.isWrittenTo = False
        self.table = QtGui.QTableWidget()
        self.configureTable(self.table)
        self.searchbutton.clicked.connect(lambda: self.searchForPPA(self.table))
        self.buttonRefresh.clicked.connect(self.updateSources)
        self.table.verticalHeader().hide()
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.addWidget(self.searchEditText)
        self.horizontalLayout.addWidget(self.searchbutton)
        self.horizontalLayout.setAlignment(QtCore.Qt.AlignRight)
        self.horizontalLayout2 = QtGui.QHBoxLayout()
        self.horizontalLayout2.setAlignment(QtCore.Qt.AlignRight)
        self.horizontalLayout2.addWidget(self.progressbar)
        self.horizontalLayout2.addWidget(self.buttonRefresh)
        self.horizontalLayout2.addWidget(self.closebutton)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.table)
        self.verticalLayout.addWidget(self.lbl1)
        self.verticalLayout.addLayout(self.horizontalLayout2)
        self.os_info = lsb_release.get_distro_information()
        self.sources = sourceslist.SourcesList()

        self.aprogress = UIAcquireProgress(True)
        self.thread1 = QtCore.QThread()
        self.aprogress.moveToThread(self.thread1)
        self.thread1.started.connect(lambda: self.aprogress.play(0.0, False, ""))
        self.aprogress.finished.connect(self.thread1.quit)
        self.connect(self.aprogress, QtCore.SIGNAL("updateProgressBar2(int, bool, QString)"), self.updateProgressBar2)

        self.ppa = []
        self.table_data = []
Ejemplo n.º 43
0
    def __init__(self, parent=None):
        super(ResetterHelper, self).__init__(parent)
        self.setWindowTitle("Resetter Helper v1.2")
        self.os_info = lsb_release.get_distro_information()
        os_information = '{} {}'.format(self.os_info['ID'],
                                        self.os_info['RELEASE'])
        os_info_label = QtWidgets.QLabel(os_information)
        self.lbl2 = QtWidgets.QLabel("File1")
        self.lbl3 = QtWidgets.QLabel("File2")
        self.lbl4 = QtWidgets.QLabel("")
        self.btnCreateManifest = QtWidgets.QPushButton("Make Manifest")
        self.btnCreateUserlist = QtWidgets.QPushButton("Make Userlist")
        self.btnOpen1 = QtWidgets.QPushButton("Open First File")
        self.btnOpen2 = QtWidgets.QPushButton("Open Second File")
        self.btnCompare = QtWidgets.QPushButton("Compare Files")
        self.listView = QtWidgets.QListView(self)
        self.model = QtGui.QStandardItemModel(self.listView)
        self.msg = QtWidgets.QMessageBox(self)
        self.euid = os.geteuid()
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue)
        self.lbl4.setPalette(palette)
        horizontalLayout = QtWidgets.QHBoxLayout()
        horizontalLayout2 = QtWidgets.QHBoxLayout()
        horizontalLayout.addWidget(self.btnOpen1)
        horizontalLayout.addWidget(self.btnOpen2)
        horizontalLayout2.addWidget(self.lbl2)
        horizontalLayout2.addWidget(self.lbl3)

        verticalLayout = QtWidgets.QVBoxLayout(self)
        verticalLayout.addWidget(os_info_label)
        verticalLayout.addWidget(self.btnCreateManifest)
        verticalLayout.addWidget(self.btnCreateUserlist)
        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addLayout(horizontalLayout2)
        verticalLayout.addWidget(self.btnCompare)
        verticalLayout.addWidget(self.lbl4)
        verticalLayout.addWidget(self.listView)
        self.setLayout(verticalLayout)
        self.btnCreateManifest.clicked.connect(self.generateManifest)
        self.btnCreateUserlist.clicked.connect(self.generateUserlist)
        self.btnOpen1.clicked.connect(self.openFile1)
        self.btnOpen2.clicked.connect(self.openFile2)
        self.btnCompare.clicked.connect(self.compareFiles)
        self.file1 = None
        self.file2 = None
        if 'PKEXEC_UID' in os.environ:
            self.user = pwd.getpwuid(int(os.environ['PKEXEC_UID'])).pw_name
        elif self.euid == 0 and 'PKEXEC_UID' not in os.environ:
            self.user = os.environ['SUDO_USER']
        else:
            self.user = os.environ.get('USER')
Ejemplo n.º 44
0
    def installpath(self):
        title = "Ubuntu %s" % (
            lsb_release.get_distro_information()['RELEASE'], )
        excerpt = _("Welcome to Ubuntu! The world's favorite platform "
                    "for clouds, clusters, and amazing internet things. "
                    "This is the installer for Ubuntu on servers and "
                    "internet devices.")
        footer = _("Use UP, DOWN arrow keys, and ENTER, to "
                   "navigate options")

        self.ui.set_header(title, excerpt)
        self.ui.set_footer(footer)
        self.ui.set_body(InstallpathView(self.model, self.signal))
Ejemplo n.º 45
0
    def _getPlatform(self):

        '''Discovers the platform'''
        _platform = None

        if sys.platform.startswith("linux"):

            import lsb_release
            info = lsb_release.get_distro_information()['ID'].lower()

            bits = _useELFtrick("/sbin/init")
            
            if bits == 32:
                if info == 'ubuntu':
                    _platform = "ubuntu32"
                elif info == 'linuxmint':
                    _platform = "mint32"
                else:
                    _platform = "linux32"
            elif bits == 64:
                if info == 'ubuntu':
                    _platform = "ubuntu64"
                elif info == 'linuxmint':
                    _platform = "mint64"
                else:
                    _platform = "linux64"

            # if os.path.exists("/proc/vmware"):
            #     _platform = PlatformType.ESX

        # elif sys.platform.startswith("sunos"):
        #     import commands
        #     _, bits = commands.getstatusoutput('isainfo -b')
        #     bits = int(bits)
        #     if bits == 32:
        #         _platform = PlatformType.SOLARIS32
        #     elif bits == 64:
        #         _platform = PlatformType.SOLARIS64
        #     else:
        #         _platform = PlatformType.UNKNOWN

        elif sys.platform.startswith("win"):
            _platform = "win64"

        elif sys.platform.startswith("cygwin"):
            _platform = "cygwin"

        # elif sys.platform.startswith("darwin"):
        #     _platform = PlatformType.DARWIN

        return _platform        
Ejemplo n.º 46
0
    def test_jinja_deep_error(self):
        """
        Test when we have an error in a execution module
        called by jinja
        """
        if salt.utils.platform.is_linux() and HAS_LSB_RELEASE:
            release = lsb_release.get_distro_information()
            if (release.get("ID") == "Debian"
                    and int(release.get("RELEASE", "0")[0]) < 9):
                self.skipTest("This test is flaky on Debian 8. Skipping.")

        ret = self.run_function("state.sls", ["issue-10010"])
        self.assertTrue(", in jinja_error" in ret[0].strip())
        self.assertTrue(ret[0].strip().endswith("Exception: hehehe"))
Ejemplo n.º 47
0
    def _getPlatform(self):
        '''Discovers the platform'''
        _platform = None

        if sys.platform.startswith("linux"):

            import lsb_release
            info = lsb_release.get_distro_information()['ID'].lower()

            bits = _useELFtrick("/sbin/init")

            if bits == 32:
                if info == 'ubuntu':
                    _platform = "ubuntu32"
                elif info == 'linuxmint':
                    _platform = "mint32"
                else:
                    _platform = "linux32"
            elif bits == 64:
                if info == 'ubuntu':
                    _platform = "ubuntu64"
                elif info == 'linuxmint':
                    _platform = "mint64"
                else:
                    _platform = "linux64"

            # if os.path.exists("/proc/vmware"):
            #     _platform = PlatformType.ESX

        # elif sys.platform.startswith("sunos"):
        #     import commands
        #     _, bits = commands.getstatusoutput('isainfo -b')
        #     bits = int(bits)
        #     if bits == 32:
        #         _platform = PlatformType.SOLARIS32
        #     elif bits == 64:
        #         _platform = PlatformType.SOLARIS64
        #     else:
        #         _platform = PlatformType.UNKNOWN

        elif sys.platform.startswith("win"):
            _platform = "win64"

        elif sys.platform.startswith("cygwin"):
            _platform = "cygwin"

        # elif sys.platform.startswith("darwin"):
        #     _platform = PlatformType.DARWIN

        return _platform
Ejemplo n.º 48
0
    def test_jinja_deep_error(self):
        '''
        Test when we have an error in a execution module
        called by jinja
        '''
        if salt.utils.is_linux() and HAS_LSB_RELEASE:
            release = lsb_release.get_distro_information()
            if release.get('ID') == 'Debian' and int(
                    release.get('RELEASE', '0')[0]) < 9:
                self.skipTest('This test is flaky on Debian 8. Skipping.')

        ret = self.run_function('state.sls', ['issue-10010'])
        self.assertTrue(', in jinja_error' in ret[0].strip())
        self.assertTrue(ret[0].strip().endswith('Exception: hehehe'))
	def test_get_distro_information(self):
		# Test that an inexistant /etc/lsb-release leads to empty output
		supposed_output = get_arch_distinfo()
		supposed_output['RELEASE']     = 'unstable';
		supposed_output['DESCRIPTION'] = '%(ID)s %(OS)s %(RELEASE)s' % supposed_output

		os.environ['LSB_ETC_LSB_RELEASE'] = 'test/inexistant_file_' + rnd_string(2,5)
		fn = 'test/debian_version_' + rnd_string(5,12)
		f = open(fn,'w')
		f.write('testing/sid')
		f.close()
		os.environ['LSB_ETC_DEBIAN_VERSION'] = fn
		self.assertEqual(lr.get_distro_information(),supposed_output)
		os.remove(fn)
		os.environ.pop('LSB_ETC_DEBIAN_VERSION')
Ejemplo n.º 50
0
def os_release():
    """
    This code is borrowed from Cobbler and really shouldn't be repeated.
    """
    if check_dist() == "redhat":
        fh = open("/etc/redhat-release")
        data = fh.read().lower()
        if data.find("fedora") != -1:
            make = "fedora"
        elif data.find("centos") != -1:
            make = "centos"
        else:
            make = "redhat"
        release_index = data.find("release")
        rest = data[release_index + 7:-1]
        tokens = rest.split(" ")
        for t in tokens:
            try:
                match = re.match('^\d+(?:\.\d+)?', t)
                if match:
                    return (make, float(match.group(0)))
            except ValueError:
                pass
        raise KX("failed to detect local OS version from /etc/redhat-release")

    elif check_dist() == "debian":
        import lsb_release
        release = lsb_release.get_distro_information()['RELEASE']
        return ("debian", release)
    elif check_dist() == "ubuntu":
        version = subprocess.check_output(
            ("lsb_release", "--release", "--short")).rstrip()
        make = "ubuntu"
        return (make, float(version))
    elif check_dist() in ("suse", "opensuse"):
        fd = open("/etc/SuSE-release")
        for line in fd.read().split("\n"):
            if line.find("VERSION") != -1:
                version = line.replace("VERSION = ", "")
            if line.find("PATCHLEVEL") != -1:
                rest = line.replace("PATCHLEVEL = ", "")
        make = "suse"
        return (make, float(version))
    else:
        return ("unknown", 0)
Ejemplo n.º 51
0
def log_startup_info():
	global _pre_log_buffer
	if len(_pre_log_buffer) > 0:
		_log.info('early startup log buffer:')
	for line in _pre_log_buffer:
		_log.info(' ' + line)
	del _pre_log_buffer
	_log.info('GNUmed client version [%s] on branch [%s]', current_client_version, current_client_branch)
	_log.info('Platform: %s', platform.uname())
	_log.info(('Python %s on %s (%s)' % (sys.version, sys.platform, os.name)).replace('\n', '<\\n>'))
	try:
		import lsb_release
		_log.info('lsb_release: %s', lsb_release.get_distro_information())
	except ImportError:
		pass
	_log.info('os.getcwd(): [%s]', os.getcwd())
	_log.info('process environment:')
	for key, val in os.environ.items():
		_log.info(' %s: %s' % (('${%s}' % key).rjust(30),	val))
Ejemplo n.º 52
0
    def _security_update_origins(klass):
        "Determine security update origins from apt configuration"

        if lsb_release is None:
            raise PkgError("lsb_release not found, can't determine security updates")

        codename = lsb_release.get_distro_information()['CODENAME']

        def _subst(line):
            mapping = {'distro_codename': codename,
                       'distro_id': klass.id, }
            return string.Template(line).substitute(mapping)

        origins = []
        for s in apt_pkg.config.value_list('Whatmaps::Security-Update-Origins'):
            (distro_id, distro_codename) = s.split()
            origins.append((_subst(distro_id),
                            _subst(distro_codename)))
        logging.debug("Security Update Origins: %s", origins)
        return origins
Ejemplo n.º 53
0
 def check(self):
     """
     check if ubuntu
     """
     if not self._checked:
         try:
             import lsb_release
             info = lsb_release.get_distro_information()['ID']
             if info != 'Ubuntu':
                 raise RuntimeError("Only ubuntu is supported, platform is not even linux.")
             self._checked = True
         except ImportError:
             self._checked = False
             raise RuntimeError("Only ubuntu is supported.")
     if not self._cache:
         try:
             import apt
             self._cache = apt.Cache()
         except ImportError:
             pass
Ejemplo n.º 54
0
 def _write_state_installed_pkgs(self, sourcedir, tar):
     cache = self._cache_cls(rootdir=sourcedir)
     s = ""
     foreign = ""
     for pkg in cache:
         if pkg.is_installed:
             # a version identifies the pacakge
             s += "%s %s %s\n" % (
                 pkg.name, pkg.installed.version, int(pkg.is_auto_installed))
             if not pkg.candidate or not pkg.candidate.downloadable:
                 self.not_downloadable.add(pkg.name)
             elif not (pkg.installed.downloadable and
                       pkg.candidate.downloadable):
                 self.version_mismatch.add(pkg.name)
             for o in pkg.installed.origins:
                 if o.archive == "now" and o.origin == "":
                     continue
                 import lsb_release
                 distro_id = lsb_release.get_distro_information()['ID']
                 if o.origin != distro_id:
                     foreign += "%s %s %s\n" % (
                         pkg.name, pkg.installed.version,
                         o.origin if o.origin != "" else "unknown")
                 break
     # store the installed.pkgs
     tarinfo = tarfile.TarInfo("./var/lib/apt-clone/installed.pkgs")
     s = s.encode('utf-8')
     tarinfo.size = len(s)
     tarinfo.mtime = time.time()
     tar.addfile(tarinfo, BytesIO(s))
     # store the foreign packages
     tarinfo = tarfile.TarInfo("./var/lib/apt-clone/foreign.pkgs")
     foreign = foreign.encode('utf-8')
     tarinfo.size = len(foreign)
     tarinfo.mtime = time.time()
     tar.addfile(tarinfo, BytesIO(foreign))
Ejemplo n.º 55
0
    def _detect_dist(self):
        # Detect windows
        _uname = platform.uname()
        if _uname[0].lower() == 'windows':
            win32_ver = platform.win32_ver()
            self['family'] = 'Windows'
            self['name'] = 'Windows'
            self['release'] = win32_ver[1]
            self['codename'] = win32_ver[0]

        elif osmod.path.isfile('/etc/lsb-release'):
            for line in open('/etc/lsb-release').readlines():
                # Matches any possible format:
                #     DISTRIB_ID="Ubuntu"
                #     DISTRIB_ID='Mageia'
                #     DISTRIB_ID=Fedora
                #     DISTRIB_RELEASE='10.10'
                #     DISTRIB_CODENAME='squeeze'
                #     DISTRIB_DESCRIPTION='Ubuntu 10.10'
                regex = re.compile('^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?([\w\s\.-_]+)(?:\'|")?')
                match = regex.match(line)
                if match:
                    # Adds: lsb_distrib_{id,release,codename,description}
                    self['lsb_%s' % match.groups()[0].lower()] = match.groups()[1].rstrip()
        try:
            import lsb_release
            release = lsb_release.get_distro_information()
            for key, value in release.iteritems():
                self['lsb_%s' % key.lower()] = value  # override /etc/lsb-release
        except ImportError:
            pass
        if 'lsb_codename' in self:
            self['codename'] = self['lsb_codename']

        if osmod.path.isfile('/etc/arch-release'):
            self['name'] = 'Arch'
            self['family'] = 'Arch'
        elif osmod.path.isfile('/etc/debian_version'):
            self['name'] = 'Debian'
            self['family'] = 'Debian'
            if 'lsb_distrib_id' in self:
                if 'GCEL' in self['lsb_distrib_id']:
                    self['name'] = 'GCEL'
                if 'Ubuntu' in self['lsb_distrib_id']:
                    self['name'] = 'Ubuntu'
                elif osmod.path.isfile('/etc/issue.net') and \
                        'Ubuntu' in open('/etc/issue.net').readline():
                    self['name'] = 'Ubuntu'
        elif osmod.path.isfile('/etc/gentoo-release'):
            self['name'] = 'Gentoo'
            self['family'] = 'Gentoo'
        elif osmod.path.isfile('/etc/fedora-release'):
            self['name'] = 'Fedora'
            self['family'] = 'RedHat'
        elif osmod.path.isfile('/etc/mandriva-version'):
            self['name'] = 'Mandriva'
            self['family'] = 'Mandriva'
        elif osmod.path.isfile('/etc/mandrake-version'):
            self['name'] = 'Mandrake'
            self['family'] = 'Mandriva'
        elif osmod.path.isfile('/etc/mageia-version'):
            self['name'] = 'Mageia'
            self['family'] = 'Mageia'
        elif osmod.path.isfile('/etc/meego-version'):
            self['name'] = 'MeeGo'
            self['family'] = 'MeeGo'
        elif osmod.path.isfile('/etc/vmware-version'):
            self['name'] = 'VMWareESX'
            self['family'] = 'VMWare'
        elif osmod.path.isfile('/etc/bluewhite64-version'):
            self['name'] = 'Bluewhite64'
            self['family'] = 'Bluewhite'
        elif osmod.path.isfile('/etc/slamd64-version'):
            self['name'] = 'Slamd64'
            self['family'] = 'Slackware'
        elif osmod.path.isfile('/etc/slackware-version'):
            self['name'] = 'Slackware'
            self['family'] = 'Slackware'
        elif osmod.path.isfile('/etc/enterprise-release'):
            self['family'] = 'Oracle'
            if osmod.path.isfile('/etc/ovs-release'):
                self['name'] = 'OVS'
            else:
                self['name'] = 'OEL'
        elif osmod.path.isfile('/etc/redhat-release'):
            self['family'] = 'RedHat'
            data = open('/etc/redhat-release', 'r').read()
            if 'centos' in data.lower():
                self['name'] = 'CentOS'
            elif 'scientific' in data.lower():
                self['name'] = 'Scientific'
            elif 'goose' in data.lower():
                self['name'] = 'GoOSe'
            else:
                self['name'] = 'RedHat'
        elif osmod.path.isfile('/etc/system-release'):
            self['family'] = 'RedHat'
            data = open('/etc/system-release', 'r').read().strip()
            if 'amazon' in data.lower():
                self['name'] = 'Amazon'
                code = data[-7:]
                bases = {
                '2012.09': '6.3',
                '2013.03': '6.4'
                }
                self['release'] = Version(bases.get(code, '6.3'))
                self['codename'] = code
        elif osmod.path.isfile('/etc/SuSE-release'):
            self['family'] = 'Suse'
            data = open('/etc/SuSE-release', 'r').read()
            if 'SUSE LINUX Enterprise Server' in data:
                self['name'] = 'SLES'
            elif 'SUSE LINUX Enterprise Desktop' in data:
                self['name'] = 'SLED'
            elif 'openSUSE' in data:
                self['name'] = 'openSUSE'
            else:
                self['name'] = 'SUSE'
        name, release, codename = platform.dist()
        if not 'name' in self:
            self['name'] = name
        if not 'release' in self:
            self['release'] = Version(release)
        self['version'] = self['release']
        if not 'codename' in self:
            self['codename'] = codename


        if not 'name' in self:
            self['name'] = 'Unknown %s' % self['kernel']
            self['family'] = 'Unknown'
        if not 'family' in self:
            self['family'] = 'Unknown'
Ejemplo n.º 56
0
Archivo: core.py Proyecto: 1mentat/salt
def os_data():
    '''
    Return grains pertaining to the operating system
    '''
    grains = {
        'num_gpus': 0,
        'gpus': [],
    }

    # Windows Server 2008 64-bit
    # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
    # Ubuntu 10.04
    # ('Linux', 'MINIONNAME', '2.6.32-38-server', '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
    (grains['kernel'], grains['nodename'],
     grains['kernelrelease'], version, grains['cpuarch'], _) = platform.uname()
    if salt.utils.is_windows():
        grains['osrelease'] = grains['kernelrelease']
        grains['osversion'] = grains['kernelrelease'] = version
        grains['os'] = 'Windows'
        grains['os_family'] = 'Windows'
        grains.update(_memdata(grains))
        grains.update(_windows_platform_data())
        grains.update(_windows_cpudata())
        grains.update(_ps(grains))
        return grains
    elif salt.utils.is_linux():
        # Add lsb grains on any distro with lsb-release
        try:
            import lsb_release
            release = lsb_release.get_distro_information()
            for key, value in release.iteritems():
                key = key.lower()
                lsb_param = 'lsb_{0}{1}'.format(
                    '' if key.startswith('distrib_') else 'distrib_',
                    key
                )
                grains[lsb_param] = value
        except ImportError:
            # if the python library isn't available, default to regex
            if os.path.isfile('/etc/lsb-release'):
                with salt.utils.fopen('/etc/lsb-release') as ifile:
                    for line in ifile:
                        # Matches any possible format:
                        #     DISTRIB_ID="Ubuntu"
                        #     DISTRIB_ID='Mageia'
                        #     DISTRIB_ID=Fedora
                        #     DISTRIB_RELEASE='10.10'
                        #     DISTRIB_CODENAME='squeeze'
                        #     DISTRIB_DESCRIPTION='Ubuntu 10.10'
                        regex = re.compile('^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?([\\w\\s\\.-_]+)(?:\'|")?')
                        match = regex.match(line.rstrip('\n'))
                        if match:
                            # Adds: lsb_distrib_{id,release,codename,description}
                            grains['lsb_{0}'.format(match.groups()[0].lower())] = match.groups()[1].rstrip()
            elif os.path.isfile('/etc/os-release'):
                # Arch ARM Linux
                with salt.utils.fopen('/etc/os-release') as ifile:
                    # Imitate lsb-release
                    for line in ifile:
                        # NAME="Arch Linux ARM"
                        # ID=archarm
                        # ID_LIKE=arch
                        # PRETTY_NAME="Arch Linux ARM"
                        # ANSI_COLOR="0;36"
                        # HOME_URL="http://archlinuxarm.org/"
                        # SUPPORT_URL="https://archlinuxarm.org/forum"
                        # BUG_REPORT_URL="https://github.com/archlinuxarm/PKGBUILDs/issues"
                        regex = re.compile('^([\\w]+)=(?:\'|")?([\\w\\s\\.-_]+)(?:\'|")?')
                        match = regex.match(line.rstrip('\n'))
                        if match:
                            name, value = match.groups()
                            if name.lower() == 'name':
                                grains['lsb_distrib_id'] = value.strip()
            elif os.path.isfile('/etc/altlinux-release'):
                # ALT Linux
                grains['lsb_distrib_id'] = 'altlinux'
                with salt.utils.fopen('/etc/altlinux-release') as ifile:
                    # This file is symlinked to from:
                    #     /etc/fedora-release
                    #     /etc/redhat-release
                    #     /etc/system-release
                    for line in ifile:
                        # ALT Linux Sisyphus (unstable)
                        comps = line.split()
                        if comps[0] == 'ALT':
                            grains['lsb_distrib_release'] = comps[2]
                            grains['lsb_distrib_codename'] = \
                                comps[3].replace('(', '').replace(')', '')
            elif os.path.isfile('/etc/centos-release'):
                # CentOS Linux
                grains['lsb_distrib_id'] = 'CentOS'
                with salt.utils.fopen('/etc/centos-release') as ifile:
                    for line in ifile:
                        # Need to pull out the version and codename
                        # in the case of custom content in /etc/centos-release
                        find_release = re.compile(r'\d+\.\d+')
                        find_codename = re.compile(r'(?<=\()(.*?)(?=\))')
                        release = find_release.search(line)
                        codename = find_codename.search(line)
                        if release is not None:
                            grains['lsb_distrib_release'] = release.group()
                        if codename is not None:
                            grains['lsb_distrib_codename'] = codename.group()

        # Use the already intelligent platform module to get distro info
        # (though apparently it's not intelligent enough to strip quotes)
        (osname, osrelease, oscodename) = \
            [x.strip('"').strip("'") for x in
             platform.linux_distribution(supported_dists=_supported_dists)]
        # Try to assign these three names based on the lsb info, they tend to
        # be more accurate than what python gets from /etc/DISTRO-release.
        # It's worth noting that Ubuntu has patched their Python distribution
        # so that platform.linux_distribution() does the /etc/lsb-release
        # parsing, but we do it anyway here for the sake for full portability.
        grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip()
        grains['osrelease'] = grains.get('lsb_distrib_release',
                                         osrelease).strip()
        grains['oscodename'] = grains.get('lsb_distrib_codename',
                                          oscodename).strip()
        distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip()
        # return the first ten characters with no spaces, lowercased
        shortname = distroname.replace(' ', '').lower()[:10]
        # this maps the long names from the /etc/DISTRO-release files to the
        # traditional short names that Salt has used.
        grains['os'] = _OS_NAME_MAP.get(shortname, distroname)
        grains.update(_linux_cpudata())
        grains.update(_linux_gpu_data())
    elif grains['kernel'] == 'SunOS':
        grains['os_family'] = 'Solaris'
        uname_v = __salt__['cmd.run']('uname -v')
        if 'joyent_' in uname_v:
            # See https://github.com/joyent/smartos-live/issues/224
            grains['os'] = grains['osfullname'] = 'SmartOS'
            grains['osrelease'] = uname_v
        elif os.path.isfile('/etc/release'):
            with salt.utils.fopen('/etc/release', 'r') as fp_:
                rel_data = fp_.read()
                try:
                    release_re = r'(Solaris|OpenIndiana(?: Development)?)' \
                                 r'\s+(\d+ \d+\/\d+|oi_\S+)?'
                    osname, osrelease = re.search(release_re,
                                                  rel_data).groups()
                except AttributeError:
                    # Set a blank osrelease grain and fallback to 'Solaris'
                    # as the 'os' grain.
                    grains['os'] = grains['osfullname'] = 'Solaris'
                    grains['osrelease'] = ''
                else:
                    grains['os'] = grains['osfullname'] = osname
                    grains['osrelease'] = osrelease

        grains.update(_sunos_cpudata())
    elif grains['kernel'] == 'VMkernel':
        grains['os'] = 'ESXi'
    elif grains['kernel'] == 'Darwin':
        osrelease = __salt__['cmd.run']('sw_vers -productVersion')
        grains['os'] = 'MacOS'
        grains['osrelease'] = osrelease
        grains.update(_bsd_cpudata(grains))
        grains.update(_osx_gpudata())
    else:
        grains['os'] = grains['kernel']
    if grains['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
        grains.update(_bsd_cpudata(grains))
        grains['osrelease'] = grains['kernelrelease'].split('-')[0]
        if grains['kernel'] == 'NetBSD':
            grains.update(_netbsd_gpu_data())
    if not grains['os']:
        grains['os'] = 'Unknown {0}'.format(grains['kernel'])
        grains['os_family'] = 'Unknown'
    else:
        # this assigns family names based on the os name
        # family defaults to the os name if not found
        grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'],
                                                 grains['os'])

    # Build the osarch grain. This grain will be used for platform-specific
    # considerations such as package management. Fall back to the CPU
    # architecture.
    if grains.get('os_family') == 'Debian':
        osarch = __salt__['cmd.run']('dpkg --print-architecture').strip()
    else:
        osarch = grains['cpuarch']
    grains['osarch'] = osarch

    grains.update(_memdata(grains))

    # Get the hardware and bios data
    grains.update(_hw_data(grains))

    # Load the virtual machine info
    grains.update(_virtual(grains))
    grains.update(_ps(grains))

    # Load additional OS family grains
    if grains['os_family'] == "RedHat":
        grains['osmajorrelease'] = grains['osrelease'].split('.', 1)

        grains['osfinger'] = '{os}-{ver}'.format(
                os=grains['osfullname'],
                ver=grains['osrelease'].partition('.')[0])
    elif grains.get('osfullname') == 'Ubuntu':
        grains['osfinger'] = '{os}-{ver}'.format(
                os=grains['osfullname'],
                ver=grains['osrelease'])

    return grains
Ejemplo n.º 57
0
import logging
import yaml
import tempfile
import shutil
import pprint
import subprocess
import glob
import submodules
import onlyaml
import onlu
from string import Template
import re
import json
import lsb_release

g_dist_codename = lsb_release.get_distro_information().get("CODENAME")

logger = onlu.init_logging("onlpm", logging.INFO)


class OnlPackageError(Exception):
    """General Package Error Exception

    This class is used to communicate user-level configuration
    and runtime errors related to package contents, package
    building, and similar operations.

    This exception should be caught at the highest level and
    the error message comminicated to the user."""

    def __init__(self, value):
Ejemplo n.º 58
0
         make = "centos"
      else:
         make = "redhat"
      release_index = data.find("release")
      rest = data[release_index+7:-1]
      tokens = rest.split(" ")
      for t in tokens:
         try:
             return (make,float(t))
         except ValueError, ve:
             pass
      raise CX("failed to detect local OS version from /etc/redhat-release")

   elif check_dist() == "debian":
      import lsb_release
      release = lsb_release.get_distro_information()['RELEASE']
      return ("debian", release)
   elif check_dist() == "ubuntu":
      version = sub_process.check_output(("lsb_release","--release","--short")).rstrip()
      make = "ubuntu"
      return (make, float(version))
   elif check_dist() == "suse":
      fd = open("/etc/SuSE-release")
      for line in fd.read().split("\n"):
         if line.find("VERSION") != -1:
            version = line.replace("VERSION = ","")
         if line.find("PATCHLEVEL") != -1:
            rest = line.replace("PATCHLEVEL = ","")
      make = "suse"
      return (make, float(version))
   else:
Ejemplo n.º 59
0
__author__ = 'ads'
# !/usr/bin/env python

import apt
import sys
import os
import lsb_release
import subprocess
from string import Template

release = lsb_release.get_distro_information()['CODENAME']
os.system(
    "echo \"deb http://ppa.launchpad.net/nginx/stable/ubuntu " + release + " main\" | sudo tee /etc/apt/sources.list.d/nginx-stable.list")
os.system("apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C300EE8C")
os.system("apt-get update")
os.system("apt-get install debconf-utils")
# Mysql Password
while True:
    mysql_pass = raw_input("MySql password >")
    confirm_mysql_pass = raw_input("Confirm Mysql password >")
    if mysql_pass == confirm_mysql_pass:
        os.system(
            "echo \"mysql-server-5.5 mysql-server/root_password password \"" + mysql_pass + " | debconf-set-selections")
        os.system(
            "echo \"mysql-server-5.5 mysql-server/root_password_again password \"" + mysql_pass + " | debconf-set-selections")
        break
    else:
        print "Sorry , Passwords do not match, try again"

# List of packages you want to install
packages_to_install = ["mysql-server", "php5-mysql", "nginx", "php5-fpm"]