def handle_key(self, tokens): (ttype, val, curline) = tokens.get() if ttype == T_STRING: name = val.replace('"', '') key = Key(name) (ttype, val, curline) = tokens.get() if ttype != T_LBRACE: bail('? need opening brace for "key" defn (%d: %s)' % (ttype, val)) (ttype, val, curline) = tokens.get() while ttype != T_RBRACE: if ttype == T_KEYWORD and val == 'algorithm': (ttype, val, curline) = tokens.get() if ttype == T_KEYWORD or ttype == T_NAME: key.setAlgorithm(val) else: bail('? bogosity after "algorithm" (%d: %s)' % (ttype, val)) elif ttype == T_KEYWORD and val == 'secret': (ttype, val, curline) = tokens.get() if ttype == T_STRING: s = val.replace('"','') key.setSecret(s) else: bail('? bogosity after "secret" (%d: %s)' % (ttype, val)) elif ttype == T_SEMI: pass (ttype, val, curline) = tokens.get() else: bail('? need to have a string after "key" (%d: %s)' % (ttype, val)) self.named.addKey(key) (ttype, val, curline) = tokens.get() if ttype != T_SEMI: bail('? need a semicolon to end the "key" (%d: %s)' % (ttype, val)) return
def textInterface(): if not textMode: ft = FixedTerminal([ Field("Enter a key: ", default="c"), Field("Enter text to encrypt: ", default="b") ], pygame, InterfaceFont, screen) while True: if textMode: try: text1 = getTextInput("\n\nEnter a key:") if text1 == "": return text2 = getTextInput("Enter text to encrypt:") if text2 == "": return except EOFError: exit() else: ft.getInputs() text1, text2 = ft.get_values() text1, text2 = text1[:5], text2[:6] num1 = Key.fromCharArr(text1, charSet) num2 = Key.fromCharArr(text2, charSet) overshoot = 7 solver = Solver(num1, num2, overshoot) pollEvents() def peek(path): clear() drawPath(path, solver.upperBound) pollEvents() solver.solve(preview=peek) pollEvents() clear() if solver.done: investigate(solver, alphabet=charSet)
def __init__(self, x, y, platforms, width=30, height=50, mass=1): pygame.sprite.Sprite.__init__(self) self.currentSprite = 0 self.lastTicks = 0 self.walking = False self.load_images() self.image = self.standingRight[0] self.rect = self.image.get_rect() self.rect.center = (x, y) self.lightRect = lightAlpha.get_rect() self.lightRect.center = (x, y) #self.rect.left = x-15 #self.rect.right = x+15 #self.rect.bottom = y-25 #self.rect.top = y+25 #print(self.rect) #print(self.rect.top) #print(self.rect.bottom) self.width = width self.height = height self.platforms = platforms self.mass = mass self.vel = vec(0, 0) self.acc = vec(0, 0) self.position = vec(x, y) self.platforming = True self.isJump = False self.hasKey = False self.k = Key(-100, -100, 50) self.isRight = True pygame.mixer.init() self.move_sound = pygame.mixer.Sound('Audio/Slow_Walk.ogg')
def setup_seed(config): if os.path.isfile("./seed.txt"): seed = Key.load_seed("./seed.txt") else: seed = Key.create_seed() priv, pub = Key.create(config["password"], seed) return priv, pub
def getVid(): aws_access_key_id = Key.getAws_access_key_id() aws_secret_access_key = Key.getAws_secret_access_key() def upload_to_aws(local_file, bucket, s3_file): s3 = boto3.client( 's3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) try: s3.put_object(Bucket="videosformturk", Key=(directory + '/')) s3.upload_file(local_file, bucket, s3_file, ExtraArgs={ "ContentType": mimetypes.MimeTypes().guess_type(s3_file)[0] }) print("Upload Successful of " + s3_file) return True except NoCredentialsError: print("Credentials not available") return False uploaded = [] db = pymysql.connect("localhost", "utente", "pass123", "dbmysql") # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sqlSelect = "SELECT MAX(FOLDER) FROM metavideo" try: cursor.execute(sqlSelect) i = cursor.fetchall() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() if i[0][0] == 0: directory = "video" else: s = i[0][0] directory = "video" + str(s) videos = os.listdir(directory) for vid in videos: if upload_to_aws(directory + "/" + vid, 'videosformturk', directory + "/" + vid): uploaded.append( "https://videosformturk.s3.eu-central-1.amazonaws.com/" + directory + "/" + vid) tuple = [] tuple.append(uploaded) tuple.append(directory) return tuple
def send_false_transaction(): message, signature = Key.sign(priv, "Pay_false,0.14," + Key.hex(pub) + "," + Key.hex(pub2) + "," + str(time.time()) + "," + "for the banana") transaction = Transaction.create(message, signature) json_transaction = transaction.json().encode('utf-8') req = urllib.request.Request(url=config["protocol"] + "://localhost:" + str(config["port"]) + "/post_transaction", data=json_transaction, method='POST') with urllib.request.urlopen(req, timeout=5, context=ssl._create_unverified_context()) as f: return f.read()
def tpost(ImgPath, STR): CONSUMER_KEY = Key.twiter()[0] CONSUMER_SECRET = Key.twiter()[1] ACCESS_KEY = Key.twiter()[2] ACCESS_SECRET = Key.twiter()[3] twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) photo = open(ImgPath, 'rb') response = twitter.upload_media(media=photo) twitter.update_status(status=STR, media_ids=[response['media_id']])
def check_key(self, attribute, temp_keys): is_super_key = False for key in temp_keys: if set(set(key.Attributes)).issubset(attribute): is_super_key = True break if not is_super_key: if set(self.compute_attribute_closure(self.FDs, attribute)) == set(self.Attributes): key = Key() key.Attributes = attribute[:] temp_keys.append(key)
def Mine(vein): pos = Character.GetPos() while pos.x < (vein.x - 50) or pos.x > (vein.x + 50): Character.AMoveX(vein.x) pos = Character.GetPos() Character.StopMove() print("Pressing mining key") time.sleep(.25) Key.Press(0x20) time.sleep(.1) Key.Press(0x20) time.sleep(.1) Key.Press(0x20) time.sleep(4)
def enterbramble(): if fieldid != 940200216: rush(450005220) time.sleep(1) Character.Teleport(-850, 75) time.sleep(1) Key.Press(0x26)
def OnKeyDown(self, e): k = e.GetKeyCode() if k == wx.WXK_ESCAPE and self.frame.IsFullScreen(): self.ShowFullScreen(False) return True else: key_code = Key.KeyCodeFromWx(e) if wx.GetApp().input_mode_object.OnKeyDown(key_code): return True if k == wx.WXK_DELETE: if cad.GetNumSelected() > 0: self.DeleteMarkedList() elif k == wx.WXK_RETURN: if self.inMainLoop: self.ExitMainLoop() self.Repaint() elif k == ord('Z'): if e.ControlDown(): if e.ShiftDown(): self.OnRedo(e) else: self.OnUndo(e) elif k == ord('X'): if e.ControlDown(): self.OnCut(e) elif k == ord('C'): if e.ControlDown(): self.OnCopy(e) elif k == ord('V'): if e.ControlDown(): self.OnPaste(e) else: return False return True
def compute_candidate_keys(self): temp_keys = [] left = [] # contains attributes appear 'only' on the left hand sides of FDs # 'left' attributes must be part of every key middle = [] # contains attributes appear on both left and right hand sides of FDs # 'middle' attributes may or may not part of a key right = [] # contains attributes appear 'only' on the right hand sides of FDs # 'right' attributes are not part of any key for fd in self.FDs: left += fd.leftHandSide right += fd.rightHandSide middle = list(set(left).intersection(set(right))) left = list(set(left)-set(middle)) right = list(set(right)-set(middle)) if len(left) > 0: # check keys in left list self.check_attribute_list(left, temp_keys) # if keys still not found, check keys in left list with middle list combinations if len(temp_keys) == 0: r1 = 1 while r1 != (len(left)+1): for left_combination in itertools.combinations(left, r1): r2 = 1 while r2 != (len(middle)+1): for middle_combination in itertools.combinations(middle, r2): self.check_key(list(left_combination) + list(middle_combination), temp_keys) #if len(temp_keys) > 0: # break r2 += 1 #if len(temp_keys) > 0: # break r1 += 1 else: # check keys in middle list self.check_attribute_list(middle, temp_keys) if len(temp_keys) == 0: key = Key() # Basic Key U->U: key.Attributes = self.Attributes temp_keys.append(key) self.Keys = temp_keys[:]
def doSS(): Terminal.SetCheckBox("bot/si_no_wait", True) #Terminal.SetCheckBox("main/boss_freeze", True) Terminal.SetCheckBox("Auto Buff", False) for i in range(roundsPerRun): killCount = 0 mobsKilled = [] while killCount < 5: if not GameState.IsInGame() or not isInSS(): print("Not in SS!") break curMob = "" for mobID in mobArray: mob = Field.FindMob(mobID) if mob.valid and mob not in mobsKilled: curMob = mob mobsKilled.append(mob) break if curMob != "": SunCat.KamiTP(curMob.x, curMob.y) time.sleep(killTime) Key.Press(npcChatKey) time.sleep(0.2) Key.Press(npcChatKey) time.sleep(waitTime) killCount += 1 else: print("No mobs left!") time.sleep( 3) #Wait for mobs to respawn - this should never be hit SunCat.KamiTP(baseX, baseY) time.sleep(roundWaitTime) Terminal.SetCheckBox("bot/si_no_wait", False) #Terminal.SetCheckBox("main/boss_freeze", False) Terminal.SetCheckBox("Auto Buff", True) SunCat.StopTP() print("Finished!")
def attackAuto(skillid,on): attack_key = 0x44 Key.Set(attack_key,1,skillid) Terminal.SetCheckBox("Skill Injection", False) Terminal.SetCheckBox("Melee No Delay",False) Terminal.SetCheckBox("Auto Attack", on) Terminal.SetComboBox("AttackKey",33) Terminal.SetSpinBox("autoattack_spin",100)
def SpamKey(key): if key == "down": key = 0x28 elif key == "alt": key = 0x12 elif key == "ctrl": key = 0x11 elif key == "up": key = 0x26 delay = 0 for i in range(5): delay += 0.2 time.sleep(delay) Key.Down(key) time.sleep(0.1) Key.Up(key)
def get_keys_callback(event): if event.char == '`': window.destroy() return if not (event.char in game_keys) and type(listbox.focus_get()) is tk.Listbox: key = Key.Key(event.char) game_keys.append(key) listbox.insert(tk.END, key)
def generateKeyPairs(self): files = [('Text Document', '*.txt')] f = fd.asksaveasfile(title = "Select directory", initialfile='keypairs', filetypes=files, defaultextension=files) if f is None: return [private, public] = k.genKeyPairs() text = "private_key = "+str(private)+"\npublic_key = "+str(public) f.write(text) f.close()
def bind_skill(skill): oPacket = Packet.COutPacket(CP_UserHyperSkillUpRequest) oPacket.Encode4(int(time.monotonic() * 1000)) oPacket.Encode4(skill[0]) Packet.SendPacket(oPacket) Packet.WaitForRecv(LP_ChangeSkillRecordResult, 10000) print("Received {}.".format(skill[0])) Key.Set(skill[1], KeyType.Skill, skill[0])
def read_options(filename): with open(str(filename.name), 'r') as json_file: data = json.load(json_file) if "end_game_img" in data.keys(): data["end_game_img"] = np.array(data["end_game_img"]) if "game_keys" in data.keys(): for i in range(len(data["game_keys"][0])): data["game_keys"][0][i] = Key.Key(data["game_keys"][0][i][0], data["game_keys"][0][i][1]) return data
def generateKeys(prime1, prime2): n = prime1 * prime2 fi = (prime1-1)*(prime2-1) e, d = findED(fi) #print(prime1, " ", prime2) #print("n=", n) #print("fi=", fi) #print("e=", e) #print("d=", d) publica = Key.Key() publica.exponent = int(e) publica.modul = int(n) privata = Key.Key() privata.exponent = int(d) privata.modul = int(n) return privata, publica
def print_list(root): # dirs 文件夹 # files 文件 for root, dirs, files in os.walk(root): for each in dirs: # 匹配每个文件夹 match = Key.match_pattern(each) if match: List.step_in(root, each) print(get_alias(os.getcwd())) os.chdir(root)
def account_balance(self, pub): b = 0.0 key = Key.pub_from_hex(pub) for block in self.chain: for transaction in range(0, len(block.transactions)): if block.transactions[transaction].receiver == key: b += block.transactions[transaction].amount elif block.transactions[transaction].sender == key: b -= block.transactions[transaction].amount return b
def __init__(self, pub, time, prev_hash, proof): self.time = time self.transactions = list() if not isinstance(pub, str): pub = Key.hex(pub) if pub != "0": self.transactions.append(Transaction.create_mining_pay(pub, time)) self.proof = proof self.prev_hash = prev_hash
def beginEncryption(self, listFilenames, private_key, public_key): key = k.Key(private_key, public_key) self.changeButtonState(tk.DISABLED) self.changeTextBoxState(tk.DISABLED) for i in listFilenames: self.showBar(i, listFilenames.index(i), len(listFilenames)) if self.selection_value.get() == 1: e.encrypt(i, self.output_entry.get(), key) if self.selection_value.get() == 2: d.decrypt(i, self.output_entry.get(), key) self.progressText.set(self.encrypt_text.get()+"ion finished. ("+str(len(listFilenames))+"/"+str(len(listFilenames))+")") self.clearAllText() self.changeButtonState(tk.NORMAL)
def runSS(): for i in range(roundsPerRun): killCount = 0 mobsKilled = [] while killCount < 5: if not GameState.IsInGame() or not inSS(): print("Not in SS!") break curMob = None for mobID in ssMobArray: mob = Field.FindMob(mobID) if mob.valid and mob not in mobsKilled: curMob = mob mobsKilled.append(mob) break if curMob is not None: SunCat.KamiTP(curMob.x, curMob.y) time.sleep(killTime) Key.Press(npcChatKey) time.sleep(0.2) Key.Press(npcChatKey) time.sleep(waitTime) killCount += 1 else: print("No mobs left!") time.sleep( 3) #Wait for mobs to respawn - this should never be hit SunCat.KamiTP(ssBaseX, ssBaseY) time.sleep(roundWaitTime) SCLib.UpdateVar("CurSSRuns", SCLib.GetVar("CurSSRuns") + 1) SCLib.UpdateVar("CurStep", "FinishingSS")
def Enc(self, auto=False, key_path=[], wd_num=20): #Plase Choose a file: # #If auto = True, generate a Key_map Automatically key_mgr = Key() if auto == True: key_mgr.SetKeyPath(self.img_path + '.key') key_mgr.GenKey(word_num=wd_num) else: key_mgr.SetKeyPath(key_path) key_mgr.OpenFile() #Operation Begin opt_info = key_mgr.GetKeyInfo() for rl_round in range(0, opt_info['rl_round']): for row_index in range(0, self.image.size[0] / self.blc_size): shift_times = key_mgr.GetEncKey() self.Row(row_index, shift_times) for col_index in range(0, self.image.size[1] / self.blc_size): shift_times = key_mgr.GetEncKey() self.Col(col_index, shift_times) #Operation End key_mgr.CloseFile() self.image.save(fp=self.img_path)
def findMine(): print("Finding mine.") time.sleep(2) portal = Field.FindReactor(mineID) print("Mine Found") if portal.valid: print("Mine Valid") telePortToLoc(portal.x - 50, portal.y) time.sleep(3.5) print("Hitting NPC Key") Key.Press(npcKey) print("Done hitting NPC Key, should have finished mining that shit.") time.sleep(4.5) checkAgain(portal)
def Dec(self, key_path): #Please choose a key? key_mgr = Key() key_mgr.SetKeyPath(key_path) key_mgr.OpenFile() #Here should choose the file path opt_info = key_mgr.GetKeyInfo() #Calculate stop_index: used_knum = (self.image.size[0] / self.blc_size + self.image.size[1] / self.blc_size) * opt_info['rl_round'] stop_index = used_knum % opt_info['wd_num'] #Set Key Cursor: key_mgr.SetKeyCursor(key_index=stop_index) for rl_round in range(0, opt_info['rl_round']): for col_index in list( reversed(range(0, self.image.size[1] / self.blc_size))): shift_times = -key_mgr.GetDecKey() self.Col(col_index, shift_times) for row_index in list( reversed(range(0, self.image.size[0] / self.blc_size))): shift_times = -key_mgr.GetDecKey() self.Row(row_index, shift_times) key_mgr.CloseFile() self.image.save(fp=self.img_path)
def __create_scales(self, scales, key): self.__scales.clear() k = Key.Key() pitch = k.Get(key) self.__scales.append(pitch) for interval in scales: #0-11 #-1-->11 #-2-->10 #12-->0 #13-->1 pitch += interval if pitch < 0: pitch = len(self.__et.Keys) - abs(pitch) elif len(self.__et.Keys) - 1 < pitch: pitch %= len(self.__et.Keys) self.__scales.append(pitch) # print('self.__scales:', self.__scales) return self.__scales
def investigate(solver, alphabet=None): show = lambda num: str(num) + (" (" + Key.toCharArr(num, alphabet) + ")" if alphabet else "") if not solver.done: print("FAILED TO CREATE a path between " + show(solver.start) + " and " + show(solver.goal) + ": the solver never finished.") elif not Solution.pathIsValid(solver.path): print("FAILED TO CREATE a path between " + show(solver.start) + " and " + show(solver.goal) + ": the solution is not valid.") else: print("\nSUCCESSFULLY CREATED a path from " + show(solver.start) + " to " + show(solver.goal)) if len(solver.path) == 0: solver.path = [0] print("path: " + trimOut(solver.path, length=360)) instructions = Solution.pathToInstructions(solver.path) print("instructions: " + trimOut(instructions, length=360)) print("Encrypted data:" + show(Solution.instructionsToNumber(instructions))) print("re-solve: " + str(show(Solution.solveInstructions(solver.path[0], instructions)))) drawGuides({ "min": min(solver.path), "max": max(solver.path) }, solver.upperBound) drawRate(solver.upperBound) drawFrequencies(solver.path, solver.upperBound) drawPath(solver.path, solver.upperBound) print("sorted: " + str(sortEnabled) + ", reversed: " + str(reverseEnabled) + ", " + str(len(solver.path)) + " steps", end="") if isinstance(solver, StackedSolver): print(", " + str(len(solver.visited)) + " visited\n") print("visited non-repetition certification: ", end="") certify(solver.visited) print("goalPool non-repetition certification: ", end="") certify(solver.goalPool) else: print("") print("path non-repetition certification: ", end="") certify(solver.path)
def setup(self): '''This function, as of now, sets up the pieces how we have them at the beggining of a game''' gold1 = Key("A2", "South", False, "gold") gold2 = Key("A4", "South", False, "gold") gold3 = Key("A6", "South", False, "gold") self.addPieceToLocation("A2", gold1) self.addPieceToLocation("A4", gold2) self.addPieceToLocation("A6", gold3) silver1 = Key("H3", "North", False, "silver") silver2 = Key("H5", "North", False, "silver") silver3 = Key("H7", "North", False, "silver") self.addPieceToLocation("H3", silver1) self.addPieceToLocation("H5", silver2) self.addPieceToLocation("H7", silver3)
def command(self, c): c = c.strip() if c == "help": print("""Welcome to the Key Server Admin! ** [Verb] [Type] [Optional Param] ** Verbs: - List = List out all the specified TYPE ex. list app - Create = Create a new TYPE ex. create user - Update = Update a TYPE, the item to modify is specified as an additional parameter ex. update app test - Delete = Delete a TYPE, the item to delete is specified as an additional parameter ex. delete param url Types: - app = Applications - Act like folders for Parameters - key = API Key - used by clients to fetch params - param = Parameter, requires an app to be selected - user = Admin User ** select [App_Name] ** Select allows you to select an application to work with. This is required when you want to modify parameters. ** exit ** If an app is currently selected, goes back to home. If no app is currently selected, quits the admin CLI ** help ** Lists this help info""") elif c.lower().__contains__("select"): try: target_app = c.split(" ")[1] except IndexError: print("Invalid select condition - please specify which app you want to select") return if target_app in App.list_apps(self.username, self.password): CLI.current_app = target_app else: print("That is not a valid app name, type 'list apps' to see all the current apps.") elif c.lower().__contains__("list"): try: list_item = c.lower().split(" ")[1] except IndexError: print("Invalid list condition - please specify what you want to list") return if list_item.__contains__("-h") or list_item.__contains__("help"): print("""List allows you to list out different applications, keys, users, and parameters. ** list [type] ** type `help` to list out all the types and their roles In order to list parameters, an application needs to be selected.""") elif list_item.__contains__("users"): for u in User.list_users(self.username, self.password): print("\t%s (%s)" % (u['username'], u['email'])) elif list_item.__contains__("apps"): for a in App.list_apps(self.username, self.password): print("\t" + a) elif list_item.__contains__("key"): for k in Key.list_keys(self.username, self.password): print ("\t%s (%s)\n" "\t\t Permissions: %s" % (k["application_name"], k["application_key"], k["permissions"])) elif list_item.__contains__("param"): if CLI.current_app == "": print("Cannot list params when no app is selected") else: for p in Param.list_params(self.username, self.password, CLI.current_app): print("\t%s = %s" % (p['name'], p['value'])) else: print("Unknown List Command - type `list -h` or `list help` for help.") elif c.lower().__contains__("create"): try: create_item = c.lower().split(" ")[1] except IndexError: print("Invalid create condition - please specify what you want to create") return if create_item.__contains__("-h") or create_item.__contains__("help"): print("""Create allows you to create new applications, keys, users, and parameters ** create [type] ** type `help` to list out all the types and their roles In order to create parameters, an application needs to be selected.""") elif create_item.__contains__("user"): while True: username = raw_input("\tUsername: "******"\tPassword: "******"\tConfirm Password: "******"Passwords do not match. Try Again.") email = raw_input("\tEmail: ").strip() conf = raw_input("\n\tUsername: %s\n\tPassword: %s\n\tEmail: %s\n\tIs this correct [Y/n]" % (username, password, email)).strip() if conf.lower() == "y" or conf == "": user = User.create_new(self.username, self.password, username, password, email) print("Created New User: %s" % user["username"]) break elif create_item.__contains__("app"): while True: app_name = raw_input("\tApplication Name: ").strip() conf = raw_input("\n\tApplication Name: %s\n\tIs this correct [Y/n]" % app_name).strip() if conf.lower() == "y" or conf == "": app = App.create_app(self.username, self.password, app_name) print("Created New App: %s" % app["name"]) break elif create_item.__contains__("key"): while True: application_name = raw_input("\tApplication Name: ").strip() print("\tIn case you need a refresher... Application permissions are as follows:\n" "\t\t* use +app_name to whitelist the key for that app\n" "\t\t* use -app_name to blacklist the key for that app\n" "\t\t* use NO to revoke the key\n" "\t\t* or use ALL to grant the key access to all apps") permissions = raw_input("\tApplication Permissions: ").strip() if permissions == "": permissions = "ALL" conf = raw_input("\n\tName: %s\n\tPermissions: %s\n\tIs this correct [Y/n]" % ( application_name, permissions)).strip() if conf.lower() == "y" or conf == "": key = Key.create_key(self.username, self.password, application_name, permissions) print("Created New Key: %s" % key["application_key"]) break elif create_item.__contains__("param"): if CLI.current_app == "": print("Cannot create param when no app is selected") else: while True: param_name = raw_input("\tParameter Name: ").strip() param_value = raw_input("\tParameter Value: ").strip() conf = raw_input( "\n\tParameter Name: %s\n\tParameter Value: %s\n\tIs this correct [Y/n]" % (param_name, param_value)) \ .strip() if conf.lower() == "y" or conf == "": param = Param.create_param(self.username, self.password, CLI.current_app, param_name, param_value) print("Created New Parameter: %s" % param["name"]) break else: print("Unknown Create Command - type `create -h` or `create help` for help.") elif c.lower().__contains__("update"): try: update_item = c.lower().split(" ")[1] except IndexError: print("Invalid update condition - please specify what you want to update") return try: update_item_name = c.split(" ")[2] except IndexError: print("Invalid update condition - please specify which %s you want to update." % update_item) return if update_item.__contains__("-h") or update_item.__contains__("help"): print("""Update allows you to update existing applications, keys, users, and parameters ** update [type] [username/applicationName/applicationKey/parameterName]** type `help` to list out all the types and their roles In order to create parameters, an application needs to be selected.""") elif update_item.__contains__("user"): user_info = User.list_users(self.username, self.password) for u in user_info: if u['username'] == update_item_name: user_info = u break while True: password = None while True: password = getpass.getpass("\tNew Password [Leave blank to keep]: ") password_conf = getpass.getpass("\tConfirm New Password: "******"Passwords do not match. Try Again.") email = raw_input("\tEmail [%s]: " % user_info['email']).strip() email = email if email != "" else user_info['email'] conf = raw_input("\n\tUsername: %s\n\tPassword: %s\n\tEmail: %s\n\tIs this correct [Y/n]" % (update_item_name, password, email)).strip() if conf.lower() == "y" or conf == "": user = User.update_user(self.username, self.password, update_item_name, password=password, email=email) # Updating the current user's password, so let's update the one we are using to login to the API if update_item_name == self.username: self.password = password print("Updated User: %s" % user["username"]) break elif update_item.__contains__("key"): key_info = Key.list_keys(self.username, self.password) for k in key_info: if k['application_key'] == update_item_name: key_info = k break while True: application_name = raw_input("\tApplication Name [%s]: " % key_info['application_name']) permissions = raw_input("\tPermissions [%s]: " % key_info['permissions']) conf = raw_input("\n\tName: %s\n\tPermissions: %s\n\tIs this correct [Y/n]" % ( application_name, permissions)).strip() if conf.lower() == "y" or conf == "": key = Key.update_key(self.username, self.password, update_item_name, application_name=application_name, permissions=permissions) print("Updated Key: %s" % key['application_key']) break elif update_item.__contains__("param"): if CLI.current_app == "": print("Cannot update param when no app is selected") else: while True: param_value = raw_input("\tNew Value Value: ").strip() conf = raw_input("\n\tParameter Value: %s\n\tIs this correct [Y/n]" % param_value).strip() if conf.lower() == "y" or conf == "": param = Param.update_param(self.username, self.password, CLI.current_app, update_item_name, param_value) print("Updated Parameter: %s" % param["name"]) break else: print("Unknown Update Command - type `update -h` or `update help` for help.") elif c.lower().__contains__("delete"): try: delete_item = c.lower().split(" ")[1] except IndexError: print("Invalid delete condition - please specify what you want to delete") return try: delete_item_name = c.split(" ")[2] except IndexError: print("Invalid delete condition - please specify which %s you want to delete." % delete_item) return if delete_item.__contains__("-h") or delete_item.__contains__("help"): print("""Delete allows you to remove applications, users, and parameters. Delete revokes keys, which is the only delete action that can be undone; to reactivate a revoked key, update the permissions of the key. ** update [type] [username/applicationName/applicationKey/parameterName]** type `help` to list out all the types and their roles In order to create parameters, an application needs to be selected.""") elif delete_item.__contains__("user"): conf = raw_input("\n\tUsername to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip() if conf.lower() == "y" or conf == "": status = User.delete_user(self.username, self.password, delete_item_name) if status: print("User was deleted Successfully") else: print("Problem deleting user, check server logs for details") elif delete_item.__contains__("app"): conf = raw_input("\n\tApplication to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip() if conf.lower() == "y" or conf == "": status = App.delete_app(self.username, self.password, delete_item_name) if status: print("App was deleted Successfully") else: print("Problem deleting app, check server logs for details") elif delete_item.__contains__("key"): conf = raw_input("\n\tKey to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip() if conf.lower() == "y" or conf == "": status = Key.delete_key(self.username, self.password, delete_item_name) if status: print("Key was Revoked Successfully - to reactivate the Key, update its permissions") else: print("Problem revoking key, check server logs for details") elif delete_item.__contains__("param"): if CLI.current_app == "": print("Cannot delete param when no app is selected") else: conf = raw_input("\n\tParam to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip() if conf.lower() == "y" or conf == "": status = Param.delete_param(self.username, self.password, CLI.current_app, delete_item_name) if status: print("Param was deleted Successfully") else: print("Problem deleting param, check server logs for details") else: print("Unknown Delete Command - type `delete -h` or `delete help` for help.") elif c.lower().__contains__("exit"): if CLI.current_app == "": exit(0) else: CLI.current_app = "" else: print("Command not recognized")