コード例 #1
0
def test_utf8_declarations(content_type, body_decl):
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/project/',
        body=body_decl +
        b'<a href="../files/project-0.1.0-p\xC3\xBF42-none-any.whl">project-0.1.0-p\xC3\xBF42-none-any.whl</a>',
        content_type=content_type,
    )
    simple = PyPISimple('https://test.nil/simple/')
    assert simple.get_project_page('project') == ProjectPage(
        project='project',
        packages=[
            DistributionPackage(
                filename='project-0.1.0-p\xFF42-none-any.whl',
                project='project',
                version='0.1.0',
                package_type='wheel',
                url=
                "https://test.nil/simple/files/project-0.1.0-p\xFF42-none-any.whl",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
        ],
        last_serial=None,
        repository_version=None,
    )
コード例 #2
0
def test_redirected_project_page():
    responses.add(
        method=responses.GET,
        url='https://nil.test/simple/project/',
        status=301,
        headers={'Location': 'https://test.nil/simple/project/'},
    )
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/project/',
        body='<a href="../files/project-0.1.0.tar.gz">project-0.1.0.tar.gz</a>',
        content_type='text/html',
    )
    simple = PyPISimple('https://nil.test/simple/')
    assert simple.get_project_page('project') == ProjectPage(
        project='project',
        packages=[
            DistributionPackage(
                filename='project-0.1.0.tar.gz',
                project='project',
                version='0.1.0',
                package_type='sdist',
                url="https://test.nil/simple/files/project-0.1.0.tar.gz",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
        ],
        last_serial=None,
        repository_version=None,
    )
コード例 #3
0
def test_latin2_declarations(content_type, body_decl):
    # This test is deliberately weird in order to make sure the code is
    # actually paying attention to the encoding declarations and not just
    # assuming UTF-8 because the input happens to be valid UTF-8.
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/project/',
        body=body_decl +
        b'<a href="../files/project-0.1.0-p\xC3\xBF42-none-any.whl">project-0.1.0-p\xC3\xBF42-none-any.whl</a>',
        content_type=content_type,
    )
    simple = PyPISimple('https://test.nil/simple/')
    assert simple.get_project_page('project') == ProjectPage(
        project='project',
        packages=[
            DistributionPackage(
                filename=u'project-0.1.0-p\u0102\u017C42-none-any.whl',
                project='project',
                version='0.1.0',
                package_type='wheel',
                url=
                u"https://test.nil/simple/files/project-0.1.0-p\u0102\u017C42-none-any.whl",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
        ],
        last_serial=None,
        repository_version=None,
    )
コード例 #4
0
def _get_latest_versions(*, package_name, endpoint):
    pypi = PyPISimple(endpoint=endpoint)
    packages = pypi.get_project_files(package_name)
    try:
        latest_version = packages[-1].version
    except IndexError:
        # Package not found
        latest_version = None
    return (package_name, latest_version)
コード例 #5
0
ファイル: repos.py プロジェクト: roman-alexeev/bigrig
class SimpleRepo(PythonDistributionRepo):
    """ PEP-503 (aka pypi/simple) compliant repository """

    _username: t.Optional[str]
    _password: t.Optional[str]
    url: str
    client: PyPISimple

    def __init__(self, url: str, auth: t.Tuple[str, str] = None) -> None:
        self.url = url
        self._username, self._password = auth or (None, None)
        self.client = PyPISimple(endpoint=url)

    def project_files(self, project: t.Any) -> t.Any:
        return self.client.get_project_files(project)

    def download(self, project: t.Any, file: t.Any, dest: t.Any) -> t.Any:
        dists = [x for x in self.project_files(project) if x.filename == file]
        if not dists:
            raise NotAvailable(f"{file} is not available in project{project}")
        dist = dists[0]
        full_fname = os.path.join(dest, dist.filename)
        download_file(dist.url, full_fname)
        return full_fname

    def upload(self, project: t.Any, file: t.Any) -> t.Any:
        settings = twine.settings.Settings(
            repository_url=self.url, username=self._username, password=self._password
        )
        # TODO: use twine Repository object instead of command?
        twine_upload(settings, [file])
コード例 #6
0
def test_auth_custom_session():
    simple = PyPISimple(
        'https://test.nil/simple/',
        auth=('user', 'password'),
        session=requests.Session(),
    )
    assert simple.s.auth == ('user', 'password')
コード例 #7
0
def test_auth_override_custom_session():
    s = requests.Session()
    s.auth = ('login', 'secret')
    simple = PyPISimple(
        'https://test.nil/simple/',
        auth=('user', 'password'),
        session=s,
    )
    assert simple.s.auth == ('user', 'password')
コード例 #8
0
def get_hashes(dist_path: str,
               simple_url: str) -> Tuple[str, Union[str, None]]:
    """Get local and remote hashes for a distribution

    Returns a pair (local_hash, remote_hash).

    The algorithm for the hashes returned is based on the information provided
    by remote's Simple API. Based on PEP 503, the API can return any type of a
    hash, as long as it is supported by the builtin hashlib module.

    If the Simple API doesn't return any hash, raises UnsupportedAPIError.

    If the package couldn't be found, an md5 has of local package is returned
    along with a None, i.e. ('<md5>', None).
    """
    client = PyPISimple(simple_url)
    package = PackageFile.from_filename(dist_path, comment=None)
    name = package.safe_name

    filename = os.path.basename(dist_path)
    _, local_version, local_package_type = parse_filename(filename,
                                                          project_hint=name)

    remote_dists = client.get_project_files(name)

    for remote_dist in remote_dists:
        if (versions_equal(local_version, remote_dist.version)
                and remote_dist.package_type == local_package_type):
            break
    else:
        return hash_file(dist_path, hashlib.md5), None
    try:
        algo, remote_hash = url_hash_fragment(remote_dist.url)
    except Exception as exc:
        raise UnsupportedAPIError("API doesn't support hashes.") from exc

    if algo not in hashlib.algorithms_guaranteed:
        raise UnsupportedAPIError(f"API returned an unsupported hash: {algo}.")

    hashlib_cls = getattr(hashlib, algo)
    local_hash = hash_file(dist_path, hashlib_cls)

    return local_hash, remote_hash
コード例 #9
0
def test_project_hint_received():
    """
    Test that the argument to ``get_project_page()`` is used to disambiguate
    filenames
    """
    with (DATA_DIR / 'aws-adfs-ebsco.html').open() as fp:
        responses.add(
            method=responses.GET,
            url='https://test.nil/simple/aws-adfs-ebsco/',
            body=fp.read(),
            content_type='text/html',
        )
    simple = PyPISimple('https://test.nil/simple/')
    assert simple.get_project_page('aws-adfs-ebsco') == ProjectPage(
        project='aws-adfs-ebsco',
        packages=[
            DistributionPackage(
                filename='aws-adfs-ebsco-0.3.6-2.tar.gz',
                project='aws-adfs-ebsco',
                version='0.3.6-2',
                package_type='sdist',
                url=
                "https://files.pythonhosted.org/packages/13/b7/a69bdbf294db5ba0973ee45a2b2ce7045030cd922e1c0ca052d102c45b95/aws-adfs-ebsco-0.3.6-2.tar.gz#sha256=6eadd17408e1f26a313bc75afaa3011333bc2915461c446720bafd7608987e1e",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='aws-adfs-ebsco-0.3.7-1.tar.gz',
                project='aws-adfs-ebsco',
                version='0.3.7-1',
                package_type='sdist',
                url=
                "https://files.pythonhosted.org/packages/86/8a/46c2a99113cfbb7d6c089b2128ca9e4faaea1f6a1d4e17577fd9a3396bee/aws-adfs-ebsco-0.3.7-1.tar.gz#sha256=7992abc36d0061896a3f06f055e053ffde9f3fcf483340adfa675c65ebfb3f8d",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
        ],
        last_serial=None,
        repository_version=None,
    )
コード例 #10
0
def check_pip_public_repo(pkg):
    try:
        with PyPISimple() as client:
            version = 0
            requests_page = client.get_project_page(pkg['name'])
            if requests_page:
                return requests_page.repository_version
            else:
                return '0.0.0.0'
    except Exception as e:
        #print(f"PiP Error: {e}")
        return '0.0.0.0'
コード例 #11
0
ファイル: utils.py プロジェクト: etijskens/et-micc
def existsOnPyPI(package):
    """Does package exist already on PyPI?

    :return: True|False|Exception`

    In case of an exception, the result is inconclusive.
    """
    try:
        with PyPISimple() as client:
            requests_page = client.get_project_page(package)

    except Exception as e:
        return e

    return not requests_page is None
コード例 #12
0
def test_utf8_declarations(content_type, body_decl):
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/project/',
        body=body_decl +
        b'<a href="../files/project-0.1.0-p\xC3\xBF42-none-any.whl">project-0.1.0-p\xC3\xBF42-none-any.whl</a>',
        content_type=content_type,
    )
    simple = PyPISimple('https://test.nil/simple/')
    with pytest.warns(DeprecationWarning):
        files = simple.get_project_files('project')
    assert files == [
        DistributionPackage(
            filename=u'project-0.1.0-p\xFF42-none-any.whl',
            project='project',
            version='0.1.0',
            package_type='wheel',
            url=
            u"https://test.nil/simple/files/project-0.1.0-p\xFF42-none-any.whl",
            requires_python=None,
            has_sig=None,
            yanked=None,
        ),
    ]
コード例 #13
0
ファイル: pips.py プロジェクト: salesforce/DazedAndConfused
def check_pip_public_repo(pkg, registryurl=None):
    try:
        base_url = 'https://pypi.org/simple/'
        if registryurl:
            base_url = registryurl

        with PyPISimple(endpoint=registryurl) as client:
            version = 0
            requests_page = client.get_project_page(pkg['name'])
            if requests_page:
                return requests_page.repository_version
            else:
                return '0.0.0.0'
    except Exception as e:
        #print(f"PiP Error: {e}")
        return '0.0.0.0'
コード例 #14
0
def simple():
    package = input('\nPackage to be checked: ')
    try:
        with PyPISimple() as client:
            requests_page = client.get_project_page(package)
    except:
        print("\n SOMETHING WENT WRONG !!!!! \n\n",
              "CHECK INTERNET CONNECTION OR DON'T KNOW WHAT HAPPENED !!!\n")
    pkg = requests_page.packages[0]

    print(pkg)
    print(type(pkg))
    print('\nPackage_name: ', pkg, '\n')
    print('\nFilename: ' + pkg.filename)
    print('\nUrl: ' + pkg.url)
    print('\nproject: ' + pkg.project)
    print('\nversion: ' + pkg.version)
    print('\ntype: ' + pkg.package_type)
コード例 #15
0
ファイル: mirror.py プロジェクト: johanste/depper
class PyPiClient:
    def __init__(self, cache_path: "str"):
        self.client = PyPISimple()
        self.session = requests.Session()
        self.cache_path = cache_path

    @functools.lru_cache(maxsize=2)
    def list_projects(self):
        try:
            return self.load_cached_mirror()
        except:
            return list(self.client.get_projects())

    def new_projects(self):
        cached_projects = set(self.load_cached_mirror())
        found_projects = set(self.list_projects())

        return set.difference(cached_projects, found_projects)

    def download_mirror(self):
        projects = self.list_projects()

        with open(self.cache_path, 'w', encoding='utf-8-sig') as f:
            json.dump(projects, fp=f)

    def load_cached_mirror(self):
        with open(self.cache_path, 'r', encoding='utf-8-sig') as f:
            doc = json.load(fp=f)
        return doc

    @functools.lru_cache(maxsize=20)
    def extract_latest_project_file(self, project):
        project_files = self.client.get_project_files(project)
        max_version = packaging.version.parse('-1')
        max_file = None
        for project_file in project_files:
            if project_file.version is None:
                version = packaging.version.parse('0.0.0')
            else:
                version = packaging.version.parse(project_file.version)
            if project_file.package_type in ('sdist', 'wheel') and (
                    version > max_version or (version == max_version)
                    and project_file.package_type == 'wheel'):
                max_file, max_version = project_file, version
        if not max_file:
            raise MissingFilesError('Missing files?')
        return max_version, max_file

    @functools.lru_cache(maxsize=20)
    def extract_setup_py(self, project):
        version, project_file = self.extract_latest_project_file(project)
        response = self.session.get(project_file.url, stream=True, timeout=10)
        fp = io.BytesIO(response.content)

        if project_file.filename.endswith(
                '.zip') or project_file.filename.endswith('.whl'):
            zf = zipfile.ZipFile(fp)
            if project_file.filename.endswith('.zip'):
                nameinfos = list(
                    [ni for ni in zf.namelist() if ni.endswith('/setup.py')])
                if nameinfos:
                    return ('setup.py', version, zf.read(nameinfos[0]))
                raise MissingSetupError()
            else:
                nameinfos = list(
                    [ni for ni in zf.namelist() if ni.endswith('/METADATA')])
                if nameinfos:
                    return ('metadata', version, zf.read(nameinfos[0]))
                raise MissingManifestError()
        else:
            tf = tarfile.open(fileobj=fp)
            nameinfos = list(ni for ni in tf.getnames()
                             if ni.endswith('/setup.py'))
            if nameinfos:
                data = tf.extractfile(nameinfos[0])
                return ('setup.py', version, data.read())
            raise MissingSetupError()
コード例 #16
0
ファイル: repos.py プロジェクト: roman-alexeev/bigrig
 def __init__(self, url: str, auth: t.Tuple[str, str] = None) -> None:
     self.url = url
     self._username, self._password = auth or (None, None)
     self.client = PyPISimple(endpoint=url)
コード例 #17
0
def test_custom_session():
    s = requests.Session()
    simple = PyPISimple('https://test.nil/simple/', session=s)
    assert simple.s is s
    assert simple.s.auth is None
コード例 #18
0
def test_auth_new_session():
    simple = PyPISimple('https://test.nil/simple/', auth=('user', 'password'))
    assert simple.s.auth == ('user', 'password')
コード例 #19
0
 def list_packages(self):
     """Returns a list of the names of all packages on PyPI"""
     # The Warehouse devs prefer it if the Simple API is used for this
     # instead of the XML-RPC API.
     with PyPISimple() as ps:
         return ps.get_index_page().projects
コード例 #20
0
def test_get_project_url(endpoint, project):
    assert PyPISimple(endpoint).get_project_url(project) \
        == 'https://test.nil/simple/some-project/'
コード例 #21
0
def test_session(content_type):
    session_dir = DATA_DIR / 'session01'
    with (session_dir / 'simple.html').open() as fp:
        responses.add(
            method=responses.GET,
            url='https://test.nil/simple/',
            body=fp.read(),
            content_type=content_type,
            headers={"x-pypi-last-serial": "12345"},
        )
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/',
        body='This URL should only be requested once.',
        status=500,
    )
    with (session_dir / 'in-place.html').open() as fp:
        responses.add(
            method=responses.GET,
            url='https://test.nil/simple/in-place/',
            body=fp.read(),
            content_type=content_type,
            headers={"X-PYPI-LAST-SERIAL": "54321"},
        )
    responses.add(
        method=responses.GET,
        url='https://test.nil/simple/nonexistent/',
        body='Does not exist',
        status=404,
    )
    simple = PyPISimple('https://test.nil/simple/')
    assert simple.get_index_page() == IndexPage(
        projects=['in_place', 'foo', 'BAR'],
        last_serial='12345',
        repository_version='1.0',
    )
    assert simple.get_project_url('IN.PLACE') \
        == 'https://test.nil/simple/in-place/'
    assert simple.get_project_page('IN.PLACE') == ProjectPage(
        project='IN.PLACE',
        packages=[
            DistributionPackage(
                filename='in_place-0.1.1-py2.py3-none-any.whl',
                project='in_place',
                version='0.1.1',
                package_type='wheel',
                url=
                "https://files.pythonhosted.org/packages/34/81/2baaaa588ee1a6faa6354b7c9bc365f1b3da867707cd136dfedff7c06608/in_place-0.1.1-py2.py3-none-any.whl#sha256=e0732b6bdc2f1bfc4e1b96c1de2fbbd053bb2a9534547474a0485baa339bfa97",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='in_place-0.1.1.tar.gz',
                project='in_place',
                version='0.1.1',
                package_type='sdist',
                url=
                "https://files.pythonhosted.org/packages/b9/ba/f1c67fb32c37ba4263326ae4ac6fd00b128025c9289b2fb31a60a0a22f90/in_place-0.1.1.tar.gz#sha256=ffa729fd0b818ac750aa31bafc886f266380e1c8557ba38f70f422d2f6a77e23",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='in_place-0.2.0-py2.py3-none-any.whl',
                project='in_place',
                version='0.2.0',
                package_type='wheel',
                url=
                "https://files.pythonhosted.org/packages/9f/46/9f5679f3b2068e10b33c16a628a78b2b36531a9df08671bd0104f11d8461/in_place-0.2.0-py2.py3-none-any.whl#sha256=e1ad42a41dfde02092b411b1634a4be228e28c27553499a81ef04b377b28857c",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='in_place-0.2.0.tar.gz',
                project='in_place',
                version='0.2.0',
                package_type='sdist',
                url=
                "https://files.pythonhosted.org/packages/f0/51/c30f1fad2b857f7b5d5ff76ec01f1f80dd0f2ab6b6afcde7b2aed54faa7e/in_place-0.2.0.tar.gz#sha256=ff783dca5d06f85b8d084871abd11a170d732423edb48c53ccb68c55fcbbeb76",
                requires_python=None,
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='in_place-0.3.0-py2.py3-none-any.whl',
                project='in_place',
                version='0.3.0',
                package_type='wheel',
                url=
                "https://files.pythonhosted.org/packages/6f/84/ced31e646df335f8cd1b7884e3740b8c012314a28504542ef5631cdc1449/in_place-0.3.0-py2.py3-none-any.whl#sha256=af5ce9bd309f85a6bbe4119acbc0a67cda68f0ae616f0a76a947addc62791fda",
                requires_python=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4",
                has_sig=None,
                yanked=None,
            ),
            DistributionPackage(
                filename='in_place-0.3.0.tar.gz',
                project='in_place',
                version='0.3.0',
                package_type='sdist',
                url=
                "https://files.pythonhosted.org/packages/b6/cd/1dc736d5248420b15dd1546c2938aec7e6dab134e698e0768f54f1757af7/in_place-0.3.0.tar.gz#sha256=4758db1457c8addcd5f5b15ef870eab66b238e46e7d784bff99ab1b2126660ea",
                requires_python=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4",
                has_sig=None,
                yanked=None,
            ),
        ],
        last_serial='54321',
        repository_version='1.0',
    )
    assert simple.get_project_page('nonexistent') is None
コード例 #22
0
ファイル: mirror.py プロジェクト: johanste/depper
 def __init__(self, cache_path: "str"):
     self.client = PyPISimple()
     self.session = requests.Session()
     self.cache_path = cache_path
コード例 #23
0
ファイル: views.py プロジェクト: KudzaiMakufa/vulcheck
def vuln_check(request, lib_id=None):
    library = Library.objects.filter(id=lib_id).order_by('-id')
    f = open(library[0].library_list.path, "r")
    print("------------------")

    lines = f.readlines()

    data = []
    Issues = []
    Affected_Cve = []
    url_path = ""

    for line in lines:
        # here comes the vuln scanner logic
        sep = '=='
        stripped = line.split(sep, 1)[0]
        lib_version = line.split(sep, 1)[1]
        is_safe = False

        # print(line.strip())
        # print("-------without end-------")
        # print(line.split(sep, 1)[0])
        # print("------with end-----")

        # check updates and security
        with PyPISimple() as client:
            requests_page = client.get_project_page(stripped.strip())

        requests_page = client.get_project_page(stripped.strip())
        pkg_params = {}

        if (library[0].data_mode == 'application'):
            url_path = "dashboard/app_vulncheck.html"

            try:
                try:
                    vulners_api = vulners.Vulners(
                        api_key=
                        "4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ"
                    )
                    results = vulners_api.softwareVulnerabilities(
                        stripped.strip(), lib_version.strip())
                    # print(len(stripped.strip()))
                    # print(len(lib_version.strip()))
                    # results = vulners_api.softwareVulnerabilities("httpd", "1.3")
                    exploit_list = results.get('exploit')
                    vulnerabilities_list = [
                        results.get(key) for key in results
                        if key not in ['info', 'blog', 'bugbounty']
                    ]
                    print("vulneralibity type_____" +
                          vulnerabilities_list[0][0]['type'])
                    print(vulnerabilities_list[0][0]['title'])
                    Issues = vulnerabilities_list[0][0]

                except:
                    is_safe = True
                    print("safe")
                pkg = requests_page.packages[0]
                pkg_params = {
                    "name": pkg.project,
                    "current_version": lib_version.strip(),
                    "latest_version": pkg.version,
                    "digest": pkg.get_digests()['sha256'],
                    'url': pkg.url,
                    'is_signed': pkg.has_sig,
                    'is_safe': is_safe,
                    'issue_title': Issues
                }
            except:
                pkg_params = {
                    "name": stripped.strip(),
                    "current_version": lib_version.strip(),
                    "latest_version": "n/a",
                    "digest": "n/a",
                    'is_safe': is_safe,
                    'issue_title': Issues
                }

            # scan safety-db

        elif (library[0].data_mode == 'services'):
            url_path = "dashboard/service_vulncheck.html"
            pkg_params = {
                "name": stripped.strip(),
                "current_version": lib_version.strip(),
                "latest_version": "n/a",
                "digest": "n/a",
                'is_safe': is_safe
            }

        elif (library[0].data_mode == 'windows'):
            url_path = "dashboard/windows_vulncheck.html"
            try:
                vulners_api = vulners.Vulners(
                    api_key=
                    "4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ"
                )
                win_vulners = vulners_api.kbAudit(
                    os="Windows Server 2012 R2", kb_list=[lib_version.strip()])
                need_2_install_kb = win_vulners['kbMissed']
                affected_cve = win_vulners['cvelist']
                print("_____affected cve_____")
                print(affected_cve[0])
                Affected_Cve = affected_cve

            except:
                is_safe = True

            pkg_params = {
                "name": stripped.strip(),
                "kb_name": lib_version.strip(),
                "latest_version": "n/a",
                "digest": "n/a",
                'is_safe': is_safe,
                'affected_cve': Affected_Cve
            }
        else:
            pass

        data.append(pkg_params.copy())

    print("------------------")
    f.close()
    context = {"item": library[0], "data": data}
    return render(request, url_path, context)
コード例 #24
0
ファイル: views.py プロジェクト: KudzaiMakufa/vulcheck
def scan_all(request):

    url_path = "dashboard/scan_all.html"

    library = Library.objects.filter(
        data_mode="application").order_by('-id').first()
    print(library.data_mode)
    f = open(library.library_list.path, "r")
    print("------------------")
    lines = f.readlines()

    data = []
    Issues = []
    Affected_Cve = []

    for line in lines:
        # here comes the vuln scanner logic
        sep = '=='
        stripped = line.split(sep, 1)[0]
        lib_version = line.split(sep, 1)[1]
        is_safe = False

        # print(line.strip())
        # print("-------without end-------")
        # print(line.split(sep, 1)[0])
        # print("------with end-----")

        # check updates and security
        with PyPISimple() as client:
            requests_page = client.get_project_page(stripped.strip())

        requests_page = client.get_project_page(stripped.strip())
        pkg_params = {}

        if (library.data_mode == 'application'):

            try:
                try:
                    vulners_api = vulners.Vulners(
                        api_key=
                        "4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ"
                    )
                    results = vulners_api.softwareVulnerabilities(
                        stripped.strip(), lib_version.strip())
                    # print(len(stripped.strip()))
                    # print(len(lib_version.strip()))
                    # results = vulners_api.softwareVulnerabilities("httpd", "1.3")
                    exploit_list = results.get('exploit')
                    vulnerabilities_list = [
                        results.get(key) for key in results
                        if key not in ['info', 'blog', 'bugbounty']
                    ]
                    print("vulneralibity type_____" +
                          vulnerabilities_list[0][0]['type'])
                    print(vulnerabilities_list[0][0]['title'])
                    Issues = vulnerabilities_list[0][0]

                except:
                    is_safe = True
                    print("safe")
                pkg = requests_page.packages[0]
                pkg_params = {
                    "name": pkg.project,
                    "current_version": lib_version.strip(),
                    "latest_version": pkg.version,
                    "digest": pkg.get_digests()['sha256'],
                    'url': pkg.url,
                    'is_signed': pkg.has_sig,
                    'is_safe': is_safe,
                    'issue_title': Issues
                }
            except:
                pkg_params = {
                    "name": stripped.strip(),
                    "current_version": lib_version.strip(),
                    "latest_version": "n/a",
                    "digest": "n/a",
                    'is_safe': is_safe,
                    'issue_title': Issues
                }

            # scan safety-db

        data.append(pkg_params.copy())
        # print(data)

    # application level
    #
    #
    #
    #
    #
    #

    library = Library.objects.filter(
        data_mode="windows").order_by('-id').first()
    print(library.data_mode)
    f = open(library.library_list.path, "r")
    print("------------------")
    lines = f.readlines()

    windows = []
    Issues = []
    Affected_Cve = []

    for line in lines:
        # here comes the vuln scanner logic
        sep = '=='
        stripped = line.split(sep, 1)[0]
        lib_version = line.split(sep, 1)[1]
        is_safe = False

        # print(line.strip())
        # print("-------without end-------")
        # print(line.split(sep, 1)[0])
        # print("------with end-----")

        # check updates and security
        with PyPISimple() as client:
            requests_page = client.get_project_page(stripped.strip())

        requests_page = client.get_project_page(stripped.strip())
        windows_pkg_params = {}

        if (library.data_mode == 'windows'):

            try:
                vulners_api = vulners.Vulners(
                    api_key=
                    "4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ"
                )
                win_vulners = vulners_api.kbAudit(
                    os="Windows Server 2012 R2", kb_list=[lib_version.strip()])
                need_2_install_kb = win_vulners['kbMissed']
                affected_cve = win_vulners['cvelist']
                print("_____affected cve_____")
                print(affected_cve[0])
                Affected_Cve = affected_cve

            except:
                is_safe = True

            windows_pkg_params = {
                "name": stripped.strip(),
                "kb_name": lib_version.strip(),
                "latest_version": "n/a",
                "digest": "n/a",
                'is_safe': is_safe,
                'affected_cve': Affected_Cve
            }
            #  scan safety-db

        windows.append(windows_pkg_params.copy())
        # print(data)

    # f = open(library[0].library_list.path, "r")
    # print("------------------")

    # lines = f.readlines()

    # data = []
    # Issues = []
    # Affected_Cve = []
    # url_path = ""

    # for line in lines:
    #     # here comes the vuln scanner logic
    #     sep = '=='
    #     stripped = line.split(sep, 1)[0]
    #     lib_version = line.split(sep, 1)[1]
    #     is_safe = False

    #     # print(line.strip())
    #     # print("-------without end-------")
    #     # print(line.split(sep, 1)[0])
    #     # print("------with end-----")

    #     # check updates and security
    #     with PyPISimple() as client:
    #         requests_page = client.get_project_page(stripped.strip())

    #     requests_page = client.get_project_page(stripped.strip())
    #     pkg_params = {}

    #     if(library[0].data_mode == 'application'):
    #         url_path = "dashboard/app_vulncheck.html"

    #         try:
    #             try:
    #                 vulners_api = vulners.Vulners(api_key="4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ")
    #                 results = vulners_api.softwareVulnerabilities(stripped.strip(), lib_version.strip())
    #                 # print(len(stripped.strip()))
    #                 # print(len(lib_version.strip()))
    #                 # results = vulners_api.softwareVulnerabilities("httpd", "1.3")
    #                 exploit_list = results.get('exploit')
    #                 vulnerabilities_list = [results.get(key) for key in results if key not in ['info', 'blog', 'bugbounty']]
    #                 print("vulneralibity type_____"+vulnerabilities_list[0][0]['type'])
    #                 print(vulnerabilities_list[0][0]['title'])
    #                 Issues = vulnerabilities_list[0][0]

    #             except:
    #                 is_safe = True
    #                 print("safe")
    #             pkg = requests_page.packages[0]
    #             pkg_params = {"name":pkg.project , "current_version":lib_version.strip() , "latest_version":pkg.version ,"digest":pkg.get_digests()['sha256'] , 'url':pkg.url ,'is_signed':pkg.has_sig ,'is_safe':is_safe ,'issue_title':Issues}
    #         except:
    #             pkg_params = {"name":stripped.strip() , "current_version":lib_version.strip() , "latest_version":"n/a" ,"digest":"n/a",'is_safe':is_safe ,'issue_title':Issues}

    #          # scan safety-db

    #     elif(library[0].data_mode == 'services'):
    #         url_path = "dashboard/service_vulncheck.html"
    #         pkg_params = {"name":stripped.strip() , "current_version":lib_version.strip() , "latest_version":"n/a" ,"digest":"n/a" ,'is_safe':is_safe}

    #     elif(library[0].data_mode == 'windows'):
    #         url_path = "dashboard/windows_vulncheck.html"
    #         try:
    #             vulners_api = vulners.Vulners(api_key="4QIYDKA0NXPHUWXJNQYLISIZEZZH8FM25YNK0L518VOWJJEOWO81XGMH2KSL81KJ")
    #             win_vulners = vulners_api.kbAudit(os="Windows Server 2012 R2", kb_list=[lib_version.strip()])
    #             need_2_install_kb = win_vulners['kbMissed']
    #             affected_cve = win_vulners['cvelist']
    #             print("_____affected cve_____")
    #             print(affected_cve[0])
    #             Affected_Cve = affected_cve

    #         except:
    #             is_safe = True

    #         pkg_params = {"name":stripped.strip() , "kb_name":lib_version.strip() , "latest_version":"n/a" ,"digest":"n/a",'is_safe':is_safe ,'affected_cve':Affected_Cve}
    #     else:pass

    #     data.append(pkg_params.copy())

    # print("------------------")
    # f.close()
    messages.add_message(request, messages.INFO,
                         'Vulnerabilities found , Email send to admin')

    context = {"item": "show all", "windows": windows, "data": data}
    return render(request, url_path, context)