Python get user agent

60 Python code examples are found related to " get user agent". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: resources.py    From anchore with Apache License 2.0 6 votes vote down vote up
def get_user_agent():
    """
    Construct and informative user-agent string.
    Includes OS version and docker version info

    Not thread-safe
    :return:
    """

    global user_agent_string
    if user_agent_string is None:
        # get OS type
        try:
            sysinfo = subprocess.check_output('lsb_release -i -r -s'.split(' '))
            dockerinfo = subprocess.check_output('docker --version'.split(' '))

            user_agent_string = ' '.join([sysinfo.replace('\t','/'),
                                          dockerinfo.replace(" version ", "/").replace(", ", "/").replace(' ', '/')]).replace('\n','')
        except:
            user_agent_string = None

    return user_agent_string 
Example 2
Source File: zoomeye.py    From zoomeye-search with GNU General Public License v3.0 6 votes vote down vote up
def getRandomUserAgent():
    user_agents = ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
                   "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
                   "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",
                   "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36",
                   "Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0",
                   "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)",
                   "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)",
                   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
                   "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
                   "Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.17",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0",
                   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"]
    return user_agents[randint(0, len(user_agents) - 1)] 
Example 3
Source File: remote_api_stub.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def GetUserAgent():
  """Determines the value of the 'User-agent' header to use for HTTP requests.

  Returns:
    String containing the 'user-agent' header value, which includes the SDK
    version, the platform information, and the version of Python;
    e.g., "remote_api/1.0.1 Darwin/9.2.0 Python/2.5.2".
  """
  product_tokens = []

  product_tokens.append("Google-remote_api/1.0")


  product_tokens.append(appengine_rpc.GetPlatformToken())


  python_version = ".".join(str(i) for i in sys.version_info)
  product_tokens.append("Python/%s" % python_version)

  return " ".join(product_tokens) 
Example 4
Source File: wrappers.py    From KortURL with MIT License 6 votes vote down vote up
def get_user_agent(request):
    # Tries to get UserAgent objects from cache before constructing a UserAgent
    # from scratch because parsing regexes.yaml/json (ua-parser) is slow
    if not hasattr(request, 'META'):
        return ''

    ua_string = request.META.get('HTTP_USER_AGENT', '')
    if cache:
        key = get_cache_key(ua_string)
        user_agent = cache.get(key)
        if user_agent is None:
            user_agent = parse(ua_string)
            cache.set(key, user_agent)
    else:
        user_agent = parse(ua_string)
    return user_agent 
Example 5
Source File: docker_monitor.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def get_user_agent_fragment(self):
        """This method is periodically invoked by a separate (MonitorsManager) thread and must be thread safe."""

        def _version_to_fragment(ver):
            # Helper function to transform docker version to user-agent fragment
            if not ver:
                # version not yet set: return 'docker=yes' to signify docker
                return "docker=true"
            log_mode = self._config.get("log_mode")
            if log_mode == "syslog":
                extra = ""
            else:
                extra = "|raw" if self._config.get("docker_raw_logs") else "|api"
            return "docker=%s|%s%s" % (ver, log_mode, extra)

        self.__version_lock.acquire()
        try:
            return _version_to_fragment(self.__version)
        finally:
            self.__version_lock.release() 
Example 6
Source File: util.py    From rssit with MIT License 6 votes vote down vote up
def get_random_user_agent(config=None):
    if config is not None:
        useragent = get_httpheader(config, "user-agent")
        if useragent:
            return useragent
    return random.choice(user_agents) 
Example 7
Source File: wsfaker.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent_fingerprints(count=5):
        """
        Get a list of dictionaries representing user agent fingerprints.
        :param count: The number of dictionaries to return.
        :return: A list of dictionaries representing user agent fingerprints.
        """
        to_return = []
        for i in range(count):
            to_return.append({
                "user_agent_type": WsFaker.get_word(),
                "user_agent_name": WsFaker.get_word(),
                "response_has_content": WsFaker.get_user_agent(),
                "response_mime_type": WsFaker.get_mime_string(),
                "response_primary_hash": WsFaker.get_sha256_string(),
                "response_secondary_hash": WsFaker.get_sha256_string(),
                "response_status_code": WsFaker.get_http_response_status(),
            })
        return to_return 
Example 8
Source File: plugin.py    From limnoria-plugins with MIT License 5 votes vote down vote up
def get_user_agent(self):
        """
        Returns a random user agent from the ones available
        """
        agents = self.registryValue("userAgents")
        return random.choice(agents) 
Example 9
Source File: proxy_tools.py    From hproxy with MIT License 5 votes vote down vote up
def get_random_user_agent():
    """
    Get a random user agent string.
    :return: Random user agent string.
    """
    USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'
    return random.choice(await _get_data('base_spider/user_agents.txt', USER_AGENT)) 
Example 10
Source File: request.py    From dart-fss with MIT License 5 votes vote down vote up
def get_user_agent():
    """ Return user-agent
    Returns
    -------
    str
        user-agent
    """
    ua = UserAgent()
    agent = ua.chrome
    return str(agent) 
Example 11
Source File: useragent.py    From izone with MIT License 5 votes vote down vote up
def get_user_agent(os=None, navigator=None, device_type=None):
    try:
        u = generate_user_agent(os=os, navigator=navigator, device_type=device_type)
    except Exception as e:
        u = str(e)
    return u 
Example 12
Source File: req_handler.py    From Domoticz-Google-Assistant with Apache License 2.0 5 votes vote down vote up
def getUserAgent(self):
        user = self.getSessionUser()
        if user is None or user.get('uid', '') == '':
            return None
        accessToken = Auth['tokens'].get(user['tokens'][0], None)
        if accessToken is None:
            return None

        return accessToken['userAgentId'] 
Example 13
Source File: wsfaker.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent():
        """
        Create and return a fake user agent.
        :return: A fake user agent.
        """
        return 'Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US);' 
Example 14
Source File: policy.py    From starbelly with MIT License 5 votes vote down vote up
def get_first_user_agent(self):
        '''
        :returns: Return the first user agent.
        :rtype: str
        '''
        return self._user_agents[0] 
Example 15
Source File: baseapi.py    From plugin.git.browser with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent(self):
		if self.user_agent: return self.user_agent
		user_agent = kodi.get_property('user_agent')
		try: agent_refresh_time = int(kodi.get_property('agent_refresh_time'))
		except: agent_refresh_time = 0
		if not user_agent or agent_refresh_time < (time.time() - (7 * 24 * 60 * 60)):
			user_agent = self.generate_user_agent()
			kodi.set_property('user_agent', user_agent)
			kodi.set_property('agent_refresh_time', str(int(time.time())))
		return user_agent 
Example 16
Source File: hdx_configuration.py    From hdx-python-api with MIT License 5 votes vote down vote up
def get_user_agent(self):
        # type: () -> str
        """
        Return user agent

        Returns:
            str: User agent

        """
        return self.user_agent 
Example 17
Source File: utils.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user_agent(plugin=None):
    ver = sys.version_info
    python_version = '%d.%d.%d.%s.%d' % (ver[0], ver[1], ver[2], ver[3], ver[4])
    user_agent = u('wakatime/{ver} ({platform}) Python{py_ver}').format(
        ver=u(__version__),
        platform=u(platform.platform()),
        py_ver=python_version,
    )
    if plugin:
        user_agent = u('{user_agent} {plugin}').format(
            user_agent=user_agent,
            plugin=u(plugin),
        )
    else:
        user_agent = u('{user_agent} Unknown/0').format(
            user_agent=user_agent,
        )
    return user_agent 
Example 18
Source File: async_requests.py    From proxy_py with GNU General Public License v3.0 5 votes vote down vote up
def get_random_user_agent():
    return 'Mozilla/5.0 (Windows NT;) Gecko/20100101 Firefox/58.0'
    # return 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0'
    # TODO: do it
    # return UserAgent().random 
Example 19
Source File: policy.py    From starbelly with MIT License 5 votes vote down vote up
def get_user_agent(self):
        '''
        :returns: A randomly selected user agent string.
        :rtype: str
        '''
        return random.choice(self._user_agents) 
Example 20
Source File: userAgent.py    From HTTP_Request_Randomizer with MIT License 5 votes vote down vote up
def get_random_user_agent(self):
        if self.agent_file:
            user_agent = random.choice(self.useragents)
            return user_agent.decode('utf-8')
        else:
            return self.fakeuseragent.random 
Example 21
Source File: _auxiliary.py    From cognite-sdk-python with Apache License 2.0 5 votes vote down vote up
def get_user_agent():
    sdk_version = "CognitePythonSDK/{}".format(get_current_sdk_version())

    python_version = "{}/{} ({};{})".format(
        platform.python_implementation(), platform.python_version(), platform.python_build(), platform.python_compiler()
    )

    os_version_info = [platform.release(), platform.machine(), platform.architecture()[0]]
    os_version_info = [s for s in os_version_info if s]  # Ignore empty strings
    os_version_info = "-".join(os_version_info)
    operating_system = "{}/{}".format(platform.system(), os_version_info)

    return "{} {} {}".format(sdk_version, python_version, operating_system) 
Example 22
Source File: utils.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def get_user_agent():
    """
    Determines the user agent string for the current platform.
    Needed to retrieve a valid ESN (except for Android, where the ESN can
    be generated locally)

    :returns: str -- User agent string
    """
    chrome_version = 'Chrome/59.0.3071.115'
    base = 'Mozilla/5.0 '
    base += '%PL% '
    base += 'AppleWebKit/537.36 (KHTML, like Gecko) '
    base += '%CH_VER% Safari/537.36'.replace('%CH_VER%', chrome_version)
    system = platform.system()
    # Mac OSX
    if system == 'Darwin':
        return base.replace('%PL%', '(Macintosh; Intel Mac OS X 10_10_1)')
    # Windows
    if system == 'Windows':
        return base.replace('%PL%', '(Windows NT 6.1; WOW64)')
    # ARM based Linux
    if platform.machine().startswith('arm'):
        return base.replace('%PL%', '(X11; CrOS armv7l 7647.78.0)')
    # x86 Linux
    return base.replace('%PL%', '(X11; Linux x86_64)') 
Example 23
Source File: favUp.py    From fav-up with MIT License 5 votes vote down vote up
def get_user_agent(self):
        try:
            return self.ua.random
        except FakeUserAgentError:
            return "Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0" 
Example 24
Source File: __init__.py    From crawler with MIT License 5 votes vote down vote up
def getUserAgent(type=''):
    type = type.lower()
    userAgent = {
        'chrome': chrome,
        'firefox': firefox,
        'mozilla': mozilla,
        'opera': opera,
        'safari': safari,
        'all': chrome + firefox + mozilla + opera + safari
    }
    if (type == 'chrome' or type == 'firefox' or type == 'mozilla' or type == 'opera' or type == 'safari'):
        ua = random.choice(userAgent[type])
    else:
        ua = random.choice(userAgent['all'])
    return ua 
Example 25
Source File: http_fetcher.py    From feedsubs with MIT License 5 votes vote down vote up
def get_user_agent(subscriber_count: Optional[int]=None,
                   feed_id: Optional[int]=None) -> str:
    """Generate a user-agent allowing publisher to gather subscribers count.

    See https://support.feed.press/article/66-how-to-be-a-good-feed-fetcher
    """
    options = list()

    if settings.DEBUG:
        name = 'Feedsubs-dev'
    else:
        name = 'Feedsubs'
        options.append(
            '+{}'.format(build_absolute_uri(None, reverse('reader:fetcher')))
        )

    if subscriber_count is not None:
        options.append('{} subscribers'.format(subscriber_count))

    if feed_id is not None:
        options.append('feed-id={}'.format(feed_id))

    user_agent = name
    if options:
        user_agent = '{} ({})'.format(user_agent, '; '.join(options))

    return user_agent 
Example 26
Source File: core.py    From WebCrawler with MIT License 5 votes vote down vote up
def get_user_agent_by_url(self, url):
        if '//m.' in url:
            # e.g. http://m.debugtalk.com
            return self.user_agent['mobile']
        else:
            return self.user_agent['www'] 
Example 27
Source File: env.py    From whatsapp-rest-webservice with MIT License 5 votes vote down vote up
def getUserAgent(self):
        return self.__class__._USERAGENT_STRING.format(
            WHATSAPP_VERSION = self.getVersion(),
            OS_NAME = self.getOSName(),
            OS_VERSION = self.getOSVersion(),
            MANUFACTURER = self.getManufacturer(),
            DEVICE_NAME = self.getDeviceName()
        ) 
Example 28
Source File: userAgent.py    From HTTP_Request_Randomizer with MIT License 5 votes vote down vote up
def get_first_user_agent(self):
        if self.agent_file:
            return self.useragents[0].decode('utf-8')
        else:
            logger.warning('Fake-useragent library does not support operaration get_first - change to user-agent file!')
            return None 
Example 29
Source File: function.py    From owllook with Apache License 2.0 5 votes vote down vote up
def get_random_user_agent() -> str:
    """
    Get a random user agent string.
    :return: Random user agent string.
    """
    return random.choice(await _get_data('user_agents.txt', CONFIG.USER_AGENT)) 
Example 30
Source File: userAgent.py    From HTTP_Request_Randomizer with MIT License 5 votes vote down vote up
def get_last_user_agent(self):
        if self.agent_file:
            return self.useragents[-1].decode('utf-8')
        else:
            logger.warning('Fake-useragent library does not support operaration get_last - change to user-agent file!')
            return None 
Example 31
Source File: userAgent.py    From HTTP_Request_Randomizer with MIT License 5 votes vote down vote up
def get_len_user_agent(self):
        if self.agent_file:
            return len(self.useragents)
        else:
            logger.warning('Fake-useragent library does not support operaration get_len - change to user-agent file!')
            return None 
Example 32
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_maas_user_agent():
    from maasserver.models import Config

    user_agent = get_maas_version_user_agent()
    uuid = Config.objects.get_config("uuid")
    if uuid:
        user_agent = "%s/%s" % (user_agent, uuid)
    return user_agent 
Example 33
Source File: version.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_maas_version_user_agent():
    """Return the version string for the running MAAS region.

    The returned string is suitable to set the user agent.
    """
    version, subversion = get_maas_version_subversion()
    return "maas/%s/%s" % (version, subversion) 
Example 34
Source File: client.py    From sewer with MIT License 5 votes vote down vote up
def get_user_agent():
        return "python-requests/{requests_version} ({system}: {machine}) sewer {sewer_version} ({sewer_url})".format(
            requests_version=requests.__version__,
            system=platform.system(),
            machine=platform.machine(),
            sewer_version=sewer_version.__version__,
            sewer_url=sewer_version.__url__,
        ) 
Example 35
Source File: __init__.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent():
    """
    Provides the `USER_AGENT` string that is passed to the Cloudinary servers.
    Prepends  `USER_PLATFORM` if it is defined.

    :returns: the user agent
    :rtype: str
    """

    if USER_PLATFORM == "":
        return USER_AGENT
    else:
        return USER_PLATFORM + " " + USER_AGENT 
Example 36
Source File: constants.py    From SlackPirate with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent():
    operating_systems = ['windows', 'osx']
    browsers = ['chrome', 'firefox']
    try:
        user_agent = requests.get(
            "https://api.user-agent.io/?browser=" + random.choice(browsers) + "&os=" + random.choice(operating_systems))
        if user_agent.status_code == 200 and "Mozilla" in user_agent.text:
            return user_agent.text
        else:
            return random.choice(user_agents)
    except requests.exceptions.RequestException:
        return random.choice(user_agents) 
Example 37
Source File: user_agent.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def get_provisioning_user_agent():
    """
    Create the user agent for Provisioning
    """
    return "{provisioning_iden}/{version}{common}".format(
        provisioning_iden=PROVISIONING_IDENTIFIER, version=VERSION, common=_get_common_user_agent()
    ) 
Example 38
Source File: luis_util.py    From botbuilder-python with MIT License 5 votes vote down vote up
def get_user_agent():
        package_user_agent = f"{__title__}/{__version__}"
        uname = platform.uname()
        os_version = f"{uname.machine}-{uname.system}-{uname.version}"
        py_version = f"Python,Version={platform.python_version()}"
        platform_user_agent = f"({os_version}; {py_version})"
        user_agent = f"{package_user_agent} {platform_user_agent}"
        return user_agent 
Example 39
Source File: ga.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent():
    return "XBMC/%s (%s)" % (
        xbmc.getInfoLabel("System.BuildVersion").split(" ")[0],
        get_platform()
    ) 
Example 40
Source File: appcfg.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def GetUserAgent(get_version=sdk_update_checker.GetVersionObject,
                 get_platform=appengine_rpc.GetPlatformToken,
                 sdk_product=SDK_PRODUCT):
  """Determines the value of the 'User-agent' header to use for HTTP requests.

  If the 'APPCFG_SDK_NAME' environment variable is present, that will be
  used as the first product token in the user-agent.

  Args:
    get_version: Used for testing.
    get_platform: Used for testing.
    sdk_product: Used as part of sdk/version product token.

  Returns:
    String containing the 'user-agent' header value, which includes the SDK
    version, the platform information, and the version of Python;
    e.g., 'appcfg_py/1.0.1 Darwin/9.2.0 Python/2.5.2'.
  """
  product_tokens = []


  sdk_name = os.environ.get('APPCFG_SDK_NAME')
  if sdk_name:
    product_tokens.append(sdk_name)
  else:
    version = get_version()
    if version is None:
      release = 'unknown'
    else:
      release = version['release']

    product_tokens.append('%s/%s' % (sdk_product, release))


  product_tokens.append(get_platform())


  python_version = '.'.join(str(i) for i in sys.version_info)
  product_tokens.append('Python/%s' % python_version)

  return ' '.join(product_tokens) 
Example 41
Source File: util.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def GetTimelineUserAgentDict(category, version_level=None, user_agents=None):
    if version_level:
        user_agents = result_stats.CategoryBrowserManager.GetBrowsers(
            category, version_level)
        logging.info('us: %s, %s, %s', user_agents, category, version_level)
    if user_agents:
        if not version_level:
            user_agents = user_agents.split(',')
        user_agent_dict = {}
        for user_agent in user_agents:
            (family, v1, v2, v3) = (models.user_agent.UserAgent.
                                    parse_pretty(user_agent))
            if not family in user_agent_dict:
                #logging.info('Adding family: %s' % family)
                user_agent_dict[family] = []
            version = user_agent.replace('%s ' % family, '')
            user_agent_dict[family].append(version)
    else:
        user_agents = []
        user_agent_dict = DEFAULT_TIMELINE_DICT
        for family, version_list in user_agent_dict.items():
            for version in version_list:
                family_version = '%s %s' % (family, version)
                user_agents.append(family_version)

    return (user_agents, user_agent_dict) 
Example 42
Source File: __init__.py    From python-slackclient with MIT License 5 votes vote down vote up
def get_user_agent():
    """Construct the user-agent header with the package info,
    Python version and OS version.

    Returns:
        The user agent string.
        e.g. 'Python/3.6.7 slackclient/2.0.0 Darwin/17.7.0'
    """
    # __name__ returns all classes, we only want the client
    client = "{0}/{1}".format("slackclient", slack_version.__version__)
    python_version = "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info)
    system_info = "{0}/{1}".format(platform.system(), platform.release())
    user_agent_string = " ".join([python_version, client, system_info])
    return user_agent_string 
Example 43
Source File: wrappers.py    From KortURL with MIT License 5 votes vote down vote up
def get_and_set_user_agent(request):
    # If request already has ``user_agent``, it will return that, otherwise
    # call get_user_agent and attach it to request so it can be reused
    if hasattr(request, 'user_agent'):
        return request.user_agent

    if not request:
        return parse('')

    request.user_agent = get_user_agent(request)
    return request.user_agent 
Example 44
Source File: device_utils.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def get_user_agent(enable_android_mediaflag_fix=False):
    """
    Determines the user agent string for the current platform.
    Needed to retrieve a valid ESN (except for Android, where the ESN can be generated locally)

    :returns: str -- User agent string
    """
    system = get_system_platform()
    if enable_android_mediaflag_fix and system == 'android' and is_device_4k_capable():
        # The UA affects not only the ESNs in the login, but also the video details,
        # so the UAs seem refer to exactly to these conditions: https://help.netflix.com/en/node/23742
        # This workaround is needed because currently we do not login through the netflix native android API,
        # but redirect everything through the website APIs, and the website APIs do not really support android.
        # Then on android usually we use the 'arm' UA which refers to chrome os, but this is limited to 1080P, so the
        # labels on the 4K devices appears wrong (in the Kodi skin the 4K videos have 1080P media flags instead of 4K),
        # the Windows UA is not limited, so we can use it to get the right video media flags.
        system = 'windows'

    chrome_version = 'Chrome/83.0.4103.112'
    base = 'Mozilla/5.0 '
    base += '%PL% '
    base += 'AppleWebKit/537.36 (KHTML, like Gecko) '
    base += '%CH_VER% Safari/537.36'.replace('%CH_VER%', chrome_version)

    if system in ['osx', 'ios', 'tvos']:
        return base.replace('%PL%', '(Macintosh; Intel Mac OS X 10_14_6)')
    if system in ['windows', 'uwp']:
        return base.replace('%PL%', '(Windows NT 10; Win64; x64)')
    # ARM based Linux
    if get_machine().startswith('arm'):
        # Last number is the platform version of Chrome OS
        return base.replace('%PL%', '(X11; CrOS armv7l 13020.82.0)')
    # x86 Linux
    return base.replace('%PL%', '(X11; Linux x86_64)') 
Example 45
Source File: plugin.py    From limnoria-plugins with Do What The F*ck You Want To Public License 5 votes vote down vote up
def get_user_agent(self):
        """
        Returns a random user agent from the ones available
        """
        agents = self.registryValue("default.userAgents")
        return random.choice(agents) 
Example 46
Source File: user_agents.py    From Belati with GNU General Public License v2.0 5 votes vote down vote up
def get_user_agent(self):
        try:
            return ua.random
        except FakeUserAgentError:
            return "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/49.0" 
Example 47
Source File: runIPRscan.py    From funannotate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getUserAgent():
    printDebugMessage('getUserAgent', 'Begin', 11)
    # Agent string for urllib2 library.
    urllib_agent = 'Python-urllib/%s' % urllib2.__version__
    clientRevision = '$Revision: 2809 $'
    clientVersion = '0'
    if len(clientRevision) > 11:
        clientVersion = clientRevision[11:-2]
    # Prepend client specific agent string.
    user_agent = 'EBI-Sample-Client/%s (%s; Python %s; %s) %s' % (
        clientVersion, os.path.basename(__file__),
        platform.python_version(), platform.system(),
        urllib_agent
    )
    printDebugMessage('getUserAgent', 'user_agent: ' + user_agent, 12)
    printDebugMessage('getUserAgent', 'End', 11)
    return user_agent

# Wrapper for a REST (HTTP GET) request 
Example 48
Source File: haaska.py    From haaska with MIT License 5 votes vote down vote up
def get_user_agent(self):
        library = "Home Assistant Alexa Smart Home Skill"
        aws_region = os.environ.get("AWS_DEFAULT_REGION")
        default_user_agent = requests.utils.default_user_agent()
        return f"{library} - {aws_region} - {default_user_agent}" 
Example 49
Source File: dumpgenerator.py    From wikiteam with GNU General Public License v3.0 5 votes vote down vote up
def getUserAgent():
    """ Return a cool user-agent to hide Python user-agent """
    useragents = [
        # firefox
        'Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0',
        'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0',
    ]
    return useragents[0] 
Example 50
Source File: user_agent.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def get_iothub_user_agent():
    """
    Create the user agent for IotHub
    """
    return "{iothub_iden}/{version}{common}".format(
        iothub_iden=IOTHUB_IDENTIFIER, version=VERSION, common=_get_common_user_agent()
    ) 
Example 51
Source File: services.py    From bioservices with GNU General Public License v3.0 5 votes vote down vote up
def getUserAgent(self):
        #self.logging.info('getUserAgent: Begin')
        urllib_agent = 'Python-requests/%s' % requests.__version__
        #clientRevision = ''
        from bioservices import version
        clientVersion = version
        user_agent = 'BioServices/%s (bioservices.%s; Python %s; %s) %s' % (
            clientVersion, os.path.basename(__file__),
            platform.python_version(), platform.system(),
            urllib_agent
        )
        #self.logging.info('getUserAgent: user_agent: ' + user_agent)
        #self.logging.info('getUserAgent: End')
        return user_agent 
Example 52
Source File: utils.py    From paasta with Apache License 2.0 5 votes vote down vote up
def get_user_agent() -> str:
    base_name = os.path.basename(sys.argv[0])
    if base_name == "gunicorn":
        return f"{sys.argv[-1]} {paasta_tools.__version__}"
    elif len(sys.argv) >= 1:
        return f"{base_name} {paasta_tools.__version__}"
    else:
        return f"PaaSTA Tools {paasta_tools.__version__}" 
Example 53
Source File: config.py    From googleplay-api with GNU General Public License v3.0 5 votes vote down vote up
def getUserAgent(self):
        version_string = self.device.get('vending.versionstring')
        if version_string is None:
            version_string = '8.4.19.V-all [0] [FP] 175058788'
        return ("Android-Finsky/{versionString} ("
                "api=3"
                ",versionCode={versionCode}"
                ",sdk={sdk}"
                ",device={device}"
                ",hardware={hardware}"
                ",product={product}"
                ",platformVersionRelease={platform_v}"
                ",model={model}"
                ",buildId={build_id}"
                ",isWideScreen=0"
                ",supportedAbis={supported_abis}"
                ")").format(versionString=version_string,
                            versionCode=self.device.get('vending.version'),
                            sdk=self.device.get('build.version.sdk_int'),
                            device=self.device.get('build.device'),
                            hardware=self.device.get('build.hardware'),
                            product=self.device.get('build.product'),
                            platform_v=self.device.get('build.version.release'),
                            model=self.device.get('build.model'),
                            build_id=self.device.get('build.id'),
                            supported_abis=self.device.get('platforms').replace(',', ';')) 
Example 54
Source File: webtech.py    From webtech with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_random_user_agent():
    """
    Get a random user agent from a file
    """
    ua_file = os.path.join(os.path.realpath(
        os.path.dirname(__file__)), "ua.txt")
    try:
        with open(ua_file) as f:
            agents = f.readlines()
            return random.choice(agents).strip()
    except FileNotFoundException as e:
        print(e)
        print('Please: Reinstall webtech correctly or provide a valid User-Agent list')
        exit(-1) 
Example 55
Source File: processor.py    From pyriscope with MIT License 5 votes vote down vote up
def get_mocked_user_agent():
    try:
        response = requests.get("http://api.useragent.io/")
        response = json.loads(response.text)
        return response['ua']
    except:
        try:
            response = requests.get("http://labs.wis.nu/ua/")
            response = json.loads(response.text)
            return response['ua']
        except:
            return DEFAULT_UA 
Example 56
Source File: slackrequest.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def get_user_agent(self):
        # Check for custom user-agent and append if found
        if self.custom_user_agent:
            custom_ua_list = ["/".join(client_info) for client_info in self.custom_user_agent]
            custom_ua_string = " ".join(custom_ua_list)
            self.default_user_agent['custom'] = custom_ua_string

        # Concatenate and format the user-agent string to be passed into request headers
        ua_string = []
        for key, val in self.default_user_agent.items():
            ua_string.append(val)

        user_agent_string = " ".join(ua_string)
        return user_agent_string 
Example 57
Source File: user_agent.py    From advanced-launcher with GNU General Public License v2.0 5 votes vote down vote up
def getUserAgent():
    platform = random.choice(['Macintosh', 'Windows', 'X11'])
    if platform == 'Macintosh':
        os  = random.choice(['68K', 'PPC'])
    elif platform == 'Windows':
        os  = random.choice(['Win3.11', 'WinNT3.51', 'WinNT4.0', 'Windows NT 5.0', 'Windows NT 5.1', 'Windows NT 5.2', 'Windows NT 6.0', 'Windows NT 6.1', 'Windows NT 6.2', 'Win95', 'Win98', 'Win 9x 4.90', 'WindowsCE'])
    elif platform == 'X11':
        os  = random.choice(['Linux i686', 'Linux x86_64'])
    browser = random.choice(['chrome', 'firefox', 'ie'])
    if browser == 'chrome':
        webkit = str(random.randint(500, 599))
        version = str(random.randint(0, 24)) + '.0' + str(random.randint(0, 1500)) + '.' + str(random.randint(0, 999))
        return 'Mozilla/5.0 (' + os + ') AppleWebKit/' + webkit + '.0 (KHTML, live Gecko) Chrome/' + version + ' Safari/' + webkit
    elif browser == 'firefox':
        year = str(random.randint(2000, 2012))
        month = random.randint(1, 12)
        if month < 10:
            month = '0' + str(month)
        else:
            month = str(month)
        day = random.randint(1, 30)
        if day < 10:
            day = '0' + str(day)
        else:
            day = str(day)
        gecko = year + month + day
        version = random.choice(['1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0', '12.0', '13.0', '14.0', '15.0'])
        return 'Mozilla/5.0 (' + os + '; rv:' + version + ') Gecko/' + gecko + ' Firefox/' + version
    elif browser == 'ie':
        version = str(random.randint(1, 10)) + '.0'
        engine = str(random.randint(1, 5)) + '.0'
        option = random.choice([True, False])
        if option == True:
            token = random.choice(['.NET CLR', 'SV1', 'Tablet PC', 'Win64; IA64', 'Win64; x64', 'WOW64']) + '; '
        elif option == False:
            token = ''
        return 'Mozilla/5.0 (compatible; MSIE ' + version + '; ' + os + '; ' + token + 'Trident/' + engine + ')' 
Example 58
Source File: telemetry.py    From sublime-text-plugin with MIT License 5 votes vote down vote up
def get_user_agent():
    platforms = {
        'osx': 'Macintosh',
        'linux': 'X11; Linux',
        'windows': 'Windows NT 10.0; Win64; x64'
    }

    try:
        version = sublime.load_resource('/'.join(['Packages', __package__, 'VERSION']))
    except:
        version = '1.0.0'

    return 'Mozilla/5.0 (%s) EmmetTracker/%s' % (platforms.get(sublime.platform()), version.strip()) 
Example 59
Source File: utils.py    From cloudaux with Apache License 2.0 5 votes vote down vote up
def get_user_agent(**kwargs):
    """
    If there is a useragent, find it.

    Look in the keywords for user_agent. If not found,
    return get_user_agent_default
    """
    user_agent = kwargs.get('user_agent', None)
    if not user_agent:
        return get_user_agent_default()
    return user_agent 
Example 60
Source File: utils.py    From cloudaux with Apache License 2.0 5 votes vote down vote up
def get_user_agent_default(pkg_name='cloudaux'):
    """ 
    Get default User Agent String.

    Try to import pkg_name to get an accurate version number.
    
    return: string
    """
    version = '0.0.1'
    try:
        import pkg_resources
        version = pkg_resources.get_distribution(pkg_name).version
    except pkg_resources.DistributionNotFound:
        pass
    except ImportError:
        pass

    return 'cloudaux/%s' % (version)