Exemplo n.º 1
0
def zipbkp(directoryToZip):
    """
    Zips the duplicate Dumpfolder in the Temp Directory
    7zip has to be installed to use this function.
    """
    zipFileName = directoryToZip + ".zip"

    appPath = "C:\Program Files\\7-Zip"
    zApp = "7z.exe"
    zAction = 'a'
    zPass = '******'.format(param.ZIPW)
    zAnswer = '-y'
    zDir = directoryToZip
    progDir = os.path.join(appPath, zApp)

    if not os.path.isfile(progDir):
        clr.red("[X] Cannot Create .zip since 7zip is not installed!")
        sleep(3)
        return menu()

    print("[*] Trying to create .zip File, please wait...")
    cmd = [zApp, zAction, zipFileName, zPass, zAnswer, zDir]
    zipper = subprocess.Popen(cmd,
                              executable=progDir,
                              stderr=subprocess.STDOUT,
                              stdout=subprocess.PIPE)
    zipper.wait()
    clr.green("[*] Successfully created .zip File")
    return zipFileName
Exemplo n.º 2
0
def fm_upload():
    """
    This is a Function to upload a file to the ftp server
    """
    print("[*] Please Input the Full Path to the File (or drag it here)")
    filepath = input("   -> ")
    if is_file(filepath):
        filesize = os.path.getsize(filepath)
        with open(filepath, 'rb') as f:
            with tqdm(unit='blocks',
                      unit_scale=True,
                      leave=False,
                      miniters=1,
                      desc='[*] Uploading',
                      total=filesize) as tqdm_instance:
                ftp.storbinary(
                    'STOR ' + os.path.basename(filepath),
                    f,
                    2048,
                    callback=lambda block: tqdm_instance.update(len(block)))
        clr.green("[*] Upload Successful")
        sleep(2)
        items = getitems()
        return filemenu(items)
    else:
        clr.red("\n[X] Given Path is not a File")
        sleep(2)
        items = getitems()
        return filemenu(items)
Exemplo n.º 3
0
def menu():
    """
    Creates the Main Menu, we should be at the FTP Root Folder.
    Functions in this menu are prefixed mm_
    """
    mm_checkpwd()
    sleep(1)
    os.system("CLS")
    print("######################################")
    print("# {0:<35}#".format("       FTPhub - Main Menue"))
    print("# {0:<35}#".format(""))
    print("# {0:<15} {1:<12}    #".format("   Current Status:", status))
    print("# {0:<35}#".format(""))
    print("# {0:<35}#".format("Available commands:"))
    print("# {0:<35}#".format(""))
    print("# {0:<35}#".format("[ 0] Connect to Server"))
    print("# {0:<35}#".format("[ 1] Disconnect from Server"))
    print("# {0:<35}#".format("[ 2] Browse Root"))
    print("# {0:<35}#".format("[ 3] Browse Dumps"))
    print("# {0:<35}#".format("[ 4] Rotate Dumps"))
    print("# {0:<35}#".format("[ 5] Upload Dump"))
    print("# {0:<35}#".format("[ 6] Exit"))
    print("######################################")

    print("\n[*] Please select what you want to do:")
    action = input("	-> ")
    try:
        action = int(action)
    except ValueError:
        clr.red("\n[X] Wrong Input")
        return menu()
        pass
    print("")

    if action == 0:
        clr.yellow("[#] Connecting...")
        mm_connect()
    elif action == 1:
        mm_disconnect()
    elif action == 2:
        mm_browse("root")
    elif action == 3:
        mm_browse("dumps")
    elif action == 4:
        mm_rotate()
    elif action == 5:
        mm_upload()
    elif action == 6:
        ftpexit()
    else:
        clr.red("\n[X] Wrong Input")
        return menu()
Exemplo n.º 4
0
def cleanup(bkp_path, zipfile):
    """
    Cleans the Temp Directory from the Duplicate and the .zip File
    """
    print("[*] Trying to clean up, please wait...")
    try:
        shutil.rmtree(bkp_path)
        os.remove(zipfile)
    except PermissionError:
        clr.red(
            "[X] Error: Guess there's a Thumbs.db, try to manually Clean Up the Temp Directory."
        )
        pass
    clr.green("[*] Successfully Cleaned")
Exemplo n.º 5
0
def mm_connect():
    """
    Connects to a FTP-Server using the Info given in the param file
    USRN and PSWD can be None to interactively get the Info.
    THIS IS NOT SECURE and should be replaced with SFTP in the next Versions
    """
    """ monkeypatch https://stackoverflow.com/questions/44057732/connecting-to-explicit-ftp-over-tls-in-python """
    _old_makepasv = FTP.makepasv

    def _new_makepasv(self):
        host, port = _old_makepasv(self)
        host = self.sock.getpeername()[0]
        return host, port

    FTP.makepasv = _new_makepasv
    """ monkeypatch """

    global ftp
    ftp = FTP()
    ftp.connect(param.HOST, param.PORT)
    print("[*] Successfully established a Connection to [" + param.HOST +
          "] on PORT [" + str(param.PORT) + "]")
    if param.USRN is None:
        param.USRN = input("    Username: "******"    Password: "******"[*] Trying to Authenticate as [" + param.USRN + "]")
    try:
        ftp.login(user=param.USRN, passwd=param.PSWD)
        ftp.getwelcome()
    except Exception as e:
        errorcode = e.args[0][:3]
        # print('Errorcode: {}'.format(errorcode))
        if errorcode == "530":
            clr.red("[X] Error: Wrong Login credentials ||| Errorcode: " +
                    errorcode)
            return menu()
        else:
            clr.red(
                "[X] Error: undefined error, check the errorcode. ||| Errorcode: "
                + errorcode)
            return menu()
    clr.green("[*] Successfully authenticated")

    global status
    status = colored("{0:12}".format("Connected"), "green")

    if not qu and not qd:
        return menu()
Exemplo n.º 6
0
def mm_disconnect():
    """
    Disconnects you from a currently connected FTP-Server
    """
    global status
    if status != colored("{0:12}".format("Connected"), "green"):
        clr.red("[X] Not Connected to a Server")
        return menu()
    clr.yellow("[#] Disconnecting...")
    ftp.quit()
    clr.green("[*] Successfully disconnected")
    status = colored("{0:12}".format("Disconnected"), "red")
    sleep(1)
    if not qu and not qd:
        return menu()
Exemplo n.º 7
0
def printHand(
    title, showNum, hand
):  ## A template for showing which part (player or dealer) have which cards and points
    printText = title + "\n"  ## Printing the title
    count = 1
    totalVal = 0
    for card in hand:
        printText = printText + str(
            card)  ## Printing each card with comma separation
        if count + 1 == len(hand):
            printText = printText + " og "
        elif count < len(hand):
            printText = printText + ", "

        try:
            theCardVal = cardValue(
                card)  ## Numeric value of the card (J, Q, K = 10, Es = 1)
        except ValueError:
            print(
                clr.red("\n" + badChoise +
                        " Alle kort skal være numeriske (Ugyldig = " + card +
                        ")"))
            theCardVal = 0
        totalVal += theCardVal
        count += 1
    return (printText + "\nI ALT: " + str(totalVal))
    """
Exemplo n.º 8
0
def fm_delete():
    """
    Deletes a selected File or Directory using either ftp.delete or ftp.rmd
    """
    global selected
    print("\n[*] Are you sure you want to delete the selected item? (Y/N)")
    inp = input("	-> ")
    if inp == "Y" or inp == "y":
        if is_file(selected):
            ftp.delete(selected)
        else:
            ftp.rmd(selected)
        selected = "None"
        items = getitems()
        return filemenu(items)
    else:
        clr.red("\n[X] Aborted")
        sleep(1)
        items = getitems()
        return filemenu(items)
Exemplo n.º 9
0
def createbkp(root):
    """
    Creates a duplicate of the Dump folder in the Temp Directory
    Throws errors when there is a Thumbs.db blocking...
    """
    temp_dir = tempfile.gettempdir()
    date = datetime.datetime.now()
    ext = date.strftime("%Y-%m-%d")
    src = root + '\\Dump'
    dst = temp_dir + '\\' + ext + "_" + "Dump"
    print("[*] Trying to create a Duplicate, please wait...")
    try:
        monkey.copy(src, dst)
    except FileExistsError:
        try:
            shutil.rmtree(dst)
        except PermissionError:
            clr.red("[X] Error: Guess there's a Thumbs.db")
    clr.green("[*] Successfully created Duplicate")
    return dst
Exemplo n.º 10
0
def mm_rotate():
    """
    This Checks if there are more than 15 Dumps in the Dumps Folder
    if so, deletes the oldest till there are 15 Dumps.
    """
    if status != colored("{0:12}".format("Connected"), "green"):
        clr.red("[X] Not Connected to a Server")
        return menu()
    else:
        ftp.cwd("Dumps")
        items = getitems()
        items_n = len(items)
        maxdumps = 15
        if items_n > maxdumps:
            clr.red("More than {0} Dumps! [{1}]".format(maxdumps, items_n))
            todel_n = items_n - maxdumps
            # print(items[0:todel_n])
            print("\n[*] Are you sure you want to rotate the Dumps? (Y/N)")
            inp = input("	-> ")
            print("")
            if inp == "Y" or inp == "y":
                for item in items[0:todel_n]:
                    print("[*] Deleting: {0}".format(item))
                    ftp.delete(item)
                clr.green("\n[*] Deleted the {0} oldest Dumps".format(todel_n))
                sleep(5)
            else:
                clr.red("\n[X] Aborted")
        else:
            clr.green("[*] Less then {0} Dumps [{1}]! We Gucci!".format(
                maxdumps, items_n))
            sleep(3)

    return menu()
Exemplo n.º 11
0
def fm_open_dir(enumarated_items):
    """
    Opens a Sub-Directory by number, given numerated Files/Directorys of a directory
    after opening the Sub-Directory returning with a new filemenu
    """
    print("\n[*] Please select which directory to open:")
    sel = int(input("	-> "))
    thedir = enumarated_items[sel - 1][1]
    if is_file(thedir):
        clr.red("\n[X] Not a directory")
        sleep(2)
        items = getitems()
        return filemenu(items)
    else:
        try:
            ftp.cwd(thedir)
        except Exception as e:
            clr.red(e)
            sleep(2)
            pass
        items = getitems()
        selected = "None"
        return filemenu(items)
Exemplo n.º 12
0
def fm_download(qd=False):
    """
    Downloads a File from the remote server to the current working Directory
    tqdm is used to show the download progress.
    """

    global selected
    if qd:
        ftp.cwd("Dumps")
        items = getitems()
        selected = items[-1]

    if is_file(selected):
        filesize = ftp.size(selected)
        with open(selected, 'wb') as f:
            with tqdm(unit='blocks',
                      unit_scale=True,
                      leave=False,
                      miniters=1,
                      desc='[*] Downloading',
                      total=filesize) as tqdm_instance:
                ftp.retrbinary(
                    'RETR ' + selected,
                    lambda block: download_handle(block, f, tqdm_instance),
                    2048)
        clr.green("[*] Download Successful")
        sleep(2)
        items = getitems()

        if not qd:
            return filemenu(items)
    else:
        clr.red("\n[X] Can only download files")
        sleep(2)
        items = getitems()
        if not qd:
            return filemenu(items)
Exemplo n.º 13
0
def mm_upload():
    """
    Uploads a Dump Folder which lies next to the FTPhub pathwise.
    tqdm is used to show the upload progress.
    This function is based on functions wrote in savedum.py
    """
    if status != colored("{0:12}".format("Connected"), "green"):
        clr.red("[X] Not Connected to a Server")
        return menu()
    else:
        root = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
        bkp_path = createbkp(root)
        zipfile = zipbkp(bkp_path)

        filesize = os.path.getsize(zipfile)
        filename = os.path.basename(zipfile)
        ftp.cwd("Dumps")
        print("[*] Trying to transfer the Backup, please wait...")
        with open(zipfile, 'rb') as f:
            with tqdm(unit='blocks',
                      unit_scale=True,
                      leave=False,
                      miniters=1,
                      desc='[*] Uploading',
                      total=filesize) as tqdm_instance:
                ftp.storbinary(
                    'STOR ' + filename,
                    f,
                    2048,
                    callback=lambda sent: tqdm_instance.update(len(sent)))
        clr.green("[*] Successfully transfered the Backup")
        cleanup(bkp_path, zipfile)
        clr.magenta("[*] Upload-Function Successful")
        sleep(3)

        if not qu:
            return menu()
Exemplo n.º 14
0
def mm_browse(where):
    """
    Changes the Directory to the choosen, if no 'where' is defined,
    falling back to the Root FTP folder.
    """
    if status != colored("{0:12}".format("Connected"), "green"):
        clr.red("[X] Not Connected to a Server")
        return menu()
    else:
        if where == "root":
            # ftp.cwd("./")
            items = getitems()
            filemenu(items)
        elif where == "dumps":
            ftp.cwd("Dumps")
            items = getitems()
            filemenu(items)
        else:
            clr.red("[X] Path not specified, falling back to root dir")
            sleep(2)
            items = getitems()
            filemenu(items)

    return menu()
Exemplo n.º 15
0
def cardValue(theCard):  ## Calculate card value (1-10 = 1-10; J, Q, K = 10)
    if (theCard == "J" or theCard == "Q" or theCard == "K"):
        theCard = 10
    elif (theCard == "A"):
        theCard = 1

    try:
        theCard = int(theCard)  ## 1-10 including J, Q, K
    except ValueError:
        ## Error thrown is theCard is not either 1-10, J, Q og K
        print(
            clr.red(
                "\n" + badChoise +
                " Kortet skal være et J, Q, K eller et tal ml. 1-10, for at kunne vurderes."
            ))
        theCard = 0  ## Value is set to 0 for error handling

    if (0 < theCard and theCard <
            11):  ## If the card value is between 1-10, it'll be returned
        return theCard
    else:  ## If the card value fails
        return False
Exemplo n.º 16
0
def filemenu(items):
    """
    Creates the File Menu, given the items of the current working Directory
    Functions in this menu are prefixed fm_
    """
    global selected
    if selected != "None":
        if is_file(selected):
            selected_show = colored("{0:20}".format(selected), "cyan")
        else:
            selected_show = colored("{0:20}".format(selected), "magenta")
    else:
        selected_show = colored("{0:20}".format(selected), "yellow")
    os.system("CLS")
    print("######################################")
    print("# {0:<35}#".format("       FTPhub - File Menue"))
    print("# {0:<35}#".format(""))
    print("# {0:<10} {1:<25}  #".format("   Selected:", selected_show))
    print("# {0:<35}#".format(""))
    print("# {0:<35}#".format("Available commands:"))
    print("# {0:<35}#".format(""))
    print("# {0:<35}#".format("[ 0] Select File/Directory"))
    print("# {0:<35}#".format("[ 1] Create Directory"))
    print("# {0:<35}#".format("[ 2] Open Directory"))
    print("# {0:<35}#".format("[ 3] Rename Selected"))
    print("# {0:<35}#".format("[ 4] Delete Selected"))
    print("# {0:<35}#".format("[ 5] Download Selected"))
    print("# {0:<35}#".format("[ 6] Upload File"))
    print("# {0:<35}#".format("[ 7] Exit to Main Menue"))
    print("# {0:<35}#".format("[ 8] Exit"))
    print("# {0:<35}#".format(""))
    print("######################################")
    print("\n# Files:")
    enumarated_items = list(enumerate(items, 1))
    for count, element in enumerate(items, 1):

        # First Check if Element is Dir or File:
        if is_file(element):
            element = colored(element, "cyan")
        else:
            element = colored(element, "magenta")
        """ HIER MUSS DIE LOGIK REIN UM EIN ROTES X STATT EINER ZAHL ANZUZEIGEN """

        if count != 0 and count % 3 == 0:
            print("[{0:>3}] {1:<31}".format(count, element))
        else:
            print("[{0:>3}] {1:<31}".format(count, element), end="")

    print("\n#")
    print("\n[*] Please select what you want to do:")
    action = input("	-> ")
    try:
        action = int(action)
    except ValueError:
        clr.red("\n[X] Wrong Input")
        return filemenu(items)
        pass
    print("")

    if action == 0:
        fm_select(enumarated_items)
    elif action == 1:
        fm_create()
    elif action == 2:
        fm_open_dir(enumarated_items)
    elif action == 3:
        fm_rename()
    elif action == 4:
        fm_delete()
    elif action == 5:
        fm_download()
    elif action == 6:
        fm_upload()
    elif action == 7:
        selected = "None"
        return menu()
    elif action == 8:
        ftpexit()
    else:
        clr.red("\n[X] Wrong Input")
        return filemenu(items)
Exemplo n.º 17
0
import sys, random, pygame, clr, time

# CONSTANTS
X = 1366
Y = 768
d_OBJ = {
    "car": [0.75, 1, True],
    "bike": [0.5, 1.5, True],
    "truck": [1.2, 0.75, True]
}
crclr = clr.red()

# variables
x = int(X / 2 - int((X / 9) * d_OBJ["car"][0]) / 2)
y = Y - int((Y / 4.5) * d_OBJ["car"][0])
l = 3
add = 4
spd = 2
num = 0
j = 0
lst = []
rlst = [random.randrange(1, 3), random.randrange(3, 6)]

for i in range(2):
    r = random.choice(["car", "bike", "truck"])
    r1 = rlst[i]
    lst.append([r, r1, -int((X / 4.5) * d_OBJ[r][0]), clr.rdm()])
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

# Functions