Ejemplo n.º 1
0
def importDocument(repoObj, repoPath):
    filePath = raw_input("Bitte den Dateipfad angeben: ");
    if(not os.path.isfile(filePath)):
        print("An der angegeben Stelle scheint keine Datei zu liegen. Bitte nochmal versuchen.");
        return importDocument(repoObj);
    
    try:
        os.makedirs(os.path.join(repoPath, "documents"))
    except OSError as e:
        if e.errno == errno.EEXIST and os.path.isdir(path):
            pass;
        else:
            raise;
        
    docIdFile = open(os.path.join(repoPath, "docid"), 'r+');
    docId = int(docIdFile.readline());
    docIdFile.seek(0);
    docIdFile.write("{}".format(docId + 1));
    docIdFile.truncate();
    docIdFile.close();
    
    newFileName = os.path.join("documents", "{}_{}".format(docId, os.path.basename(filePath)));
    shutil.copyfile(filePath, os.path.join(repoPath, newFileName));
    
    repoObj.index.add([os.path.join(repoPath, "docid"), newFileName]);
    
    importDocumentQuest = raw_input("Möchtest du noch ein Dokument importieren ([y]es/[n]o): ");
    if importDocumentQuest == 'y' or importDocumentQuest == 'yes':
        return importDocument(repoObj, repoPath);
    
    return 0;
Ejemplo n.º 2
0
def cracker():
    counter = 1
    objetivo = raw_input(
        "Ingresar el hash MD5: ")  # c893bad68927b457dbed39460e6afd62
    diccionario = raw_input("Ingresar ruta del diccionario a utilizar: "
                            )  # /home/nick/Documentos/Diccionario

    try:
        diccionario = open(diccionario, "r")
    except:
        print("\n Diccionario no encontrado")
        quit()

    os.system('clear')

    for password in diccionario:  # Toma cada password del diccionario.
        filemd5 = hashlib.md5(password.strip().encode('utf-8')).hexdigest()
        print("\n Intentando password numero %d: " % counter)

        counter += 1

        if objetivo == filemd5:
            print("\n Coincidencia encontrada: \n el password es: %s" %
                  password)
            break
        else:
            print("Password no encontrado.")
Ejemplo n.º 3
0
def escaner():
    ns = nmap.PortScanner()
    ip = raw_input("Introduzca la IP que desea escanear: \n")  # 192.168.0.1
    ns.scan(ip, '1-1024', '-v --version-all')

    os.system('clear')

    print(" -- INFORMACION RECOLECTADA --\n")
    print("Estadisticas generales: ")
    print(ns.scanstats())
    print("Informacion adicional: ")
    print(ns.scaninfo())
    print("Tipo de escaneo realizado: ")
    print(ns.command_line())

    print("\n Estado del HOST")
    print("***************")
    print(ns[ip].state())
    print("\n")

    print("Protocolos")
    print("**********")
    print(ns[ip].all_protocols())
    print("\n")

    print("Puertos abiertos")
    print("****************")
    print(ns.csv())
    print("\n")

    print("Nombre del host/router")
    print("**********************")
    print(ns[ip].hostname())
Ejemplo n.º 4
0
def echo_IMP():
    while 1:
        x = raw_input("IMP (write something) -- ")
        if x == 'quit':
            break
        else:
            print(x)
Ejemplo n.º 5
0
 def send_message(self, recipient):
     """Sending messages to a specific user"""
     message = raw_input("Your message:")
     times = int(
         input("How many times would you like to send the message:"))
     for i in range(times):
         self.send(Message(text=message),
                   thread_id=recipient.uid,
                   thread_type=ThreadType.USER)
         time.sleep(2)
Ejemplo n.º 6
0
def fun():
    # python raw_input()# 用来获取控制台的输入。
    # raw_input() # 将所有输入作为字符串看待,返回字符串类型。
    num1 = raw_input("请输入数字1:")
    num2 = raw_input("请输入数字2:")
    num3 = raw_input("请输入数字3:")

    try:
        data = []
        if int(num1) and int(num2) and int(num3):
            data.append(num1)
            data.append(num2)
            data.append(num3)
            data.sort(reverse=True)
    except Exception as e:
        print(e)
        print("您的输入有误,请重新输入!!!")
        return
    finally:
        return data
Ejemplo n.º 7
0
    def wrap():
        signal.signal(signal.SIGINT, original_sigint)

        try:
            if raw_input("\nReally quit? (y/n)> ").lower().startswith('y'):
                db.session.remove()
                db.drop_all()
                sys.exit(1)

        except KeyboardInterrupt:
            print("Ok ok, quitting")
            sys.exit(1)

        # restore the exit gracefully handler here
        signal.signal(signal.SIGINT, exit_gracefully)
Ejemplo n.º 8
0
def getAccountInt(text, fromAccount = None):
    result = None;
    
    try:
        result = int(raw_input(text));
        dirList[result];
    except ValueError:
        print("Bitte eine Zahl eingeben!");
        result = getAccountInt(text, fromAccount);
    except IndexError:
        print("Bitte eine Zahl im Bereich der existierenden Konten eingeben!");
        result = getAccountInt(text, fromAccount);
        
    if(result == fromAccount):
        print("Bitte nicht das gleiche Konto zweimal auswählen!");
        result = getAccountInt(text, fromAccount);
        
    return result;
Ejemplo n.º 9
0
 def find_user(self):
     """Find and choose a specific user"""
     users = []
     place = -1
     not_found = True
     # until a user is chosen
     while not_found:
         name = raw_input("Name: ")
         users = self.searchForUsers(name)
         # Printout 4 best matches
         for i, user in enumerate(users[:4], 1):
             print(f'#{i}    {user.name}')
         place = int(
             input(
                 "Enter number, in case the user is not listed, press enter and try their name again:"
             ))
         if 0 <= place <= 3:
             not_found = False
     return users[place - 1]
Ejemplo n.º 10
0
def menu():
    op = 0

    while op != 1:
        print("------------------------")
        print("     Herramientas: \n")
        print("1. Salir")
        print("2. Escaner")
        print("3. MD5 Hash Cracker")
        print("4. Sniffer")
        print("------------------------")

        op = int(raw_input("Ingresar opcion: "))

        if op == 2:
            escaner()
        if op == 3:
            cracker()
        if op == 4:
            sniffer()
Ejemplo n.º 11
0
def readTransferAmount():
    transferStr = raw_input("Bitte die Geldmenge zur Übertragung eingeben: ");
    transferStr = transferStr.replace(",", ".");
    
    result = None;
    indexDot = transferStr.find(".")
    
    try:
        if(transferStr.find(".") == -1):
            result = int(transferStr) * 100;
        elif(len(transferStr) - indexDot > 3):
            print("Es sind nur zwei Nachkommastellen unterstützt");
            return readTransferAmount();
        elif(len(transferStr) - indexDot == 2):
            result = int(transferStr.replace(".", "")) * 10;
        else:
            result = int(transferStr.replace(".", ""))
    except ValueError:
        print("Bitte einen richtigen Betrag eingeben!");
        result = readTransferAmount;
        
    return result; 
Ejemplo n.º 12
0
def execCommand(repoPath, command, remote):
    if(command == "create"):
        if(is_git_dir(os.path.join(repoPath, ".git"))):
            print("Git-Repo existiert bereits. Abbruch...")
            return 0;
  
        repoObj = git.Repo.init(repoPath, True);
        
        docFile = open(os.path.join(repoPath, "docid"), 'w');
        docFile.write("0");
        docFile.close();
        
        repoObj.index.add(["docid"]);
        repoObj.index.commit("Erstelle neues Buchhaltungsrepo.");
        
        print("Git-Repo wurde angelegt.");
        return 0;
    
    repoObj = git.Repo(repoPath);
    remoteExists = False;
    try:
        remoteObj = repoObj.remote(remote);
        remoteExists = True;
    except ValueError:
        pass;
    
    if len(repoObj.untracked_files) != 0 or repoObj.is_dirty():
        print("Im Git-Repo sind Aenderungen ohne Commit gemacht wurden. Achtung, Inkosistenzen sind möglich!")
        return 1;
    
    if(command == "transaction"):        
        if remoteExists:
            remoteObj.pull();
            
        genDirList(repoPath);
        printAccountStructure(repoPath);
        
        fromAccount = getAccountInt("Bitte das Startkonto eingeben: ");
        toAccount = getAccountInt("Bitte das Zielkonto eingeben: ", fromAccount);
        transferAmount = readTransferAmount();
        
        # Open start and end account file
        fromAccountFile = open(os.path.join(repoPath, dirList[fromAccount], "account"));
        toAccountFile = open(os.path.join(repoPath, dirList[toAccount], "account"));
        
        # Calculate new amounts
        fromAccountAmount = int(fromAccountFile.readline());
        fromAccountAmount -= transferAmount;
        toAccountAmount = int(toAccountFile.readline());
        toAccountAmount += transferAmount;
        
        # Close files and reopen them
        fromAccountFile.close();
        toAccountFile.close();
        fromAccountFile = open(os.path.join(repoPath, dirList[fromAccount], "account"), 'w');
        toAccountFile = open(os.path.join(repoPath, dirList[toAccount], "account"), 'w');
        
        # Write new amounts and close files
        fromAccountFile.write(str(fromAccountAmount));
        toAccountFile.write(str(toAccountAmount));
        fromAccountFile.close();
        toAccountFile.close();
        
        repoObj.index.add([os.path.join(dirList[fromAccount], "account"), os.path.join(dirList[toAccount], "account")]);
        
        importDocumentQuest = raw_input("Möchtest du ein Dokument importieren ([y]es/[n]o): ");
        if importDocumentQuest == 'y' or importDocumentQuest == 'yes':
            importDocument(repoObj, repoPath);
        
        transferMsg = raw_input("Bitte eine Meldung für die Transaktion angeben: ");
        repoObj.index.commit(transferMsg);
        
        if remoteExists:
            remoteObj.push();
            
        print("Transaktion erfolgreich ausgeführt");
        
    elif(command == "accounts"):
        printAccountStructure(repoPath);
        
    elif(command == "createaccount"):
        if remoteExists:
            remoteObj.pull();
        
        acctName = raw_input("Bitte den Namen des Kontos angeben (einzelne Ebene durch \"/\" abtrennen): ");
        acctNameList = acctName.split(sep="/");
        
        if(os.path.isfile(os.path.join(repoPath, os.path.sep.join(acctNameList), "account"))):
            print("Konto existiert bereits.")
            return 1;
        
        path = repoPath;
        for dirName in acctNameList:
            path = os.path.join(path, dirName);
            
            try:
                os.makedirs(path)
            except OSError as e:
                if e.errno == errno.EEXIST and os.path.isdir(path):
                    pass;
                else:
                    raise;
            
            pathFile = os.path.join(path, "account")
            if(not os.path.isfile(pathFile)):
                accountFile = open(pathFile, 'w');
                accountFile.write("0");
                accountFile.close();
                repoObj.index.add([pathFile]);
        
        repoObj.index.commit("Lege neues Konto \"{}\" an.".format(acctName));
        
        if remoteExists:
            remoteObj.push();
            
        print("Konto wurde erfolgreich angelegt.");
        
    elif(command == "list"):
        for commit in repoObj.iter_commits():
            dateTuple = time.localtime(commit.authored_date);
            commitMsg = commit.message.strip();
            
            print("{:04d}-{:02d}-{:02d} {:02d}:{:02d} -- {}".format(dateTuple[0], dateTuple[1], dateTuple[2],
                                                                    dateTuple[3], dateTuple[4], commitMsg));
            
            if len(commit.parents) > 0:                                                
                diffList = commit.parents[0].diff(commit, create_patch=True)
                
                if len(diffList) >= 2:
                    fromAccount = None;
                    toAccount = None;
                    differenceAmount = 0;
                    
                    for diffEntry in diffList:
                        if(diffEntry.deleted_file or diffEntry.new_file or diffEntry.renamed or diffEntry.a_path == "docid"):
                            break;
                        
                        diffStr = diffEntry.diff.decode("utf-8") 
                        
                        removedValue = re.search(r"^-(-?\d+)", diffStr, re.MULTILINE);
                        removedValue = int(removedValue.group(1));
                        
                        addedValue = re.search(r"^\+(-?\d+)", diffStr, re.MULTILINE);
                        addedValue = int(addedValue.group(1));
                        
                        difference = addedValue - removedValue;
                        if difference < 0:
                            fromAccount = os.path.dirname(diffEntry.a_path);
                        elif difference > 0:
                            toAccount = os.path.dirname(diffEntry.a_path);
                            differenceAmount = difference;
                        else:
                            print("Eine Differenz von 0. Da ist wohl was schief gegangen.");
                            exit(1);
                        
                        continue;
                    
                    differenceAmount = str(differenceAmount);
                    differenceAmount = differenceAmount[:len(differenceAmount)-2] + "." + differenceAmount[len(differenceAmount)-2:]
                    try:
                        print("{} --> {}: {}".format(fromAccount, toAccount, differenceAmount));
                    except Exception:
                        pass;
    
            print("")
    return 0;
Ejemplo n.º 13
0
def get_username():
    user = os.environ.get("spark_username", None)
    if user is None:
        user = raw_input("No username configured, Type username: ")
    return user
Ejemplo n.º 14
0
import libxml2
import subprocess
import os
import datetime
import time
from distlib.compat import raw_input

basedir = raw_input('full path to start dir: ')
pwd = os.getcwd()
success_path = os.path.join(pwd, "success.txt")
error_path = os.path.join(pwd, "error.txt")

if not basedir:
    print('please give a start path as argument!')
    quit()
#clear files
with open(success_path, "w"):
    pass
with open(error_path, "w"):
    pass
for root, dirs, files in os.walk(basedir):
    for file in files:
        if file.endswith(".xml"):
            file_path = os.path.join(root, file)
            directory = root
            os.chdir(directory)
            try:
                doc = libxml2.parseFile(file_path)
                context = doc.xpathNewContext()
                context.xpathRegisterNs("xlink",
                                        "http://www.w3.org/1999/xlink")
Ejemplo n.º 15
0
from distlib.compat import raw_input

a = raw_input("Enter a string:")

if a:

    print(a.title())
Ejemplo n.º 16
0
#         <suite>
#     return 0
#
# while_FP = lambda: (<cond> and while_block()) or while_FP()
# while_FP()

print('###### imperative version of "echo()" ######')


def echo_IMP():
    while 1:
        x = raw_input("IMP (write something) -- ")
        if x == 'quit':
            break
        else:
            print(x)


echo_IMP()


# utility function for "identity with side-effect"
def monadic_print(x):
    print(x)
    return x


print('###### FP version of "echo()" #####')
echo_FP = lambda: monadic_print(raw_input("FP (write something) -- ")
                                ) == 'quit' or echo_FP()
echo_FP()
from distlib.compat import raw_input

n = int(input())
array = [int(x) for x in raw_input().split()]
array = sorted(array)


def pickingNumber(array):
    count = 0
    i = 0
    while i < len(array):
        item = array[i]
        for j in range(i+1,len(array)):
            dif = abs(array[i] - array[j])
            if dif == 1:
                count += 1
            else:
                pass
        i += 1
    print(count)


pickingNumber(array)
Ejemplo n.º 18
0
from distlib.compat import raw_input

persons_name = raw_input("Escreva o nome da pessoa.\n")
print(persons_name + " escreveu o nome")
Ejemplo n.º 19
0
def fill_cards(bar: tqdm, driver, root):

    if not command_line_args.skipsetup:
        print(
            "Configuring a new order. If you'd like to continue uploading cards to an existing project,"
            "start this program with the -skipsetup option and follow the printed instructions."
            "example: ./autofill -skipsetup")
        configure_order(driver)
    else:
        print(
            "Please sign in and select an existing project to continue editing."
            "Once you've signed in, return to the script execution window and press ENTER."
        )
        driver.get("https://www.makeplayingcards.com/login.aspx")
        raw_input("Press Enter to continue...")

    insert_card_fronts(bar, driver)

    # Page through to backs
    driver.execute_script("javascript:oDesign.setNextStep();")
    try:
        alert = driver.switch_to.alert
        alert.accept()
    except NoAlertPresentException:
        pass

    # Page over to the next step from "add text to fronts"
    wait(driver)
    try:
        driver.find_element_by_id("closeBtn").click()
    except NoSuchElementException:
        pass
    driver.execute_script("javascript:oDesign.setNextStep();")

    # Select "different images" for backs
    wait(driver)
    switch_to_frame(driver, "sysifm_loginFrame")

    if len(order.backs) == 0:
        # Same cardback for every card
        driver.execute_script("javascript:setMode('ImageText', 1);")
        driver.switch_to.default_content()

        # Pull the common cardback card info off the queue, then upload and insert it
        curr_card = q_cardback.get()
        if curr_card != ("", ""):
            pid = upload_card(driver, curr_card[0])
            insert_card(driver, pid, [0])
        bar.update(1)

    else:
        # Different cardbacks
        driver.execute_script("javascript:setMode('ImageText', 0);")
        driver.switch_to.default_content()

        # Insert specified cardbacks
        cards_with_backs = []
        for i in range(0, len(cardsinfo_back)):
            curr_card = q_back.get()
            if curr_card != ("", ""):
                pid = upload_card(driver, curr_card[0])
                insert_card(driver, pid, curr_card[1])

            # Keep track of the back slots we've filled
            cards_with_backs.extend(curr_card[1])
            bar.update(1)

        # Determine which slots require the common cardback
        # TODO: Is there a more efficient way to do this? Look at DOM instead?
        total_cards = order.details.quantity
        cards_needing_backs = [
            x for x in range(0, total_cards) if x not in cards_with_backs
        ]

        # Upload and insert the common cardback
        curr_card = q_cardback.get()
        if curr_card != ("", ""):
            pid = upload_card(driver, curr_card[0])
            insert_card(driver, pid, cards_needing_backs)
        bar.update(1)

    # Page through to finalise project
    driver.execute_script("javascript:oDesign.setNextStep();")
    try:
        alert = driver.switch_to.alert
        alert.accept()
    except NoAlertPresentException:
        pass
    wait(driver)
    time.sleep(1)
    driver.execute_script("javascript:oDesign.setNextStep();")

    # Page over to the next step from "add text to backs"
    wait(driver)
    driver.execute_script("javascript:oDesign.setNextStep();")
Ejemplo n.º 20
0
from distlib.compat import raw_input

if __name__ == '__main__':
    n = int(raw_input())
    arr = map(int, raw_input().split())
    set_temp = set(arr)
    final_ar = list(set_temp)
    final_ar.sort()
    print(final_ar[-2])
from distlib.compat import raw_input

inp = raw_input()
for i in inp:
    i.sorted(reverse=True)
Ejemplo n.º 22
0
#!/usr/bin/python3.4
import subprocess
import os
import datetime
import time
from distlib.compat import raw_input
from lxml import etree



basedir = raw_input('full path to start dir: ')
#basedir = '/home/tina/onderwijs/ARA_G05607_1915-02-08_01_000/'
pwd = os.getcwd()
success_path = os.path.join(pwd, "success.txt")
error_path = os.path.join(pwd, "error.txt")

if not basedir:
    print('please give a start path as argument!')
    quit()
#clear files
with open(success_path, "w"):
    pass
with open(error_path, "w"):
    pass
for root, dirs, files in os.walk(basedir):
   # print ("dirs: %s files: %s" % (dirs, files))
    for file in files:
        if file.endswith("mets.xml"):
            file_path = os.path.join(root, file)
            directory = root
            os.chdir(directory)
Ejemplo n.º 23
0
#Números primos
from distlib.compat import raw_input

numero_leido = raw_input("Ingrese un numero: ")
numero = int(numero_leido)
contador = 0
for i in range(1,numero+1):
    if (numero% i)==0:
        contador = contador + 1

if contador==2:
    print("El numero SI es primo")
else:
    print("El numero NO es primo")