Best Python code snippet using autotest_python
empyre.py
Source:empyre.py
...638 if choice.lower() != "" and choice.lower()[0] == "y":639 agents = self.mainMenu.agents.get_agents()640 for agent in agents:641 sessionID = agent[1]642 self.mainMenu.agents.add_agent_task(sessionID, "TASK_EXIT")643 except KeyboardInterrupt as e:644 print ""645 else:646 # extract the sessionID and clear the agent tasking647 sessionID = self.mainMenu.agents.get_agent_id(name)648 if sessionID and len(sessionID) != 0:649 self.mainMenu.agents.add_agent_task(sessionID, "TASK_EXIT")650 else:651 print helpers.color("[!] Invalid agent name")652 def do_clear(self, line):653 "Clear one or more agent's taskings."654 name = line.strip()655 if name.lower() == "all":656 self.mainMenu.agents.clear_agent_tasks("all")657 elif name.lower() == "autorun":658 self.mainMenu.agents.clear_autoruns()659 else:660 # extract the sessionID and clear the agent tasking661 sessionID = self.mainMenu.agents.get_agent_id(name)662 if sessionID and len(sessionID) != 0:663 self.mainMenu.agents.clear_agent_tasks(sessionID)664 else:665 print helpers.color("[!] Invalid agent name")666 def do_sleep(self, line):667 "Task one or more agents to 'sleep [agent/all] interval [jitter]'"668 parts = line.strip().split(" ")669 if len(parts) == 1:670 print helpers.color("[!] Please enter 'interval [jitter]'")671 if len(parts) >= 2:672 try:673 int(parts[1])674 except:675 print helpers.color("[!] Please only enter integer for 'interval'")676 return677 if len(parts) > 2:678 try:679 int(parts[2])680 except:681 print helpers.color("[!] Please only enter integer for '[jitter]'")682 return683 if parts[0].lower() == "all":684 delay = parts[1]685 jitter = 0.0686 if len(parts) == 3:687 jitter = parts[2]688 agents = self.mainMenu.agents.get_agents()689 for agent in agents:690 sessionID = agent[1]691 # update this agent info in the database692 self.mainMenu.agents.set_agent_field("delay", delay, sessionID)693 self.mainMenu.agents.set_agent_field("jitter", jitter, sessionID)694 # task the agent695 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global delay; global jitter; delay=%s; jitter=%s; print 'delay/jitter set to %s/%s'" % (delay, jitter, delay, jitter))696 # update the agent log697 msg = "Tasked agent to delay sleep/jitter to: %s/%s" % (delay, jitter)698 self.mainMenu.agents.save_agent_log(sessionID, msg)699 else:700 # extract the sessionID and clear the agent tasking701 sessionID = self.mainMenu.agents.get_agent_id(parts[0])702 delay = parts[1]703 jitter = 0.0704 if len(parts) == 3:705 jitter = parts[2]706 if sessionID and len(sessionID) != 0:707 # update this agent's information in the database708 self.mainMenu.agents.set_agent_field("delay", delay, sessionID)709 self.mainMenu.agents.set_agent_field("jitter", jitter, sessionID)710 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global delay; global jitter; delay=%s; jitter=%s; print 'delay/jitter set to %s/%s'" % (delay, jitter, delay, jitter))711 # update the agent log712 msg = "Tasked agent to delay sleep/jitter to: %s/%s" % (delay, jitter)713 self.mainMenu.agents.save_agent_log(sessionID, msg)714 else:715 print helpers.color("[!] Invalid agent name")716 def do_lostlimit(self, line):717 "Task one or more agents to 'lostlimit [agent/all] <#ofCBs> '"718 parts = line.strip().split(" ")719 if len(parts) == 1:720 print helpers.color("[!] Please enter a valid '#ofCBs'")721 elif parts[0].lower() == "all":722 lostLimit = parts[1]723 agents = self.mainMenu.agents.get_agents()724 for agent in agents:725 sessionID = agent[1]726 # update this agent info in the database727 self.mainMenu.agents.set_agent_field("lost_limit", lostLimit, sessionID)728 # task the agent729 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global lostLimit; lostLimit=%s; print 'lostLimit set to %s'" % (lostLimit, lostLimit))730 # update the agent log731 msg = "Tasked agent to change lost limit to: %s" % (lostLimit)732 self.mainMenu.agents.save_agent_log(sessionID, msg)733 else:734 # extract the sessionID and clear the agent tasking735 sessionID = self.mainMenu.agents.get_agent_id(parts[0])736 lostLimit = parts[1]737 if sessionID and len(sessionID) != 0:738 # update this agent's information in the database739 self.mainMenu.agents.set_agent_field("lost_limit", lostLimit, sessionID)740 # task the agent741 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global lostLimit; lostLimit=%s; print 'lostLimit set to %s'" % (lostLimit, lostLimit))742 # update the agent log743 msg = "Tasked agent to change lost limit to: %s" % (lostLimit)744 self.mainMenu.agents.save_agent_log(sessionID, msg)745 else:746 print helpers.color("[!] Invalid agent name")747 def do_killdate(self, line):748 "Set the killdate for one or more agents (killdate [agent/all] 01/01/2016)."749 parts = line.strip().split(" ")750 if len(parts) == 1:751 print helpers.color("[!] Please enter date in form 01/01/2016")752 elif parts[0].lower() == "all":753 killDate = parts[1]754 agents = self.mainMenu.agents.get_agents()755 for agent in agents:756 sessionID = agent[1]757 # update this agent's field in the database758 self.mainMenu.agents.set_agent_field("kill_date", killDate, sessionID)759 # task the agent760 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global killDate; killDate='%s'; print 'killDate set to %s'" % (killDate, killDate))761 msg = "Tasked agent to set killdate to: %s" % (killDate)762 self.mainMenu.agents.save_agent_log(sessionID, msg)763 else:764 # extract the sessionID and clear the agent tasking765 sessionID = self.mainMenu.agents.get_agent_id(parts[0])766 killDate = parts[1]767 if sessionID and len(sessionID) != 0:768 # update this agent's field in the database769 self.mainMenu.agents.set_agent_field("kill_date", killDate, sessionID)770 # task the agent771 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global killDate; killDate='%s'; print 'killDate set to %s'" % (killDate, killDate))772 # update the agent log773 msg = "Tasked agent to set killdate to: %s" % (killDate)774 self.mainMenu.agents.save_agent_log(sessionID, msg)775 else:776 print helpers.color("[!] Invalid agent name")777 def do_workinghours(self, line):778 "Set the workinghours for one or more agents (workinghours [agent/all] 9:00-17:00)."779 parts = line.strip().split(" ")780 if len(parts) == 1:781 print helpers.color("[!] Please enter hours in the form '9:00-17:00'")782 elif parts[0].lower() == "all":783 hours = parts[1]784 hours = hours.replace("," , "-")785 agents = self.mainMenu.agents.get_agents()786 for agent in agents:787 sessionID = agent[1]788 # update this agent's field in the database789 self.mainMenu.agents.set_agent_field("working_hours", hours, sessionID)790 # task the agent791 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global workingHours; workingHours= '%s'" % (hours))792 msg = "Tasked agent to set working hours to: %s" % (hours)793 self.mainMenu.agents.save_agent_log(sessionID, msg)794 else:795 # extract the sessionID and clear the agent tasking796 sessionID = self.mainMenu.agents.get_agent_id(parts[0])797 hours = parts[1]798 hours = hours.replace("," , "-")799 if sessionID and len(sessionID) != 0:800 # update this agent's field in the database801 self.mainMenu.agents.set_agent_field("working_hours", hours, sessionID)802 # task the agent803 self.mainMenu.agents.add_agent_task(sessionID, "TASK_CMD_WAIT", "global workingHours; workingHours= '%s'" % (hours))804 # update the agent log805 msg = "Tasked agent to set working hours to %s" % (hours)806 self.mainMenu.agents.save_agent_log(sessionID, msg)807 else:808 print helpers.color("[!] Invalid agent name")809 def do_remove(self, line):810 "Remove one or more agents from the database."811 name = line.strip()812 if name.lower() == "all":813 try:814 choice = raw_input(helpers.color("[>] Remove all agents from the database? [y/N] ", "red"))815 if choice.lower() != "" and choice.lower()[0] == "y":816 self.mainMenu.agents.remove_agent('%')817 except KeyboardInterrupt as e:818 print ""819 elif name.lower() == "stale":820 # remove 'stale' agents that have missed their checkin intervals821 agents = self.mainMenu.agents.get_agents()822 for agent in agents:823 sessionID = self.mainMenu.agents.get_agent_id(agent[3])824 # max check in -> delay + delay*jitter825 intervalMax = (agent[4] + agent[4] * agent[5])+30826 # get the agent last check in time827 agentTime = time.mktime(time.strptime(agent[16], "%Y-%m-%d %H:%M:%S"))828 if agentTime < time.mktime(time.localtime()) - intervalMax:829 # if the last checkin time exceeds the limit, remove it830 self.mainMenu.agents.remove_agent(sessionID)831 elif name.isdigit():832 # if we're removing agents that checked in longer than X minutes ago833 agents = self.mainMenu.agents.get_agents()834 try:835 minutes = int(line.strip())836 # grab just the agents active within the specified window (in minutes)837 for agent in agents:838 sessionID = self.mainMenu.agents.get_agent_id(agent[3])839 # get the agent last check in time840 agentTime = time.mktime(time.strptime(agent[16], "%Y-%m-%d %H:%M:%S"))841 if agentTime < time.mktime(time.localtime()) - (int(minutes) * 60):842 # if the last checkin time exceeds the limit, remove it843 self.mainMenu.agents.remove_agent(sessionID)844 except:845 print helpers.color("[!] Please enter the minute window for agent checkin.")846 else:847 # extract the sessionID and clear the agent tasking848 sessionID = self.mainMenu.agents.get_agent_id(name)849 if sessionID and len(sessionID) != 0:850 self.mainMenu.agents.remove_agent(sessionID)851 else:852 print helpers.color("[!] Invalid agent name")853 def do_usestager(self, line):854 "Use an EmPyre stager."855 parts = line.split(" ")856 if parts[0] not in self.mainMenu.stagers.stagers:857 print helpers.color("[!] Error: invalid stager module")858 elif len(parts) == 1:859 l = StagerMenu(self.mainMenu, parts[0])860 l.cmdloop()861 elif len(parts) == 2:862 listener = parts[1]863 if not self.mainMenu.listeners.is_listener_valid(listener):864 print helpers.color("[!] Please enter a valid listener name or ID")865 else:866 self.mainMenu.stagers.set_stager_option('Listener', listener)867 l = StagerMenu(self.mainMenu, parts[0])868 l.cmdloop()869 else:870 print helpers.color("[!] Error in AgentsMenu's do_userstager()")871 def do_usemodule(self, line):872 "Use an EmPyre Python module."873 module = line.strip()874 if module not in self.mainMenu.modules.modules:875 print helpers.color("[!] Error: invalid module")876 else:877 # set agent to "all"878 l = ModuleMenu(self.mainMenu, line, agent="all")879 l.cmdloop()880 def do_searchmodule(self, line):881 "Search EmPyre module names/descriptions."882 searchTerm = line.strip()883 if searchTerm.strip() == "":884 print helpers.color("[!] Please enter a search term.")885 else:886 self.mainMenu.modules.search_modules(searchTerm)887 def complete_interact(self, text, line, begidx, endidx):888 "Tab-complete an interact command"889 names = self.mainMenu.agents.get_agent_names()890 mline = line.partition(' ')[2]891 offs = len(mline) - len(text)892 return [s[offs:] for s in names if s.startswith(mline)]893 def complete_rename(self, text, line, begidx, endidx):894 "Tab-complete a rename command"895 names = self.mainMenu.agents.get_agent_names()896 return self.complete_interact(text, line, begidx, endidx)897 def complete_clear(self, text, line, begidx, endidx):898 "Tab-complete a clear command"899 names = self.mainMenu.agents.get_agent_names() + ["all", "autorun"]900 mline = line.partition(' ')[2]901 offs = len(mline) - len(text)902 return [s[offs:] for s in names if s.startswith(mline)]903 def complete_remove(self, text, line, begidx, endidx):904 "Tab-complete a remove command"905 names = self.mainMenu.agents.get_agent_names() + ["all", "stale"]906 mline = line.partition(' ')[2]907 offs = len(mline) - len(text)908 return [s[offs:] for s in names if s.startswith(mline)]909 def complete_list(self, text, line, begidx, endidx):910 "Tab-complete a list command"911 options = ["stale"]912 mline = line.partition(' ')[2]913 offs = len(mline) - len(text)914 return [s[offs:] for s in options if s.startswith(mline)]915 def complete_kill(self, text, line, begidx, endidx):916 "Tab-complete a kill command"917 return self.complete_clear(text, line, begidx, endidx)918 def complete_sleep(self, text, line, begidx, endidx):919 "Tab-complete a sleep command"920 return self.complete_clear(text, line, begidx, endidx)921 def complete_lostlimit(self, text, line, begidx, endidx):922 "Tab-complete a lostlimit command"923 return self.complete_clear(text, line, begidx, endidx)924 def complete_killdate(self, text, line, begidx, endidx):925 "Tab-complete a killdate command"926 return self.complete_clear(text, line, begidx, endidx)927 def complete_workinghours(self, text, line, begidx, endidx):928 "Tab-complete a workinghours command"929 return self.complete_clear(text, line, begidx, endidx)930 def complete_usemodule(self, text, line, begidx, endidx):931 "Tab-complete an EmPyre Python module path"932 return self.mainMenu.complete_usemodule(text, line, begidx, endidx)933 def complete_usestager(self, text, line, begidx, endidx):934 "Tab-complete an EmPyre stager module path."935 return self.mainMenu.complete_usestager(text, line, begidx, endidx)936 def complete_creds(self, text, line, begidx, endidx):937 "Tab-complete 'creds' commands."938 return self.mainMenu.complete_creds(text, line, begidx, endidx)939class AgentMenu(cmd.Cmd):940 def __init__(self, mainMenu, sessionID):941 cmd.Cmd.__init__(self)942 self.mainMenu = mainMenu943 self.sessionID = sessionID944 self.doc_header = 'Agent Commands'945 # try to resolve the sessionID to a name946 name = self.mainMenu.agents.get_agent_name(sessionID)947 # set the text prompt948 self.prompt = '(EmPyre: '+helpers.color(name, 'red')+') > '949 # listen for messages from this specific agent950 dispatcher.connect(self.handle_agent_event, sender=dispatcher.Any)951 # display any results from the database that were stored952 # while we weren't interacting with the agent953 results = self.mainMenu.agents.get_agent_results(self.sessionID)954 if results:955 print "\n" + results.rstrip('\r\n')956 # def preloop(self):957 # traceback.print_stack()958 def handle_agent_event(self, signal, sender):959 """960 Handle agent event signals.961 """962 if "[!] Agent" in signal and "exiting" in signal: pass963 name = self.mainMenu.agents.get_agent_name(self.sessionID)964 if (str(self.sessionID) + " returned results" in signal) or (str(name) + " returned results" in signal):965 # display any results returned by this agent that are returned966 # while we are interacting with it967 results = self.mainMenu.agents.get_agent_results(self.sessionID)968 if results:969 print "\n" + results970 elif "[+] Part of file" in signal and "saved" in signal:971 if (str(self.sessionID) in signal) or (str(name) in signal):972 print helpers.color(signal)973 # print a nicely formatted help menu974 # stolen/adapted from recon-ng975 def print_topics(self, header, cmds, cmdlen, maxcol):976 if cmds:977 self.stdout.write("%s\n" % str(header))978 if self.ruler:979 self.stdout.write("%s\n" % str(self.ruler * len(header)))980 for c in cmds:981 self.stdout.write("%s %s\n" % (c.ljust(17), getattr(self, 'do_' + c).__doc__))982 self.stdout.write("\n")983 def emptyline(self): pass984 def default(self, line):985 "Default handler"986 print helpers.color("[!] Command not recognized, use 'help' to see available commands")987 def do_back(self, line):988 "Go back a menu."989 return True990 def do_agents(self, line):991 "Jump to the Agents menu."992 raise NavAgents()993 def do_listeners(self, line):994 "Jump to the listeners menu."995 raise NavListeners()996 def do_main(self, line):997 "Go back to the main menu."998 raise NavMain()999 def do_help(self, *args):1000 "Displays the help menu or syntax for particular commands."1001 cmd.Cmd.do_help(self, *args)1002 def do_list(self, line):1003 "Lists all active agents (or listeners)."1004 if line.lower().startswith("listeners"):1005 self.mainMenu.do_list("listeners " + str(" ".join(line.split(" ")[1:])))1006 elif line.lower().startswith("agents"):1007 self.mainMenu.do_list("agents " + str(" ".join(line.split(" ")[1:])))1008 else:1009 print helpers.color("[!] Please use 'list [agents/listeners] <modifier>'.")1010 def do_rename(self, line):1011 "Rename the agent."1012 parts = line.strip().split(" ")1013 oldname = self.mainMenu.agents.get_agent_name(self.sessionID)1014 # name sure we get a new name to rename this agent1015 if len(parts) == 1:1016 # replace the old name with the new name1017 result = self.mainMenu.agents.rename_agent(oldname, parts[0])1018 if result:1019 self.prompt = "(EmPyre: "+helpers.color(parts[0], 'red')+") > "1020 else:1021 print helpers.color("[!] Please enter a new name for the agent")1022 def do_info(self, line):1023 "Display information about this agent"1024 # get the agent name, if applicable1025 agent = self.mainMenu.agents.get_agent(self.sessionID)1026 messages.display_agent(agent)1027 def do_exit(self, line):1028 "Task agent to exit."1029 try:1030 choice = raw_input(helpers.color("[>] Task agent to exit? [y/N] ", "red"))1031 if choice.lower() != "" and choice.lower()[0] == "y":1032 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_EXIT")1033 # update the agent log1034 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to exit")1035 return True1036 except KeyboardInterrupt as e:1037 print ""1038 def do_clear(self, line):1039 "Clear out agent tasking."1040 self.mainMenu.agents.clear_agent_tasks(self.sessionID)1041 def do_cd(self, line):1042 "Change an agent's active directory"1043 line = line.strip()1044 if line != "":1045 # have to be careful with inline python and no threading1046 # this can cause the agent to crash so we will use try / cath1047 # task the agent with this shell command1048 if line == "..":1049 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", 'import os; os.chdir(os.pardir); print "Directory stepped down: %s"' % (line))1050 else:1051 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", 'import os; os.chdir("%s"); print "Directory changed to: %s"' % (line, line))1052 # update the agent log1053 msg = "Tasked agent to change active directory to: %s" % (line)1054 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1055 def do_jobs(self, line):1056 "Return jobs or kill a running job."1057 parts = line.split(" ")1058 if len(parts) == 1:1059 if parts[0] == '':1060 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_GETJOBS")1061 # update the agent log1062 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to get running jobs")1063 else:1064 print helpers.color("[!] Please use form 'jobs kill JOB_ID'")1065 elif len(parts) == 2:1066 jobID = parts[1].strip()1067 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_STOPJOB", jobID)1068 # update the agent log1069 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to stop job " + str(jobID))1070 def do_sleep(self, line):1071 "Task an agent to 'sleep interval [jitter]'"1072 parts = line.strip().split(" ")1073 delay = parts[0]1074 # make sure we pass a int()1075 if len(parts) >= 1:1076 try:1077 int(delay)1078 except:1079 print helpers.color("[!] Please only enter integer for 'interval'")1080 return1081 if len(parts) > 1:1082 try:1083 int(parts[1])1084 except:1085 print helpers.color("[!] Please only enter integer for '[jitter]'")1086 return1087 if delay == "":1088 # task the agent to display the delay/jitter1089 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global delay; global jitter; print 'delay/jitter = ' + str(delay)+'/'+str(jitter)")1090 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to display delay/jitter")1091 elif len(parts) > 0 and parts[0] != "":1092 delay = parts[0]1093 jitter = 0.01094 if len(parts) == 2:1095 jitter = parts[1]1096 # update this agent's information in the database1097 self.mainMenu.agents.set_agent_field("delay", delay, self.sessionID)1098 self.mainMenu.agents.set_agent_field("jitter", jitter, self.sessionID)1099 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global delay; global jitter; delay=%s; jitter=%s; print 'delay/jitter set to %s/%s'" % (delay, jitter, delay, jitter))1100 # update the agent log1101 msg = "Tasked agent to delay sleep/jitter " + str(delay) + "/" + str(jitter)1102 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1103 def do_lostlimit(self, line):1104 "Task an agent to display change the limit on lost agent detection"1105 parts = line.strip().split(" ")1106 lostLimit = parts[0]1107 if lostLimit == "":1108 # task the agent to display the lostLimit1109 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; print 'lostLimit = ' + str(lostLimit)")1110 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to display lost limit")1111 else:1112 # update this agent's information in the database1113 self.mainMenu.agents.set_agent_field("lost_limit", lostLimit, self.sessionID)1114 # task the agent with the new lostLimit1115 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; lostLimit=%s; print 'lostLimit set to %s'"%(lostLimit, lostLimit))1116 # update the agent log1117 msg = "Tasked agent to change lost limit " + str(lostLimit)1118 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1119 def do_killdate(self, line):1120 "Get or set an agent's killdate (01/01/2016)."1121 parts = line.strip().split(" ")1122 killDate = parts[0]1123 if killDate == "":1124 # task the agent to display the killdate1125 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global killDate; print 'killDate = ' + str(killDate)")1126 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to display killDate")1127 else:1128 # update this agent's information in the database1129 self.mainMenu.agents.set_agent_field("kill_date", killDate, self.sessionID)1130 # task the agent with the new killDate1131 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global killDate; killDate='%s'; print 'killDate set to %s'" % (killDate, killDate))1132 # update the agent log1133 msg = "Tasked agent to set killdate to %s" %(killDate)1134 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1135 def do_workinghours(self, line):1136 "Get or set an agent's working hours (9:00-17:00)."1137 parts = line.strip().split(" ")1138 hours = parts[0]1139 if hours == "":1140 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global workingHours; print 'workingHours = ' + str(workingHours)")1141 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to get working hours")1142 else:1143 # update this agent's information in the database1144 self.mainMenu.agents.set_agent_field("working_hours", hours, self.sessionID)1145 # task the agent with the new working hours1146 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", "global workingHours; workingHours= '%s'"%(hours))1147 # update the agent log1148 msg = "Tasked agent to set working hours to: %s" % (hours)1149 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1150 def do_shell(self, line):1151 "Task an agent to use a shell command."1152 line = line.strip()1153 if line != "":1154 # task the agent with this shell command1155 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_SHELL", str(line))1156 # update the agent log1157 msg = "Tasked agent to run shell command: %s" % (line)1158 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1159 def do_python(self, line):1160 "Task an agent to run a Python command."1161 line = line.strip()1162 if line != "":1163 # task the agent with this shell command1164 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", str(line))1165 # update the agent log1166 msg = "Tasked agent to run Python command %s" % (line)1167 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1168 def do_pythonscript(self, line):1169 "Load and execute a python script"1170 path = line.strip()1171 if os.path.splitext(path)[-1] == '.py' and os.path.isfile(path):1172 filename = os.path.basename(path).rstrip('.py')1173 open_file = open(path, 'r')1174 script = open_file.read()1175 open_file.close()1176 script = script.replace('\r\n', '\n')1177 script = script.replace('\r', '\n')1178 msg = "[*] Tasked agent to execute python script: "+filename1179 print helpers.color(msg, color="green")1180 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_CMD_WAIT", script)1181 #update the agent log1182 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1183 else:1184 print helpers.color("[!] Please provide a valid path", color="red")1185 def do_sysinfo(self, line):1186 "Task an agent to get system information."1187 # task the agent with this shell command1188 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_SYSINFO")1189 # update the agent log1190 self.mainMenu.agents.save_agent_log(self.sessionID, "Tasked agent to get system information")1191 def do_download(self, line):1192 "Task an agent to download a file."1193 line = line.strip()1194 if line != "":1195 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_DOWNLOAD", line)1196 # update the agent log1197 msg = "Tasked agent to download: %s" % (line)1198 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1199 def do_upload(self, line):1200 "Task an agent to upload a file."1201 # "upload /path/file.ext" or "upload /path/file/file.ext newfile.ext"1202 # absolute paths accepted1203 parts = line.strip().split(" ")1204 uploadname = ""1205 if len(parts) > 0 and parts[0] != "":1206 if len(parts) == 1:1207 # if we're uploading the file with its original name1208 uploadname = os.path.basename(parts[0])1209 else:1210 # if we're uploading the file as a different name1211 uploadname = parts[1].strip()1212 if parts[0] != "" and os.path.exists(parts[0]):1213 # read in the file and base64 encode it for transport1214 f = open(parts[0], 'r')1215 fileData = f.read()1216 f.close()1217 # Get file size1218 print helpers.color("[*] Starting size of %s for upload: %s" %(uploadname, helpers.get_file_size(fileData)), color="green")1219 msg = "Tasked agent to upload " + parts[0] + " : " + hashlib.md5(fileData).hexdigest()1220 # update the agent log with the filename and MD51221 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1222 # compress data before we base641223 c = compress.compress()1224 start_crc32 = c.crc32_data(fileData)1225 comp_data = c.comp_data(fileData, 9)1226 fileData = c.build_header(comp_data, start_crc32)1227 # get final file size1228 print helpers.color("[*] Final tasked size of %s for upload: %s" %(uploadname, helpers.get_file_size(fileData)), color="green")1229 fileData = helpers.encode_base64(fileData)1230 # upload packets -> "filename | script data"1231 data = uploadname + "|" + fileData1232 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_UPLOAD", data)1233 else:1234 print helpers.color("[!] Please enter a valid file path to upload")1235 def do_usemodule(self, line):1236 "Use an EmPyre Python module."1237 module = line.strip()1238 if module not in self.mainMenu.modules.modules:1239 print helpers.color("[!] Error: invalid module")1240 else:1241 l = ModuleMenu(self.mainMenu, line, agent=self.sessionID)1242 l.cmdloop()1243 def do_searchmodule(self, line):1244 "Search EmPyre module names/descriptions."1245 searchTerm = line.strip()1246 if searchTerm.strip() == "":1247 print helpers.color("[!] Please enter a search term.")1248 else:1249 self.mainMenu.modules.search_modules(searchTerm)1250 def do_creds(self, line):1251 "Display/return credentials from the database."1252 self.mainMenu.do_creds(line)1253 # def do_updateprofile(self, line):1254 # "Update an agent connection profile."1255 # # TODO: implement1256 def do_loadpymodule(self, line):1257 "Import a python module from memory. Provide a path to a single py file or a module folder with an __init__.py. To load multiple modules, place all module folders in a single directory"1258 path = line.strip()1259 if path != "" and os.path.exists(path):1260 if os.path.splitext(path)[-1] == '.zip' and os.path.isfile(path):1261 zipname = os.path.basename(path)1262 open_file = open(path,'rb')1263 module_data = open_file.read()1264 open_file.close()1265 print helpers.color("[*] Starting size of %s for upload and import: %s" %(path, helpers.get_file_size(module_data)), color="green")1266 msg = "Tasked agent to import "+path+" : " + hashlib.md5(module_data).hexdigest()1267 self.mainMenu.agents.save_agent_log(self.sessionID, msg)1268 c = compress.compress()1269 start_crc32 = c.crc32_data(module_data)1270 comp_data = c.comp_data(module_data, 9)1271 module_data = c.build_header(comp_data, start_crc32)1272 print helpers.color("[*] Final tasked size of %s for import: %s" %(path, helpers.get_file_size(module_data)), color="green")1273 module_data = helpers.encode_base64(module_data)1274 data = zipname + "|" + module_data1275 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_MODULE_IMPORT", data)1276 else:1277 print helpers.color("[!] Unable to locate zip compressed module")1278 else:1279 print helpers.color("[!] Please enter a valid module path")1280 def do_viewrepo(self, line):1281 "View all of the currently modules in the empire repository"1282 repoName = line.strip()1283 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_MODULE_VIEW", repoName)1284 def do_removerepo(self, line):1285 "Remove a module repo."1286 repoName = line.strip()1287 self.mainMenu.agents.add_agent_task(self.sessionID, "TASK_MODULE_REMOVE", repoName)1288 def complete_loadpymodule(self, text, line, begidx, endidx):1289 "Tab-complete a module import file path"1290 return helpers.complete_path(text, line)1291 def complete_pythonscript(self, text, line, begidx, endidx):1292 "Tab-complete a zip file path"1293 return helpers.complete_path(text, line)1294 def complete_usemodule(self, text, line, begidx, endidx):1295 "Tab-complete an EmPyre Python module path"1296 return self.mainMenu.complete_usemodule(text, line, begidx, endidx)1297 def complete_upload(self, text, line, begidx, endidx):1298 "Tab-complete an upload file path"1299 return helpers.complete_path(text, line)1300 # def complete_updateprofile(self, text, line, begidx, endidx):1301 # "Tab-complete an updateprofile path"1302 # return helpers.complete_path(text,line)1303class ListenerMenu(cmd.Cmd):1304 def __init__(self, mainMenu):1305 cmd.Cmd.__init__(self)1306 self.doc_header = 'Listener Commands'1307 self.mainMenu = mainMenu1308 # get all the the stock listener options1309 self.options = self.mainMenu.listeners.get_listener_options()1310 # set the prompt text1311 self.prompt = '(EmPyre: '+helpers.color("listeners", color="blue")+') > '1312 # display all active listeners on menu startup1313 messages.display_listeners(self.mainMenu.listeners.get_listeners())1314 # def preloop(self):1315 # traceback.print_stack()1316 # print a nicely formatted help menu1317 # stolen/adapted from recon-ng1318 def print_topics(self, header, cmds, cmdlen, maxcol):1319 if cmds:1320 self.stdout.write("%s\n" % str(header))1321 if self.ruler:1322 self.stdout.write("%s\n" % str(self.ruler * len(header)))1323 for c in cmds:1324 self.stdout.write("%s %s\n" % (c.ljust(17), getattr(self, 'do_' + c).__doc__))1325 self.stdout.write("\n")1326 def emptyline(self): pass1327 def do_exit(self, line):1328 "Exit EmPyre."1329 raise KeyboardInterrupt1330 def do_list(self, line):1331 "List all active listeners (or agents)."1332 if line.lower().startswith("agents"):1333 self.mainMenu.do_list("agents " + str(" ".join(line.split(" ")[1:])))1334 elif line.lower().startswith("listeners"):1335 self.mainMenu.do_list("listeners " + str(" ".join(line.split(" ")[1:])))1336 else:1337 self.mainMenu.do_list("listeners " + str(line))1338 def do_back(self, line):1339 "Go back to the main menu."1340 raise NavMain()1341 def do_agents(self, line):1342 "Jump to the Agents menu."1343 raise NavAgents()1344 def do_main(self, line):1345 "Go back to the main menu."1346 raise NavMain()1347 def do_exit(self, line):1348 "Exit EmPyre."1349 raise KeyboardInterrupt1350 def do_set(self, line):1351 "Set a listener option."1352 parts = line.split(" ")1353 if len(parts) > 1:1354 if parts[0].lower() == "defaultprofile" and os.path.exists(parts[1]):1355 try:1356 f = open(parts[1], 'r')1357 profileDataRaw = f.readlines()1358 1359 profileData = [l for l in profileDataRaw if (not l.startswith("#") and l.strip() != "")]1360 profileData = profileData[0].strip("\"")1361 f.close()1362 self.mainMenu.listeners.set_listener_option(parts[0], profileData)1363 except:1364 print helpers.color("[!] Error opening profile file %s" %(parts[1]))1365 else:1366 self.mainMenu.listeners.set_listener_option(parts[0], " ".join(parts[1:]))1367 else:1368 print helpers.color("[!] Please enter a value to set for the option")1369 def do_unset(self, line):1370 "Unset a listener option."1371 option = line.strip()1372 self.mainMenu.listeners.set_listener_option(option, '')1373 def do_info(self, line):1374 "Display listener options."1375 parts = line.split(" ")1376 if parts[0] != '':1377 if self.mainMenu.listeners.is_listener_valid(parts[0]):1378 listener = self.mainMenu.listeners.get_listener(parts[0])1379 messages.display_listener_database(listener)1380 else:1381 print helpers.color("[!] Please enter a valid listener name or ID")1382 else:1383 messages.display_listener(self.mainMenu.listeners.options)1384 def do_options(self, line):1385 "Display listener options."1386 parts = line.split(" ")1387 if parts[0] != '':1388 if self.mainMenu.listeners.is_listener_valid(parts[0]):1389 listener = self.mainMenu.listeners.get_listener(parts[0])1390 messages.display_listener_database(listener)1391 else:1392 print helpers.color("[!] Please enter a valid listener name or ID")1393 else:1394 messages.display_listener(self.mainMenu.listeners.options)1395 def do_kill(self, line):1396 "Kill one or all active listeners."1397 listenerID = line.strip()1398 if listenerID.lower() == "all":1399 try:1400 choice = raw_input(helpers.color("[>] Kill all listeners? [y/N] ", "red"))1401 if choice.lower() != "" and choice.lower()[0] == "y":1402 self.mainMenu.listeners.killall()1403 except KeyboardInterrupt as e:1404 print ""1405 else:1406 if listenerID != "" and self.mainMenu.listeners.is_listener_valid(listenerID):1407 self.mainMenu.listeners.shutdown_listener(listenerID)1408 self.mainMenu.listeners.delete_listener(listenerID)1409 else:1410 print helpers.color("[!] Invalid listener name or ID.")1411 def do_execute(self, line):1412 "Execute a listener with the currently specified options."1413 (success, message) = self.mainMenu.listeners.add_listener_from_config()1414 if success:1415 print helpers.color("[*] Listener '%s' successfully started." %(message))1416 else:1417 print helpers.color("[!] %s" %(message))1418 def do_run(self, line):1419 "Execute a listener with the currently specified options."1420 self.do_execute(line)1421 def do_usestager(self, line):1422 "Use an EmPyre stager."1423 parts = line.split(" ")1424 if parts[0] not in self.mainMenu.stagers.stagers:1425 print helpers.color("[!] Error: invalid stager module")1426 elif len(parts) == 1:1427 l = StagerMenu(self.mainMenu, parts[0])1428 l.cmdloop()1429 elif len(parts) == 2:1430 listener = parts[1]1431 if not self.mainMenu.listeners.is_listener_valid(listener):1432 print helpers.color("[!] Please enter a valid listener name or ID")1433 else:1434 self.mainMenu.stagers.set_stager_option('Listener', listener)1435 l = StagerMenu(self.mainMenu, parts[0])1436 l.cmdloop()1437 else:1438 print helpers.color("[!] Error in ListenerMenu's do_userstager()")1439 def do_launcher(self, line):1440 "Generate an initial launcher for a listener."1441 nameid = self.mainMenu.listeners.get_listener_id(line.strip())1442 if nameid:1443 listenerID = nameid1444 else:1445 listenerID = line.strip()1446 if listenerID != "" and self.mainMenu.listeners.is_listener_valid(listenerID):1447 # set the listener value for the launcher1448 stager = self.mainMenu.stagers.stagers["launcher"]1449 stager.options['Listener']['Value'] = listenerID1450 stager.options['Base64']['Value'] = "True"1451 # and generate the code1452 print stager.generate()1453 else:1454 print helpers.color("[!] Please enter a valid listenerID")1455 def complete_set(self, text, line, begidx, endidx):1456 "Tab-complete listener option values."1457 if line.split(" ")[1].lower() == "host":1458 return ["http://" + helpers.lhost()]1459 elif line.split(" ")[1].lower() == "redirecttarget":1460 # if we're tab-completing a listener name, return all the names1461 listenerNames = self.mainMenu.listeners.get_listener_names()1462 endLine = " ".join(line.split(" ")[1:])1463 mline = endLine.partition(' ')[2]1464 offs = len(mline) - len(text)1465 return [s[offs:] for s in listenerNames if s.startswith(mline)]1466 elif line.split(" ")[1].lower() == "type":1467 # if we're tab-completing the listener type1468 listenerTypes = ["native", "pivot", "hop", "foreign", "meter"]1469 endLine = " ".join(line.split(" ")[1:])1470 mline = endLine.partition(' ')[2]1471 offs = len(mline) - len(text)1472 return [s[offs:] for s in listenerTypes if s.startswith(mline)]1473 elif line.split(" ")[1].lower() == "certpath":1474 return helpers.complete_path(text, line, arg=True)1475 elif line.split(" ")[1].lower() == "defaultprofile":1476 return helpers.complete_path(text, line, arg=True)1477 mline = line.partition(' ')[2]1478 offs = len(mline) - len(text)1479 return [s[offs:] for s in self.options if s.startswith(mline)]1480 def complete_unset(self, text, line, begidx, endidx):1481 "Tab-complete listener option values."1482 mline = line.partition(' ')[2]1483 offs = len(mline) - len(text)1484 return [s[offs:] for s in self.options if s.startswith(mline)]1485 def complete_usestager(self, text, line, begidx, endidx):1486 "Tab-complete an EmPyre stager module path."1487 return self.mainMenu.complete_usestager(text, line, begidx, endidx)1488 def complete_kill(self, text, line, begidx, endidx):1489 "Tab-complete listener names"1490 # get all the listener names1491 names = self.mainMenu.listeners.get_listener_names() + ["all"]1492 mline = line.partition(' ')[2]1493 offs = len(mline) - len(text)1494 return [s[offs:] for s in names if s.startswith(mline)]1495 def complete_launcher(self, text, line, begidx, endidx):1496 "Tab-complete listener names/IDs"1497 # get all the listener names1498 names = self.mainMenu.listeners.get_listener_names()1499 mline = line.partition(' ')[2]1500 offs = len(mline) - len(text)1501 return [s[offs:] for s in names if s.startswith(mline)]1502 def complete_info(self, text, line, begidx, endidx):1503 "Tab-complete listener names/IDs"1504 return self.complete_launcher(text, line, begidx, endidx)1505 def complete_options(self, text, line, begidx, endidx):1506 "Tab-complete listener names/IDs"1507 return self.complete_launcher(text, line, begidx, endidx)1508class ModuleMenu(cmd.Cmd):1509 def __init__(self, mainMenu, moduleName, agent=None):1510 cmd.Cmd.__init__(self)1511 self.doc_header = 'Module Commands'1512 self.mainMenu = mainMenu1513 # get the current module/name1514 self.moduleName = moduleName1515 self.module = self.mainMenu.modules.modules[moduleName]1516 # set the prompt text1517 self.prompt = '(EmPyre: '+helpers.color(self.moduleName, color="blue")+') > '1518 # if this menu is being called from an agent menu1519 if agent:1520 # resolve the agent sessionID to a name, if applicable1521 agent = self.mainMenu.agents.get_agent_name(agent)1522 self.module.options['Agent']['Value'] = agent1523 # def preloop(self):1524 # traceback.print_stack()1525 def validate_options(self):1526 "Make sure all required module options are completed."1527 sessionID = self.module.options['Agent']['Value']1528 for option, values in self.module.options.iteritems():1529 if values['Required'] and ((not values['Value']) or (values['Value'] == '')):1530 print helpers.color("[!] Error: Required module option missing.")1531 return False1532 # # TODO: implement this all/autorun check1533 # try:1534 # # if we're running this module for all agents, skip this validation1535 # if sessionID.lower() != "all" and sessionID.lower() != "autorun": 1536 # modulePSVersion = int(self.module.info['MinPSVersion'])1537 # agentPSVersion = int(self.mainMenu.agents.get_ps_version(sessionID))1538 # # check if the agent/module PowerShell versions are compatible1539 # if modulePSVersion > agentPSVersion:1540 # print helpers.color("[!] Error: module requires PS version "+str(modulePSVersion)+" but agent running PS version "+str(agentPSVersion))1541 # return False1542 # except Exception as e:1543 # print helpers.color("[!] Invalid module or agent PS version!")1544 # return False1545 # check if the module needs admin privs1546 if self.module.info['NeedsAdmin']:1547 # if we're running this module for all agents, skip this validation1548 if sessionID.lower() != "all" and sessionID.lower() != "autorun":1549 if not self.mainMenu.agents.is_agent_elevated(sessionID):1550 print helpers.color("[!] Error: module needs to run in an elevated context.")1551 return False1552 # if the module isn't opsec safe, prompt before running1553 if not self.module.info['OpsecSafe']:1554 try:1555 choice = raw_input(helpers.color("[>] Module is not opsec safe, run? [y/N] ", "red"))1556 if not (choice.lower() != "" and choice.lower()[0] == "y"):1557 return False1558 except KeyboardInterrupt:1559 print ""1560 return False1561 return True1562 def emptyline(self): pass1563 # print a nicely formatted help menu1564 # stolen/adapted from recon-ng1565 def print_topics(self, header, cmds, cmdlen, maxcol):1566 if cmds:1567 self.stdout.write("%s\n" % str(header))1568 if self.ruler:1569 self.stdout.write("%s\n" % str(self.ruler * len(header)))1570 for c in cmds:1571 self.stdout.write("%s %s\n" % (c.ljust(17), getattr(self, 'do_' + c).__doc__))1572 self.stdout.write("\n")1573 def do_back(self, line):1574 "Go back a menu."1575 return True1576 def do_agents(self, line):1577 "Jump to the Agents menu."1578 raise NavAgents()1579 def do_listeners(self, line):1580 "Jump to the listeners menu."1581 raise NavListeners()1582 def do_main(self, line):1583 "Go back to the main menu."1584 raise NavMain()1585 def do_exit(self, line):1586 "Exit EmPyre."1587 raise KeyboardInterrupt1588 def do_list(self, line):1589 "Lists all active agents (or listeners)."1590 if line.lower().startswith("listeners"):1591 self.mainMenu.do_list("listeners " + str(" ".join(line.split(" ")[1:])))1592 elif line.lower().startswith("agents"):1593 self.mainMenu.do_list("agents " + str(" ".join(line.split(" ")[1:])))1594 else:1595 print helpers.color("[!] Please use 'list [agents/listeners] <modifier>'.")1596 def do_reload(self, line):1597 "Reload the current module."1598 print "\n" + helpers.color("[*] Reloading module") + "\n"1599 # reload the specific module1600 self.mainMenu.modules.reload_module(self.moduleName)1601 # regrab the reference1602 self.module = self.mainMenu.modules.modules[self.moduleName]1603 def do_info(self, line):1604 "Display module options."1605 messages.display_module(self.moduleName, self.module)1606 def do_options(self, line):1607 "Display module options."1608 messages.display_module(self.moduleName, self.module)1609 def do_set(self, line):1610 "Set a module option."1611 parts = line.split()1612 try:1613 option = parts[0]1614 if option not in self.module.options:1615 print helpers.color("[!] Invalid option specified.")1616 elif len(parts) == 1:1617 # "set OPTION"1618 # check if we're setting a switch1619 if self.module.options[option]['Description'].startswith("Switch."):1620 self.module.options[option]['Value'] = "True"1621 else:1622 print helpers.color("[!] Please specify an option value.")1623 else:1624 # otherwise "set OPTION VALUE"1625 option = parts[0]1626 value = " ".join(parts[1:])1627 if value == '""' or value == "''":1628 value = ""1629 self.module.options[option]['Value'] = value1630 except:1631 print helpers.color("[!] Error in setting option, likely invalid option name.")1632 def do_unset(self, line):1633 "Unset a module option."1634 option = line.split()[0]1635 if line.lower() == "all":1636 for option in self.module.options:1637 self.module.options[option]['Value'] = ''1638 if option not in self.module.options:1639 print helpers.color("[!] Invalid option specified.")1640 else:1641 self.module.options[option]['Value'] = ''1642 def do_usemodule(self, line):1643 "Use an EmPyre Python module."1644 module = line.strip()1645 if module not in self.mainMenu.modules.modules:1646 print helpers.color("[!] Error: invalid module")1647 else:1648 l = ModuleMenu(self.mainMenu, line, agent=self.module.options['Agent']['Value'])1649 l.cmdloop()1650 def do_creds(self, line):1651 "Display/return credentials from the database."1652 self.mainMenu.do_creds(line)1653 def do_execute(self, line):1654 "Execute the given EmPyre module."1655 if not self.validate_options():1656 return1657 agentName = self.module.options['Agent']['Value']1658 try:1659 moduleData = self.module.generate()1660 except Exception as e:1661 moduleData = False1662 moduleError = e1663 if not moduleData or moduleData == "":1664 print helpers.color("[!] Error: module produced an empty script")1665 print helpers.color("[!] Error Building module: " + str(moduleError), color="yellow")1666 dispatcher.send("[!] Error: module produced an empty script", sender="EmPyre")1667 return1668 try:1669 moduleData.decode('ascii')1670 except UnicodeDecodeError:1671 print helpers.color("[!] Error: module source contains non-ascii characters")1672 return1673 # strip all comments from the module1674 moduleData = helpers.strip_python_comments(moduleData)1675 taskCommand = ""1676 # check for opt tasking methods to prevent using a try/catch block1677 # elif dose not support try/catch native 1678 try:1679 if str(self.module.info['RunOnDisk']).lower() == "true":1680 RunOnDisk = True1681 if str(self.module.info['RunOnDisk']).lower() == "false":1682 RunOnDisk = False1683 except:1684 RunOnDisk = False1685 pass1686 # build the appropriate task command and module data blob1687 if str(self.module.info['Background']).lower() == "true":1688 # if this module should be run in the background1689 extention = self.module.info['OutputExtension']1690 if extention and extention != "":1691 # if this module needs to save its file output to the server1692 # format- [15 chars of prefix][5 chars extension][data]1693 saveFilePrefix = self.moduleName.split("/")[-1]1694 moduleData = saveFilePrefix.rjust(15) + extention.rjust(5) + moduleData1695 taskCommand = "TASK_CMD_JOB_SAVE"1696 else:1697 taskCommand = "TASK_CMD_JOB"1698 elif RunOnDisk:1699 # if this module is run on disk1700 extention = self.module.info['OutputExtension']1701 if self.module.info['OutputExtension'] and self.module.info['OutputExtension'] != "":1702 # if this module needs to save its file output to the server1703 # format- [15 chars of prefix][5 chars extension][data]1704 saveFilePrefix = self.moduleName.split("/")[-1][:15]1705 moduleData = saveFilePrefix.rjust(15) + extention.rjust(5) + moduleData1706 taskCommand = "TASK_CMD_WAIT_SAVE"1707 else:1708 taskCommand = "TASK_CMD_WAIT_DISK"1709 else:1710 # if this module is run in the foreground1711 extention = self.module.info['OutputExtension']1712 if self.module.info['OutputExtension'] and self.module.info['OutputExtension'] != "":1713 # if this module needs to save its file output to the server1714 # format- [15 chars of prefix][5 chars extension][data]1715 saveFilePrefix = self.moduleName.split("/")[-1][:15]1716 moduleData = saveFilePrefix.rjust(15) + extention.rjust(5) + moduleData1717 taskCommand = "TASK_CMD_WAIT_SAVE"1718 else:1719 taskCommand = "TASK_CMD_WAIT"1720 # if we're running the module on all modules1721 if agentName.lower() == "all":1722 try:1723 choice = raw_input(helpers.color("[>] Run module on all agents? [y/N] ", "red"))1724 if choice.lower() != "" and choice.lower()[0] == "y":1725 # signal everyone with what we're doing1726 print helpers.color("[*] Tasking all agents to run " + self.moduleName)1727 dispatcher.send("[*] Tasking all agents to run " + self.moduleName, sender="EmPyre")1728 # actually task the agents1729 for agent in self.mainMenu.agents.get_agents():1730 sessionID = agent[1]1731 # set the agent's tasking in the cache1732 self.mainMenu.agents.add_agent_task(sessionID, taskCommand, moduleData)1733 # update the agent log1734 dispatcher.send("[*] Tasked agent "+sessionID+" to run module " + self.moduleName, sender="EmPyre")1735 msg = "Tasked agent to run module " + self.moduleName1736 self.mainMenu.agents.save_agent_log(sessionID, msg)1737 except KeyboardInterrupt as e:1738 print ""1739 # set the script to be the global autorun1740 elif agentName.lower() == "autorun":1741 self.mainMenu.agents.set_autoruns(taskCommand, moduleData)1742 dispatcher.send("[*] Set module " + self.moduleName + " to be global script autorun.", sender="EmPyre")1743 else:1744 if not self.mainMenu.agents.is_agent_present(agentName):1745 print helpers.color("[!] Invalid agent name.")1746 else:1747 # set the agent's tasking in the cache1748 self.mainMenu.agents.add_agent_task(agentName, taskCommand, moduleData)1749 # update the agent log1750 dispatcher.send("[*] Tasked agent "+agentName+" to run module " + self.moduleName, sender="EmPyre")1751 msg = "Tasked agent to run module " + self.moduleName1752 self.mainMenu.agents.save_agent_log(agentName, msg)1753 def do_run(self, line):1754 "Execute the given EmPyre module."1755 self.do_execute(line)1756 def complete_set(self, text, line, begidx, endidx):1757 "Tab-complete a module option to set."1758 options = self.module.options.keys()1759 if line.split(" ")[1].lower() == "agent":1760 # if we're tab-completing "agent", return the agent names1761 agentNames = self.mainMenu.agents.get_agent_names() + ["all", "autorun"]1762 endLine = " ".join(line.split(" ")[1:])...
test_routing_algorithm.py
Source:test_routing_algorithm.py
...88 self.assertFalse(self.routing_manager.is_simulation_complete())89 def test_routing_blockages(self):90 move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])91 move_y_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.Y, 3])92 self.routing_manager.add_agent_task(0, move_x_task)93 for i in range(1, 3):94 self.assertEqual(TileState.RESERVED, self.arena.get_tile_state(i, 0))95 self.assertEqual(TileState.AGENT_TARGET, self.arena.get_tile_state(3, 0))96 self.routing_manager.add_agent_task(0, move_y_task)97 for i in range(1, 3):98 self.assertEqual(TileState.RESERVED, self.arena.get_tile_state(3, i))99 self.assertEqual(TileState.AGENT_TARGET, self.arena.get_tile_state(3, 3))100 def test_adding_and_completing_task_clears_blockage(self):101 move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])102 self.routing_manager.add_agent_task(0, move_x_task)103 for i in range(1, 3):104 self.assertEqual(TileState.RESERVED, self.arena.get_tile_state(i, 0))105 self.assertEqual(TileState.AGENT_TARGET, self.arena.get_tile_state(3, 0))106 self.routing_manager.signal_agent_event(0, AgentEvent.TASK_COMPLETED)107 for i in range(1, 4):108 self.assertEqual(TileState.FREE, self.arena.get_tile_state(i, 0))109 def test_completing_task_clears_agent_active(self):110 move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])111 self.routing_manager.add_agent_task(0, move_x_task)112 self.routing_manager.signal_agent_event(0, AgentEvent.TASK_COMPLETED)113 self.assertFalse(self.routing_manager.active_agents[0])114 def test_initialize_algorithm(self):115 self.routing_manager.initialize()116 self.assertTrue(self.routing_manager.initialized)117 def test_is_agent_at_goal(self):118 self.routing_manager.add_agent_goal(0, (0, 0))119 self.assertTrue(self.routing_manager.is_agent_at_goal(0))120 def test_start_new_task(self):121 move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])122 self.routing_manager.add_agent_task(0, move_x_task)123 self.routing_manager.start_new_task(0)124 self.assertTrue(self.routing_manager.active_agents[0])125class TestSingleAgentAlgorithm(unittest.TestCase):126 def setUp(self):127 time_step = 0.005128 self.arena = Arena(10, 10)129 self.biased_grid = BiasedGrid(self.arena.get_dimensions())130 self.agents = [Agent(0, 0, time_step), Agent(1, 1, time_step)]131 self.algorithm = SingleAgentAlgorithmMock(self.arena, self.agents, self.biased_grid)132 def tearDown(self):133 pass134 def test_reconstruct_empty_path_is_invalid(self):135 self.algorithm.node_path = list()136 status = self.algorithm.create_path()...
test_bulk_operations.py
Source:test_bulk_operations.py
1import pytest2from tenable_io.api.bulk_operations import BulkOpAddAgentRequest, BulkOpRemoveAgentRequest, BulkOpUnlinkAgentRequest3from tenable_io.api.models import BulkOpTask4@pytest.mark.vcr()5def test_bulk_operations_bulk_agent_add_and_status(client, new_agent_group, fetch_agent):6 add_agent_task = client.bulk_operations_api.bulk_add_agent(7 new_agent_group,8 BulkOpAddAgentRequest(9 items=[fetch_agent]10 )11 )12 assert isinstance(add_agent_task, BulkOpTask), u'The `bulk_add_agent` method did not return type `BulkOpTask`.'13 agent_status = client.bulk_operations_api.bulk_agent_status(add_agent_task.task_id)14 assert isinstance(agent_status,15 BulkOpTask), u'The `bulk_agent_status` method did not return type `BulkOpTask`.'16@pytest.mark.vcr()17def test_bulk_operations_bulk_agent_remove_and_status(client, new_agent_group, fetch_agent):18 remove_agent_task = client.bulk_operations_api.bulk_remove_agent(19 new_agent_group,20 BulkOpRemoveAgentRequest(21 items=[fetch_agent]22 )23 )24 assert isinstance(remove_agent_task,25 BulkOpTask), u'The `bulk_remove_agent` method did not return type `BulkOpTask`.'26 group_status = client.bulk_operations_api.bulk_agent_group_status(new_agent_group, remove_agent_task.task_id)27 assert isinstance(group_status,28 BulkOpTask), u'The `bulk_agent_group_status` method did not return type `BulkOpTask`.'29@pytest.mark.vcr()30def test_bulk_operations_bulk_agent_unlink(client, fetch_agent):31 unlink_agent_task = client.bulk_operations_api.bulk_unlink_agent(32 BulkOpUnlinkAgentRequest(items=[fetch_agent]))33 assert isinstance(unlink_agent_task,...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!