class WebSocketHandler(tornado.websocket.WebSocketHandler): # the client connected def open(self): print "New client connected" self.write_message("You are connected\n") # the client sent the message def on_message(self, message): print message if message.find('msg::input_json::') == 0: json_data = message[len('msg::input_json::'):] print json_data self.write_message('Recieved JSON\n') self.input_json_file_name = 'input_json.txt' file_ = open(self.input_json_file_name, 'w') file_.write(json_data) file_.write('\n') file_.close() self.write_message('Saved JSON to file ' + self.input_json_file_name + '\n') elif message.find('msg::simulate::') == 0: console_cmd = sys.prefix + '/bin/python main.py \'' + self.input_json_file_name + '\'' print console_cmd self.console_proc = subprocess.Popen(console_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) self.console_thread = KThread(target=self.console_thread_func) self.console_thread.setDaemon(True) self.console_thread.start() else: self.console_proc.stdin.write(message + '\n') def console_thread_func(self): while True: out = self.console_proc.stdout.read(1) if not out: break else: print out, self.write_message(out) # client disconnected def on_close(self): print "Client disconnected"
class NodeStatusPanel(wx.Panel): """ """ #---------------------------------------------------------------------- def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY, style= wx.BK_DEFAULT #wx.BK_TOP #wx.BK_BOTTOM #wx.BK_LEFT #wx.BK_RIGHT ) #size=(235,100) self.node_map = self.read_nodelist_from_file(NODELIST_FILEPATH) hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, 'Cluster nodes status:') hbox.Add(label, 0, wx.EXPAND|wx.RIGHT, 1) self.node_labels = [] for node in self.node_map.keys(): #response = os.system("ping -c 1 " + node) node_label = wx.StaticText(self, -1, node, style=wx.ALIGN_CENTER) #if response == 0: # node_label.SetForegroundColour('green') #else: # node_label.SetForegroundColour('red') hbox.Add(node_label, 1, wx.EXPAND|wx.RIGHT, 1) self.node_labels.append(node_label) self.SetSizer(hbox) self.ping_thread = KThread(target=self.ping_thread_func) self.ping_thread.setDaemon(True) self.ping_thread.start() def ping_thread_func(self): while True: for node_label in self.node_labels: ping = subprocess.Popen(["ping", "-c", "1", node_label.GetLabel()], stdout=subprocess.PIPE, shell=False) ping.wait() if ping.returncode != 0: node_label.SetBackgroundColour('#F79C94') else: node_label.SetBackgroundColour('#A3F291') time.sleep(CHECK_PING_TIME_PERIOD) def read_nodelist_from_file(self, nodelist_filepath): '''Read list of cluster nodes from file. Args: nodelist_file: Name of file with list of cluster nodes. ''' node_map = {} # open nodelist file #logger_MininetCE.info('Reading nodelist from file') nodelist_file = open(nodelist_filepath, 'r') file_lines = nodelist_file.readlines() for file_line in file_lines: splitted_line = file_line.split(' ') node_map[splitted_line[0]] = splitted_line[2] return node_map
class GraphEditorPanel(wx.Panel): """ """ #---------------------------------------------------------------------- def __init__(self, parent, wv, inf_hosts_list=None): wx.Panel.__init__(self, parent, id=wx.ID_ANY, style= wx.BK_DEFAULT #wx.BK_TOP #wx.BK_BOTTOM #wx.BK_LEFT #wx.BK_RIGHT ) #size=(235,100) self.tabs = {'Result', 'Visualizer', 'WorldMap'} self.wv = wv if MALWARE_MODE_ON: self.inf_hosts_list = inf_hosts_list self. graph_data = "" self.current_tab = 'Editor' self.options_status = False hbox = wx.BoxSizer(wx.HORIZONTAL) self.live_btn = CustomButton(self, -1, "Live") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnLiveButton, self.live_btn) hbox.Add(self.live_btn, 1, wx.EXPAND|wx.RIGHT, 1) self.options_btn = CustomButton(self, -1, "Options") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnOptionsButton, self.options_btn) hbox.Add(self.options_btn, 1, wx.EXPAND|wx.RIGHT, 1) if MALWARE_MODE_ON: self.showinf_btn = CustomButton(self, -1, "Show Inf") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnShowInfButton, self.showinf_btn) self.showinf_btn.Hide() hbox.Add(self.showinf_btn, 1, wx.EXPAND|wx.RIGHT, 1) self.showinf_chb = wx.CheckBox(self, label='Show Inf') self.showinf_chb.Bind(wx.EVT_CHECKBOX, self.OnShowInfChbClick) hbox.Add(self.showinf_chb, 1, wx.EXPAND|wx.RIGHT, 1) self.showinf_chb.Enable(False) self.update_thread = KThread(target=self.update_thread_func) self.update_thread.setDaemon(True) self.thread_already_created = True self.editor_btn = CustomButton(self, -1, "Editor") #self.editor_btn.SetBackgroundColour('#FFFFFF') self.Bind(wx.EVT_BUTTON, self.OnEditorButton, self.editor_btn) hbox.Add(self.editor_btn, 1, wx.EXPAND|wx.RIGHT, 1) self.result_btn = CustomButton(self, -1, "Result") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnResultButton, self.result_btn) hbox.Add(self.result_btn, 1, wx.EXPAND|wx.RIGHT, 1) self.visualiser_btn = CustomButton(self, -1, "Visualiser") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnVisualiserButton, self.visualiser_btn) hbox.Add(self.visualiser_btn, 1, wx.EXPAND|wx.RIGHT, 1) self.worldmap_btn = CustomButton(self, -1, "World Map") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnWorldMapButton, self.worldmap_btn) hbox.Add(self.worldmap_btn, 1, wx.EXPAND|wx.RIGHT, 1) btn = CustomButton(self, -1, "Undo") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnUndoButton, btn) hbox.Add(btn, 1, wx.EXPAND|wx.RIGHT, 1) btn = CustomButton(self, -1, "Reset") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnResetButton, btn) hbox.Add(btn, 1, wx.EXPAND|wx.RIGHT, 1) btn = CustomButton(self, -1, "Help") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnHelpButton, btn) hbox.Add(btn, 1, wx.EXPAND|wx.RIGHT, 1) self.SetSizer(hbox) def show_options(self): self.wv.RunScript("$('#graph_ed').animate({'width': my_graph_editor.get_SIZE_x() + 185 + 'px'}, " "{queue: true, duration: 'fast', easing: 'linear', complete: function (){ " " $('#graph_ed' + ' #graph_editor_tweaks').slideToggle('fast'); " " my_graph_editor.set_UIside_panel_opened(true);}});") self.wv.RunScript("$('#graph_ed' + ' #tweaks_button').toggleClass('graph_editor_button_on');") self.options_status = True #self.options_btn.SetBackgroundColour('#FFFFFF') def hide_options(self): self.wv.RunScript("$('#graph_ed' + ' #graph_editor_tweaks').slideToggle('fast', function ()" " {$('#graph_ed').animate({'width': my_graph_editor.get_SIZE_x() +'px'}," " {queue: true, duration: 'fast', easing: 'linear'}); " " my_graph_editor.set_UIside_panel_opened(false);});") self.wv.RunScript("$('#graph_ed' + ' #tweaks_button').toggleClass('graph_editor_button_on');") self.options_status = False #self.options_btn.SetBackgroundColour('#B2B2B2') #self.editor_btn.SetBackgroundColour('#FFFFFF') def show_result(self): self.wv.RunScript("document.getElementById('result_image').src = \"result.png?random=\"+new Date().getTime();") self.wv.RunScript("$('#graph_ed' + ' #result').show();") self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).hide();") self.wv.RunScript("$('#graph_ed'+' #result_button').toggleClass('graph_editor_button_on');") self.current_tab = 'Result' #self.result_btn.SetBackgroundColour('#FFFFFF') #self.editor_btn.SetBackgroundColour('#B2B2B2') def hide_result(self): self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).show();") self.wv.RunScript("$('#graph_ed' + ' #result').hide();") self.wv.RunScript("$('#graph_ed' + ' #result_button').toggleClass('graph_editor_button_on');") self.current_tab = 'Editor' #self.result_btn.SetBackgroundColour('#B2B2B2') #self.editor_btn.SetBackgroundColour('#FFFFFF') def show_visualiser(self): self.wv.RunScript("$('#graph_ed' + ' #vizualizer').show();") self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).hide();") self.wv.RunScript("$('#graph_ed'+' #vizualizer_button').toggleClass('graph_editor_button_on');") self.current_tab = 'Visualiser' #self.visualiser_btn.SetBackgroundColour('#FFFFFF') #self.editor_btn.SetBackgroundColour('#B2B2B2') def hide_visualiser(self): self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).show();") self.wv.RunScript("$('#graph_ed' + ' #vizualizer').hide();") self.wv.RunScript("$('#graph_ed' +' #vizualizer_button').toggleClass('graph_editor_button_on');") self.current_tab = 'Editor' #self.visualiser_btn.SetBackgroundColour('#B2B2B2') #self.editor_btn.BackgroundColour('#FFFFFF') def show_worldmap(self): self.wv.RunScript("$('#graph_ed' + ' #worldmap').show();") self.wv.RunScript("$('#graph_ed' + ' #worldmap').fadeIn().resize();") self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).hide();") self.wv.RunScript("$('#graph_ed'+' #worldmap_button').toggleClass('graph_editor_button_on');") self.current_tab = 'WorldMap' #self.worldmap_btn.SetBackgroundColour('#FFFFFF') #self.editor_btn.SetBackgroundColour('#B2B2B2') def hide_worldmap(self): self.wv.RunScript("canvas = $('#graph_ed' +' canvas')[0];") self.wv.RunScript("$(canvas).show();") self.wv.RunScript("$('#graph_ed' + ' #worldmap').hide();") self.wv.RunScript("$('#graph_ed' +' #worldmap_button').toggleClass('graph_editor_button_on');") self.current_tab = 'Editor' #self.worldmap_btn.SetBackgroundColour('#B2B2B2') #self.editor_btn.SetBackgroundColour('#FFFFFF') def go_to_editor_tab(self): if self.current_tab == 'Editor' and self.options_status == True: self.hide_options() if self.current_tab == 'Result': self.hide_result() if self.current_tab == 'Visualiser': self.hide_visualiser() if self.current_tab == 'WorldMap': self.hide_worldmap() def set_graph_data(self, graph_data): self.graph_data = graph_data def enable_showinf_chb(self): self.showinf_chb.Enable(True) def change_hosts_color(self, graph_data): # Draw in green only leaves js = json.loads(graph_data) G = nx.Graph() for edge in js['edges']: if int(edge[0]) not in G.nodes(): G.add_node(int(edge[0])) if int(edge[1]) not in G.nodes(): G.add_node(int(edge[1])) G.add_edge(int(edge[0]), int(edge[1])) leaves = define_leaves_in_graph(G) for l in leaves: self.wv.RunScript("my_graph_editor.set_node_vulnerable(\"" + str(l) + "\");") def OnLiveButton(self, event): if self.current_tab == 'Editor': self.wv.RunScript("my_graph_editor.toggle_live();") def OnOptionsButton(self, event): if not self.options_status and self.current_tab == 'Editor': self.show_options() elif self.options_status and self.current_tab == 'Editor': self.hide_options() def OnShowInfButton(self, event): if self.current_tab == 'Editor': for host in self.inf_hosts_list: self.wv.RunScript("my_graph_editor.set_node_infected(\"" + host[1:] + "\")") def OnShowInfChbClick(self, event): sender = event.GetEventObject() isChecked = sender.GetValue() if isChecked: self.change_hosts_color(self.graph_data) if not self.thread_already_created: self.update_thread = KThread(target=self.update_thread_func) self.update_thread.setDaemon(True) self.update_thread.start() else: self.update_thread.kill() self.thread_already_created = False self.wv.RunScript("my_graph_editor.set_nodes_invulnerable()") def update_thread_func(self): while True: time.sleep(1) evt = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.showinf_btn.GetId()) wx.PostEvent(self.showinf_btn, evt) def OnEditorButton(self, event): self.go_to_editor_tab() #self.editor_btn.SetBackgroundColour('#FFFFFF') def OnResultButton(self, event): if self.current_tab == 'Result': self.hide_result() else: self.go_to_editor_tab() self.show_result() def OnVisualiserButton(self, event): if self.current_tab == 'Visualiser': self.hide_visualiser() else: self.go_to_editor_tab() self.show_visualiser() def OnWorldMapButton(self, event): if self.current_tab == 'WorldMap': self.hide_worldmap() else: self.go_to_editor_tab() self.show_worldmap() def OnUndoButton(self, event): if self.current_tab == 'Editor': self.wv.RunScript("my_graph_editor.undo_remove();") def OnResetButton(self, event): if self.current_tab == 'Editor': self.wv.RunScript("my_graph_editor.erase_graph();") def OnHelpButton(self, event): self.wv.RunScript("$('#help_dialog').dialog('open');")
class WebPanel(wx.Panel): """Class fo WebPanel. TODO """ def __init__(self, parent): '''Cunstructor of WebPanel. Args: parent: ''' self.p = None wx.Panel.__init__(self, parent) if MALWARE_MODE_ON: self.inf_hosts_list = [] self.hosts_list = [] self.current = os.path.realpath(parent.parent.html_path) self.frame = parent if parent: self.titleBase = parent.GetTitle() sizer = wx.BoxSizer(wx.VERTICAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL) self.wv = webview.WebView.New(self) self.wv.LoadURL('file://' + self.current) self.contentNotSaved = True ## Main function buttons row btn = CustomButton(self, -1, "Simulate") # btn.SetBackgroundColour('#93FF8C') B2B2B2 self.Bind(wx.EVT_BUTTON, self.OnSimulateButton, btn) btnSizer.Add(btn, 1, wx.EXPAND|wx.RIGHT, 1) btn = CustomButton(self, -1, "DB:JSON") btn.SetBackgroundColour('#B5B5B5') self.Bind(wx.EVT_BUTTON, self.OnDBJsonButton, btn) btnSizer.Add(btn, 1, wx.EXPAND|wx.RIGHT, 1) btn = CustomButton(self, -1, "Random") self.Bind(wx.EVT_BUTTON, self.OnRandomButton, btn) btnSizer.Add(btn, 1, wx.EXPAND) btn = CustomButton(self, -1, "LinearX") self.Bind(wx.EVT_BUTTON, self.OnLinearButton, btn) btnSizer.Add(btn, 1, wx.EXPAND) self.node_num = CustomTextCtrl(self) #size=(117, -1) self.node_num.ChangeValue(str(17)) btnSizer.Add(self.node_num, 0, wx.EXPAND) btn = CustomButton(self, -1, "Save") self.Bind(wx.EVT_BUTTON, self.OnSaveButton, btn) btnSizer.Add(btn, 1, wx.EXPAND|wx.RIGHT,1) btn = CustomButton(self, -1, "Load") self.Bind(wx.EVT_BUTTON, self.OnLoadButton, btn) btnSizer.Add(btn, 1, wx.ALIGN_RIGHT) sizer.Add(btnSizer, 0, wx.EXPAND) ## Panel that shows the availability of cluster nodes node_status_panel = NodeStatusPanel(self) sizer.Add(node_status_panel, 0, wx.EXPAND) ## Graph editor control panel if MALWARE_MODE_ON: self.graph_editor_panel = GraphEditorPanel(self, self.wv, self.inf_hosts_list) else: self.graph_editor_panel = GraphEditorPanel(self, self.wv, None) sizer.Add(self.graph_editor_panel, 0, wx.EXPAND) sizer.Add(self.wv, 1, wx.EXPAND) #self.console = CustomTextCtrl_readonly(self, wx.ID_ANY, size=(235,100)) #font_console = wx.Font(9, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') #self.console.SetFont(font_console) ## Console tab panel console_tabs = ConsoleTabPanel(self) self.console = console_tabs.get_console() #self.controller = CustomTextCtrl_readonly(self, wx.ID_ANY) #size=(235,100) #font_controller = wx.Font(7, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') #self.controller.SetFont(font_controller) if MALWARE_MODE_ON: ## Malware center panel self.malware_center = CustomTextCtrl_readonly(self, wx.ID_ANY) font_malware_center = wx.Font(7, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') self.malware_center.SetFont(font_malware_center) ## Controller tab panel controller_tabs = ControllerTabPanel(self) self.controller = controller_tabs.get_console() ## Send command row btn = CustomButton(self, wx.ID_ANY, 'Send') self.Bind(wx.EVT_BUTTON, self.onSendButton, btn) self.cmd_line = CustomTextCtrl(self, wx.ID_ANY) #size=(235,-1) font_cmd_line = wx.Font(11, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') self.cmd_line.SetFont(font_cmd_line) self.cmd_line.Bind(wx.EVT_KEY_DOWN, self.onKeyPress) # Add widgets to a sizer con_hsizer = wx.BoxSizer(wx.HORIZONTAL) con_hsizer.Add(self.cmd_line, 3, wx.EXPAND) con_hsizer.Add(btn, 1, wx.EXPAND) con_sizer = wx.BoxSizer(wx.VERTICAL) #con_sizer.Add(self.controller, 1, wx.BOTTOM|wx.EXPAND, 1) if MALWARE_MODE_ON: con_sizer.Add(wx.StaticText(self, -1, 'Malware center output:'), 0, wx.BOTTOM|wx.EXPAND, 1) con_sizer.Add(self.malware_center, 1, wx.BOTTOM|wx.EXPAND, 1) con_sizer.Add(controller_tabs, 1, wx.BOTTOM|wx.EXPAND, 1) #con_sizer.Add(self.console, 2, wx.ALL|wx.EXPAND) con_sizer.Add(console_tabs, 5, wx.ALL|wx.EXPAND) con_sizer.Add(con_hsizer, 0, wx.ALL|wx.EXPAND) glob_sizer = wx.BoxSizer(wx.HORIZONTAL) glob_sizer.Add(con_sizer, 1, wx.EXPAND|wx.RIGHT, 1) glob_sizer.Add(sizer, 3, wx.EXPAND) self.SetSizer(glob_sizer) self.Layout() #self.wv.LoadURL('file://' + self.current) def change_hosts_color(self, graph_data): # Draw in green only leaves js = json.loads(graph_data) G = nx.Graph() for edge in js['edges']: if int(edge[0]) not in G.nodes(): G.add_node(int(edge[0])) if int(edge[1]) not in G.nodes(): G.add_node(int(edge[1])) G.add_edge(int(edge[0]), int(edge[1])) leaves = define_leaves_in_graph(G) for l in leaves: self.wv.RunScript("my_graph_editor.set_node_vulnerable(\"" + str(l) + "\");") def OnDropFiles(self, x, y, filenames): print('FILE!!!') def onKeyPress(self, event): keycode = event.GetKeyCode() if keycode == 13: # ENTER KEY self.onSendButton(event) event.Skip() def onSendButton(self, event): cmd = self.cmd_line.GetValue() if cmd != 'exit': self.console_proc.stdin.write(cmd + '\n') self.cmd_line.ChangeValue('') else: self.console_proc.stdin.write(cmd + '\n') #self.console_thread.kill() self.cmd_line.ChangeValue('') self.controller_thread.kill() self.controller_proc.terminate() self.malware_center_thread.kill() self.malware_center_proc.terminate() def OnLoadButton(self, event): if self.contentNotSaved: if wx.MessageBox("Current content has not been saved! Proceed?", "Please confirm", wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO: return openFileDialog = wx.FileDialog(self, "Open NPS Graph file", "", "", "NPS Graph files (*.nps)|*.nps", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return load_file = open(openFileDialog.GetPath(), 'r') graph_data = load_file.read() print graph_data self.wv.RunScript("jrg = '%s'" % graph_data) self.wv.RunScript("my_graph_editor.import_from_JSON(jrg)") load_file.close() def OnSaveButton(self, event): saveFileDialog = wx.FileDialog(self, "Save NPS Graph file", "", "", "NPS Graph files (*.nps)|*.nps", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if saveFileDialog.ShowModal() == wx.ID_CANCEL: return #output_stream = wx.FileOutputStream(saveFileDialog.GetPath()) prev_title = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = my_graph_editor.export_sage()") graph_data = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = %s" % prev_title) save_file = open(saveFileDialog.GetPath(), 'w') save_file.write(graph_data) save_file.close() #if not output_stream.IsOk(): # wx.LogError("Cannot save current contents in file '%s'."%saveFileDialog.GetPath()) # return def OnSimulateButton(self, event): os.system("cp GUI/res/not_ready.png GUI/result.png") # Save current graph self.console.ChangeValue('') self.controller.ChangeValue('') if MALWARE_MODE_ON: self.malware_center.ChangeValue('') prev_title = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = my_graph_editor.export_sage()") graph_data = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = %s" % prev_title) # p = self.GetParent() # p.set_graph_data(graph_data) if MALWARE_MODE_ON: self.graph_editor_panel.set_graph_data(graph_data) self.graph_editor_panel.enable_showinf_chb() #self.change_hosts_color(graph_data) malware_center_cmd = "python " + MALWARE_CENTER_PATH + "/malware_center.py " + \ MALWARE_CENTER_IP + ' ' + str(MALWARE_CENTER_PORT) self.malware_center_proc = subprocess.Popen(malware_center_cmd, stdout=subprocess.PIPE, shell=True) self.malware_center_thread = KThread(target=self.malware_center_thread_func) self.malware_center_thread.setDaemon(True) self.malware_center_thread.start() controller_cmd = "java -jar " + CONTROLLER_PATH + "/target/floodlight.jar" self.controller_proc = subprocess.Popen(controller_cmd, stdout=subprocess.PIPE, shell=True) self.controller_thread = KThread(target=self.controller_thread_func) self.controller_thread.setDaemon(True) self.controller_thread.start() #self.controller.AppendText("CONTROLLER ON") #save graph data to tmp file file_name = 'tmp/topo.nps' graph_file = open(file_name, 'w') graph_file.write(graph_data) graph_file.close() #console_cmd = sys.prefix + '/bin/python main.py \'' + graph_data + '\'' #self.console_proc = subprocess.Popen(console_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) #self.console_thread = KThread(target=self.console_thread_func) #self.console_thread.setDaemon(True) #self.console_thread.start() console_cmd = sys.prefix + '/bin/python main.py \'' + file_name + '\'' self.console_proc = subprocess.Popen(console_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) self.console_thread = KThread(target=self.console_thread_func) self.console_thread.setDaemon(True) self.console_thread.start() def OnDBJsonButton(self, event): prev_title = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = my_graph_editor.export_sage()") graph_data = self.wv.GetCurrentTitle() self.wv.RunScript("document.title = %s" % prev_title) # graph_data = cookies.split('=')[1] # print(graph_data) print(graph_data) # p = self.GetParent() # p.set_graph_data(graph_data) def OnRandomButton(self, event): raw_value = self.node_num.GetValue().strip() # numeric check if all(x in '0123456789.+-' for x in raw_value): # convert to float and limit to 2 decimals value = round(float(raw_value), 2) self.node_num.ChangeValue(str(value)) G = nx.barabasi_albert_graph(value, 1, 777) js_str = self.import_from_networkx_to_json(G) self.wv.RunScript("jrg = '%s'" % js_str) self.wv.RunScript("my_graph_editor.import_from_JSON(jrg)") else: self.node_num.ChangeValue("Number only") def OnLinearButton(self, event): raw_value = self.node_num.GetValue().strip() # numeric check if all(x in '0123456789.' for x in raw_value): # convert to float and limit to 2 decimals value = round(float(raw_value), 2) self.node_num.ChangeValue(str(value)) G = nx.path_graph(int(value)) new_node_num = int(value) for node_num,deg in nx.degree(G).items(): if deg > 1: G.add_node(new_node_num) G.add_edge(new_node_num, node_num) new_node_num += 1 js_str = self.import_from_networkx_to_json(G) self.wv.RunScript("jrg = '%s'" % js_str) self.wv.RunScript("my_graph_editor.import_from_JSON(jrg)") else: self.node_num.ChangeValue("Number only") def import_from_networkx_to_json(self, G): pos = nx.spring_layout(G) js_data = {} js_data["vertices"] = [] js_data["pos"] = {} for n in G.nodes(): js_data["vertices"].append(str(n)) js_data["pos"][str(n)] = [pos[n][0], pos[n][1]] js_data["edges"] = [] for e in G.edges(): js_data["edges"].append([str(e[0]), str(e[1]), None]) js_data["name"] = "G" js_str = str(js_data) js_str = js_str.replace('None','null') js_str = js_str.replace('\'','\"') return js_str def malware_center_thread_func(self): while True: out = self.malware_center_proc.stdout.readline() if out == '' and self.malware_center_proc.poll() != None: break if out != '': if "new worm instance " in out: host = out.split()[3].split(':')[0].split('-')[0] #self.wv.RunScript("my_graph_editor.set_node_infected(\"3\")") print "my_graph_editor.set_node_infected(\"" + host[1:] + "\")" self.inf_hosts_list.append(host) #self.wv.RunScript("my_graph_editor.set_node_infected(\"" + host[1:] + "\")") wx.CallAfter(self.malware_center.AppendText, out) def controller_thread_func(self): #FOR HUGE TOPO# wx.CallAfter(self.controller.AppendText, 'CONTROLLER ON') while True: #time.sleep(1) out = self.controller_proc.stdout.readline() if out == '' and self.controller_proc.poll() != None: break if out != '': #wx.CallAfter(self.controller.AppendText, out) pass def console_thread_func(self): while True: out = self.console_proc.stdout.read(1) if not out: break else: wx.CallAfter(self.console.AppendText, out)
class WebSocketHandler(tornado.websocket.WebSocketHandler): # the client connected # def __init__(self): # self.already_run_simulation = False # def open(self): print "New client connected" if os.path.isfile("tmp/groups.txt"): os.remove("tmp/groups.txt") self.write_message("You are connected\n") # the client sent the message def on_message(self, message): print message if message.find('msg::input_json::') == 0: json_data = message[len('msg::input_json::'):] print json_data self.write_message('Recieved JSON\n') self.input_json_file_name = 'input_json.txt' file_ = open(self.input_json_file_name, 'w') file_.write(json_data) file_.write('\n') file_.close() self.write_message('Saved JSON to file ' + self.input_json_file_name + '\n') elif message.find('msg::simulate::') == 0: console_cmd = sys.prefix + '/bin/python main.py \'' + self.input_json_file_name + '\'' print console_cmd self.console_proc = subprocess.Popen(console_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) self.console_mon_thread = KThread(target=self.console_mon_thread_func) self.console_mon_thread.setDaemon(True) self.console_mon_thread.start() elif message.find('msg::controller::') == 0: controller_cmd = "java -jar " + CONTROLLER_PATH + "/target/floodlight.jar" print controller_cmd self.controller_proc = subprocess.Popen(controller_cmd, stdout=subprocess.PIPE, shell=True) self.controller_mon_thread = KThread(target=self.controller_mon_thread_func) self.controller_mon_thread.setDaemon(True) self.controller_mon_thread.start() elif message.find('msg::groups::') == 0: file_ = open('tmp/groups.txt', 'r') groups = file_.readline() file_.close() self.write_message('msg::groups::' + groups) elif message.find('msg::hosts::') == 0: file_ = open('tmp/hosts.txt', 'r') hosts = file_.readline() file_.close() self.write_message('msg::hosts::' + hosts) elif message.find('msg::malwarecenter::') == 0: malware_center_cmd = "python " + MALWARE_CENTER_PATH + "/malware_center.py " + \ MALWARE_CENTER_IP + ' ' + str(MALWARE_CENTER_PORT) print malware_center_cmd self.malware_center_proc = subprocess.Popen(malware_center_cmd, stdout=subprocess.PIPE, shell=True) self.malware_center_thread = KThread(target=self.malware_center_thread_func) self.malware_center_thread.setDaemon(True) self.malware_center_thread.start() else: self.console_proc.stdin.write(message + '\n') def console_mon_thread_func(self): while True: out = self.console_proc.stdout.read(1) #self.console_proc.stdout.flush() if not out: break else: #print out, self.write_message(out) def controller_mon_thread_func(self): self.write_message("msg::controller::" + "CONTROLLER ON") while True: out = self.controller_proc.stdout.readline() if not out: break else: #print out, # self.write_message("msg::controller::" + out) pass def malware_center_thread_func(self): while True: out = self.malware_center_proc.stdout.readline() if not out: break else: print out, self.write_message("msg::malwarecenter::" + out) # if out == '' and self.malware_center_proc.poll() != None: # break # if out != '': # if "new worm instance " in out: # host = out.split()[3].split(':')[0].split('-')[0] # print "my_graph_editor.set_node_infected(\"" + host[1:] + "\")" # self.inf_hosts_list.append(host) # self.write_message("msg::malwarecenter::" + out) # client disconnected def on_close(self): print "Client disconnected"
class NodeStatusPanel(wx.Panel): """ """ #---------------------------------------------------------------------- def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY, style= wx.BK_DEFAULT #wx.BK_TOP #wx.BK_BOTTOM #wx.BK_LEFT #wx.BK_RIGHT ) #size=(235,100) self.node_map = self.read_nodelist_from_file(NODELIST_FILEPATH) hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, 'Cluster nodes status:') hbox.Add(label, 0, wx.EXPAND|wx.RIGHT, 1) self.node_labels = [] node_num = len(self.node_map.keys()) if node_num < 10: gridSizer = wx.GridSizer(rows=node_num%10, cols=node_num, hgap=1, vgap=1) else: gridSizer = wx.GridSizer(rows=node_num%10, cols=10, hgap=1, vgap=1) for node in self.node_map.keys(): node_label = wx.StaticText(self, -1, node, style=wx.ALIGN_CENTER) font = wx.Font(9, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') node_label.SetFont(font) gridSizer.Add(node_label, 0, wx.EXPAND) self.node_labels.append(node_label) hbox.Add(gridSizer, 1, wx.EXPAND|wx.RIGHT, 1) self.SetSizer(hbox) self.ping_thread = KThread(target=self.ping_thread_func) self.ping_thread.setDaemon(True) self.ping_thread.start() def ping_thread_func(self): #while True: # for node_label in self.node_labels: # ping = subprocess.Popen(["ping", "-c", "1", node_label.GetLabel()], stdout=subprocess.PIPE, shell=False) # ping.wait() # if ping.returncode != 0: # node_label.SetBackgroundColour('#F79C94') # else: # node_label.SetBackgroundColour('#A3F291') # time.sleep(CHECK_PING_TIME_PERIOD) while True: make_threaded(color_ping_func, [], self.node_labels) def read_nodelist_from_file(self, nodelist_filepath): '''Read list of cluster nodes from file. Args: nodelist_file: Name of file with list of cluster nodes. ''' node_map = {} # open nodelist file nodelist_file = open(nodelist_filepath, 'r') file_lines = nodelist_file.readlines() for file_line in file_lines: splitted_line = file_line.split(' ') node_map[splitted_line[0]] = splitted_line[2] return node_map