0

I have the following two PY(Python) files that represent one project (in PyCharm):

antivirus.py

import requests
import json

try:
    from colors import red, green
except ImportError:
    def nothing(val):
            return val
    global red
    global green
    red = green = nothing


class api():
    def __init__(self, verbose=False):
        self.verbose = verbose
        #self.api = "ASWGFHAHJGASDAGHHKHEGWARJLQGEIQYEQWIUAGHDASD"
        self.api = "INSERT YOUR VIRUS TOTAL PUBLIC API HERE"
        self.baseurl = "https://www.virustotal.com/vtapi/v2/"

    #Print results from a file/url
    def print_scan_results(self, results):
        if results['response_code'] == 0:
            print ("Url/file not found, or scanned yet. Try again later")
        else:
            print ("""Permalink: %s \nScandate: %s \n"""
                   % (results['permalink'], results['scan_date']))
            for i in results['scans']:
                print("%s: " % i),
                if (str(results['scans'][i]['detected']) == "False"):
                    print (green("Clean"))
                else:
                    print (red("Malicious -- %s"
                               % str(results['scans'][i]['result'])))
        if self.verbose:
            print
            print (results)

    #Print reply for a url scan request
    def print_url_scan(self, results):
        print ("""Permalink: %s \nURL: %s \nDate: %s \nID: %s"""
               % (results['permalink'], results['resource'],
                  results['scan_date'], results['scan_id']))
        if self.verbose:
            print
            print (results)

    #Print reply for a file scan request
    def print_file_scan(self, results):
        print (results['verbose_msg'])
        print ("Permalink: %s" % results['permalink'])
        if self.verbose:
            print
            print (results)

    #Checking if any `networking` related errors occured
    def check_results(self, r):
        try:
            results = r.json()
        except ValueError:
            print ("URL not found, malformed URL or invalid API token")
            exit(1)
        return results

    #Function to get results of a scanned file/url
    def results(self, mode, resource):
        url = self.baseurl + "%s/report" % mode
        values = {"resource": resource,
                  "apikey": self.api}

        r = requests.post(url, values)
        results = self.check_results(r)
        return results

    #Scan a url
    def scanurl(self, resource):
        url = self.baseurl + "url/scan"
        values = {"url": resource,
                  "apikey": self.api}

        r = requests.post(url, values)
        results = self.check_results(r)
        return results

    #Scan a file
    def sendfile(self, filename):
        url = self.baseurl + "file/scan"
        try:
            f = open(filename, "rb")
        except:
            print ("Could not open file")

        files = {"file": f}
        values = {"apikey": self.api}
        r = requests.post(url, values, files=files)
        results = self.check_results(r)
        return results

wrapper.py

from antivirus import api
import argparse
import hashlib


def parse_options():
    parser = argparse.ArgumentParser()
    parser.add_argument("-u", "--url", dest="url",
                        help="URL to scan")
    parser.add_argument("-F", "--results-file", dest="sfile",
                        help="Get report of previously scanned file. If the "
                        "given filename cannot be found/opened, we'll assume "
                        "it's a hash.")
    parser.add_argument("-U", "--results", dest="url_res",
                        help="Get report of previously scanned url")
    parser.add_argument("-f", "--file", dest="file",
                        help="Scan file")
    parser.add_argument("-v", "--verbose", default=False, action="store_true",
                        dest="verbose", help="Print complete reply")
    return parser.parse_args()


def main():
    arg = parse_options()
    vt = api(arg.verbose)

    #Scan url
    if arg.url:
        vt.print_url_scan(vt.scanurl(arg.url))

    #Get results of file
    elif arg.sfile:
        try:
            f = open(arg.sfile, "r")
            fhash = hashlib.sha256()
            fhash.update(str(f.read()))
            value = fhash.hexdigest()
        except:
            value = arg.sfile
        vt.print_scan_results(vt.results("file", value))

    #Get results of url
    elif arg.url_res:
        vt.print_scan_results(vt.results("url", arg.url_res))

    #Send file for scan
    elif arg.file:
        vt.print_file_scan(vt.sendfile(arg.file))


if __name__ == "__main__":
    exit(main())

When I run one of these files (e.g. wrapper.py), nothing happens. There are no errors, but nothing happens.

How can I test the functionality of this project?

That is, how to run this program?

Is it possible to run it as a console application?

Also, I can't type in console. How to enable this? I am using Windows 7.

  • 1
    You could try calling it from console in pycharm (like `python[3] project.py [-args]`) – Ryan Schaefer Mar 18 '18 at 23:17
  • @Ryan Schaefer, How would the user call the application? It shouldn't be complicated. – user9408826 Mar 18 '18 at 23:18
  • @Ryan Schaefer, ... also, where is that console in PyCharm? I can't type anything in the space below code (which I assume is a console). – user9408826 Mar 18 '18 at 23:20
  • It doesn’t do anything since I assume when you run it you don’t pass in the arguments required.. since you want run this script on pycharm take a look at this SO answer on how to: [link](https://stackoverflow.com/questions/33102272/pycharm-and-sys-argv-arguments) [link2](https://stackoverflow.com/questions/27952331/debugging-with-pycharm-terminal-arguments) – gyx-hh Mar 18 '18 at 23:29
  • @Hamza Haider, Ok, but how to enable this to work as an application? User wont enter arguments, he/she will use simplified interface (or console in this case). How to enable this for simple user? – user9408826 Mar 18 '18 at 23:33
  • Im not convinced you even wrote this code. This code is written to take in arguments so everytime you run the script you need to specify the argument or have default arguments if they’re not defined. So if that’s not the behaviour you want re-write the code to work as an application you want it to. But my answe above answered your question on how to run the script ! – gyx-hh Mar 18 '18 at 23:40
  • @Hamza Haider , I can't even type in the console. – user9408826 Mar 19 '18 at 00:00

1 Answers1

0

Just Right click on the file and hit Run or in PyCharm Editor, see right side of the editor and locate the run symbol, you will find that at the left side of run symbol there is a box, and in that box you have to select the file name you want to execute, as in your case selece wrapper.py and hit Run Symbol.

enter image description here

MrBhuyan
  • 151
  • 2
  • 17
  • I explained that doesn't do anything. – user9408826 Mar 18 '18 at 23:22
  • You should remove the in statement and try to run the main() to start the execution and you can trace your program flow, in your case your main() is not going to execute, so make it happen first. – MrBhuyan Mar 18 '18 at 23:33