def auditlog_fields(): """ Retrieve Audit log Query fields. \nExample command: ./audit-logs.py auditlog_fields """ try: api_url = "/auditlog/fields" url = base_url + api_url response = requests.get(url=url, headers=header, verify=False) if response.status_code == 200: items = response.json() else: click.echo("Failed to get list of Audit Log Query fields " + str(response.text)) exit() tags = list() cli = cmd.Cmd() for item in items: tags.append(item['property'] + "(" + item['dataType'] + ")") click.echo("") click.echo(cli.columnize(tags, displaywidth=120)) except Exception as e: print('Exception line number: {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
def add(cls, obj, specialcommands): p = plac_core.parser_from(obj) c = cmd.Cmd(stdout=cls()) c.stdout.write('\n') c.print_topics('special commands', sorted(specialcommands), 15, 80) c.print_topics('custom commands', sorted(obj.commands), 15, 80) c.print_topics('commands run in external processes', sorted(obj.mpcommands), 15, 80) c.print_topics('threaded commands', sorted(obj.thcommands), 15, 80) p.helpsummary = str(c.stdout)
def __init__(self): try: self.debug = debug.Debug("risc") self.load_config() self.irc = irc.Irc(self.host, self.port, self.channel, self.nick) self.cmd = cmd.Cmd(self) self.init_db() self.ident = "" except: self.debug.critical("Risc.__init__: Exception occured while loading config settings - Make sure there's no missing field") raise SystemExit
def default(self, s): """Implement a slight exchange""" if s in self.skills: print("Your " + s.capitalize() + " skill entered the assigner with"\ " a level " + str(self.init_stats[s]) + ",\nAnd is now set "\ "to level " + str(self.values[s])) elif s[0] == "<" and s[-1] == ">": print("The commands shouldn't be surrounded by <>") print("That is just our way of distinguishing the print of a "\ "command from the print of a single \"normal\" word.") else: cmd.Cmd().default(s)
def columnize_suggestions(suggestions): suggestions = json.loads(suggestions) buf = io.StringIO() cli = cmd.Cmd(stdout=buf) cli.columnize(suggestions, displaywidth=shutil.get_terminal_size().columns) buf.seek(0) ret = buf.read() buf.close() return ret
def list(): """ Lists all the files associated with a particular password. """ # Prompt the user for a password password = getpass(prompt="Enter password for encryption:") v = vault.Vault(password) tmp = [] for entry in v.get_data_list(): data = entry.get_name().split() tmp.append(data[0].strip()) tmp = sorted(tmp) cmd.Cmd().columnize(tmp, displaywidth=80)
def __init__(self, port, baudrate): """Constructor""" self.cmd = cmd.Cmd() self.rsp = rsp.Rsp() self.terminate = False self.ser = serial.Serial() self.ser.port = port self.ser.baudrate = baudrate self.ser.timeout = 0.1 self.ser.setDTR(False) self.ser.setRTS(False) self.ser.open() self.lock = threading.Lock() info("Starting serial communication.... please wait") time.sleep(2) self.ser.reset_input_buffer() self.ser.reset_output_buffer()
def list_alarms_tags(): """ Retrieve list of alarm tags. \nExample command: ./alarms_apis.py list-alarms-tags """ click.secho("\nRetrieving the alarm tags\n") url = base_url + "/alarms/rulenamedisplay/keyvalue" response = requests.get(url=url, headers=header, verify=False) if response.status_code == 200: items = response.json()['data'] else: click.echo("Failed to get list of devices " + str(response.text)) exit() tags = list() cli = cmd.Cmd() for item in items: if item['key'] == "": continue tags.append(item['key']) click.echo(cli.columnize(tags, displaywidth=120))
def websocket_error(flow: mitmproxy.websocket.WebSocketFlow): """ A websocket connection has had an error. """ pass def process_request(flow): print("process_request") # print(flow.request.url) try: url = flow.request.url if url == URL: headers = flow.request.headers cookie = headers.get("cookie") if cookie: ctx.log.info(' cookie is:' + cookie) save_cookie(cookie) except Exception as e: ctx.log.info("error is " + str(e)) def save_cookie(cookie): # with open("cookie.txt", "w") as f: # f.write(cookie) redis.add(cookie) if __name__ == '__main__': cmd.Cmd() os.system("mitmdump -k -s mitproxy.py --set stream_websockets=true")
def main(): global lr, density, fix_choice if len(argv) > 3: density = argv[3] if len(argv) > 4: fix_choice = int(argv[4]) if len(argv) > 5: lr = argv[5] timestamp = datetime.datetime.fromtimestamp( time.time()).strftime('_%H_%M_%S') log = 'lr' + str(lr) + 'alg' + str(fix_choice) + timestamp + '.log' rtopo = RTopo() net = Mininet( topo=rtopo, link=TCLink, switch=OVSKernelSwitch, controller=RemoteController, autoSetMacs=True # --mac ) #c1 = net.addController('c1',controller = RemoteController, ip='127.0.0.1', port = 6633) #c1.start() #for i in range(1,m+1): # net['s'+str(i)].start([c1]) c = RemoteController('c', ip='127.0.0.1', port=6633) net.addController(c) K = 3 f = open(log, 'w') for i in range(K): f.write('0\n') f.write('@') f.close() request_file = "default.req" if len(argv) > 2: request_file = argv[2] f = open(request_file, 'r') num = int(f.readline()) cmd.Cmd('sudo rm sender.txt') for i in range(1, n + 1): cmd.Cmd('sudo rm h{}.txt'.format(i)) net.start() time.sleep(10) random.seed(7) for i in range(1, n + 1): for j in range(1, n + 1): if i != j: host1 = 'h' + str(i) host2 = 'h' + str(j) net[host2].cmd( 'sudo python2 receive.py {} {} 2>&1>>{}.txt&'.format( 4000 + i, 0, 'noise' + host2)) net[host1].cmd( 'sudo python2 randomtraffic.py {} {} {} {} 2>&1 >> {}.txt&' .format(random.randint(1, 100), net[host2].IP(), 4000 + i, density, 'traffic' + host1)) time.sleep(4) time0 = time.time() for i in range(num): starttime, host1, host2, portnum, packagesize = f.readline( )[:-1].split() starttime = float(starttime) + time0 net[host2].cmd('sudo python2 receive.py {} {} 2>&1>>{}.txt &'.format( portnum, starttime, host2)) net[host1].cmd( 'sudo python2 send.py {} {} {} {} {} {} {} {} 2>&1 >>sender{}.txt&' .format(packagesize, net[host2].IP(), portnum, starttime, lr, lr * 1000, fix_choice, log, fix_choice)) f.close() # hosts =[] # for i in range(2,4): # hosts.append('h'+str(i)) # portnum = range(5000+2,5000+4) # schedule = np.array(range(2,4))+ time.time() #time # #print(type(net['h1'])) # for t in range(0,2): # net[hosts[t]].cmd('python2 receive.py {} {} 2>&1>>{}.txt &'.format(portnum[t], schedule[t], hosts[t])) # net['h1'].cmd('python2 send.py {} {} {} {} {} 2>&1 >>sender.txt&'.format(100,net[hosts[t]].IP(), portnum[t], schedule[t], 0.1)) # tprint net[hosts[t]].IP() while True: if os.path.isfile(str(num) + ".kill"): cmd.Cmd('sudo rm *.kill') break else: time.sleep(0.5) net.stop()
def parseline(self, line): line = line.lower() return cmd.Cmd().parseline(line)
class TurtleRepl: cmd = cmd.Cmd() intro = "Welcome to the tootle shell. Type help or ? to list commands.\n" tootle = InteractiveTurtle() def __init__(self): # ----- Setting up cmd via delegation----- self.cmd.prompt = "(tootle) " # Should probably be in python core implementation def do_EOF(self, _): "Stop recording, close the turtle window, and exit: BYE" print("Thank you for using Turtle") repl.tootle.bye() return True self.cmd.do_EOF = types.MethodType(do_EOF, self.cmd) def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. """ cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if line == 'EOF': self.lastcmd = '' if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) # inspect the function to discover how many arguments are necessary sig = inspect.signature(func) # attempt to parse these arguments leftover = arg # TODO : function compact expression ? args = [] for n in range(0, len(sig.parameters)): arg, leftover, _ = self.parseline(leftover) args.append(arg) # recover unused arguments stop = func(*args) if not stop: if leftover: # recurse for the rest of the line stop = self.onecmd(leftover) return stop self.cmd.onecmd = types.MethodType(onecmd, self.cmd) # TODO # def complete(self, text, state): # """Return the next possible completion for 'text'. # # If a command has not been entered, then complete against command list. # Otherwise try to call complete_<command> to get list of completions. # """ # if state == 0: # import readline # origline = readline.get_line_buffer() # line = origline.lstrip() # stripped = len(origline) - len(line) # begidx = readline.get_begidx() - stripped # endidx = readline.get_endidx() - stripped # if begidx > 0: # cmd, args, foo = self.parseline(line) # if cmd == '': # compfunc = self.completedefault # else: # try: # compfunc = getattr(self, 'complete_' + cmd) # except AttributeError: # compfunc = self.completedefault # else: # compfunc = self.completenames # self.completion_matches = compfunc(text, line, begidx, endidx) # try: # return self.completion_matches[state] # except IndexError: # return None # self.cmd.complete = types.MethodType(complete, self.cmd) repl = self def do_move(self, distance): "Move the turtle forward by the specified distance: MOVE 10" repl.tootle.move(distance) def do_left(self, angle): "Turn turtle right by given number of degrees: LEFT 20" repl.tootle.left(angle) def do_right(self, angle): "Turn turtle right by given number of degrees: RIGHT 20" repl.tootle.right(angle) def do_home(self, arg): "Return turtle to the home postion: HOME" repl.tootle.home() # This is "read-only" def do_position(self, arg): "Print the current turle position: POSITION" print("Current position is {}".format(repl.tootle.position())) # This is "read-only" def do_heading(self, arg): "Print the current turle heading in degrees: HEADING" print("Current heading is {}".format(repl.tootle.heading())) # This is only cosmetic :-) def do_color(self, arg=None): "Set the color: COLOR BLUE" if arg is None or arg is '': arg = 'black' repl.tootle.color(arg.lower()) def do_reset(self, arg): "Clear the screen and return turtle to center: RESET" self.do_color() repl.tootle.reset() def do_bye(self, arg): "Stop recording, close the turtle window, and exit: BYE" print("Thank you for using Turtle") repl.tootle.bye() return True self.cmd.do_move = types.MethodType(do_move, self.cmd) self.cmd.do_left = types.MethodType(do_left, self.cmd) self.cmd.do_right = types.MethodType(do_right, self.cmd) self.cmd.do_home = types.MethodType(do_home, self.cmd) self.cmd.do_position = types.MethodType(do_position, self.cmd) self.cmd.do_heading = types.MethodType(do_heading, self.cmd) self.cmd.do_color = types.MethodType(do_color, self.cmd) self.cmd.do_reset = types.MethodType(do_reset, self.cmd) self.cmd.do_bye = types.MethodType(do_bye, self.cmd) # delegating def cmdloop(self): self.cmd.cmdloop(intro=self.intro)
import execute,cmd from PIL import ImageDraw if __name__ == '__main__': cmd.Cmd('')