예제 #1
0
    def mapping(self):
        """ Configure Ethernet port mapping
        """

        connected_interfaces = map(int, self.getConnectedInterfaceList())
        for (vlan, portlist) in self.config['vlans'].iteritems():
            for port in portlist:
                if port in connected_interfaces:
                    if not self.ethsw.mapping.has_key(port):
                        (destnode, destinterface)= self.getConnectedNeighbor(str(port))
                        porttype = self.config['ports'][port]
                        if self.ethsw.dynamips.intversion < 208.3 and porttype == 'qinq':
                            QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("ETHSW", "Port type"),  translate("ETHSW", "QinQ is only supported with Dynamips > 0.2.8 RC2"))
                            return

                        if destinterface.lower()[:3] == 'nio':
                            debug("ethsw_map: " + str(port) + ' to ' + porttype + ' ' + str(vlan) + ' ' + destinterface)
                            self.dynagen.ethsw_map(self.ethsw, port, porttype + ' ' + str(vlan) + ' ' + destinterface)
                        else:
                            debug("ethsw_map: " + str(port) + ' to ' + porttype + ' ' + str(vlan))
                            self.dynagen.ethsw_map(self.ethsw, port, porttype + ' ' + str(vlan))
                    elif self.ethsw.mapping.has_key(port):
                        porttype = self.config['ports'][port]
                        # check if the vlan or port type has changed
                        # WARNING: see unset_port()
                        if (vlan != self.ethsw.mapping[port][1]) or (porttype != self.ethsw.mapping[port][0]):
                            self.ethsw.unset_port(port)
                            self.dynagen.ethsw_map(self.ethsw, port, porttype + ' ' + str(vlan))
예제 #2
0
    def reconfigNode(self, new_hostname):
        """ Used when changing the hostname
        """

        old_hostname = self.hostname
        old_console = None
        old_aux = None
        if self.router:
            old_console = self.router.console
            old_aux = self.router.aux
        links = self.getEdgeList().copy()
        for link in links:
            globals.GApp.topology.deleteLink(link)
        self.delete_router()
        dynamips_files = glob.glob(
            os.path.normpath(self.hypervisor.workingdir) + os.sep +
            self.get_platform() + '?' + self.hostname + '*')
        for file in dynamips_files:
            try:
                new_file_name = os.path.basename(file).replace(
                    self.hostname, new_hostname)
                shutil.move(file,
                            os.path.dirname(file) + os.sep + new_file_name)
            except (OSError, IOError), e:
                debug("Warning: cannot move " + file + " to " +
                      os.path.dirname(file) + os.sep + new_file_name)
                continue
예제 #3
0
def connect(host, port, name):
        """ Start a telnet console and connect to it
        """

        try:
            console = globals.GApp.systconf['general'].term_cmd
            if console:
                console = console.replace('%h', host)
                console = console.replace('%p', str(port))
                console = console.replace('%d', name)
                debug('Start console with: ' + console)
                if globals.GApp.systconf['general'].use_shell:
                    #Если порт находится в диапазоне портов, отведенных для VNС окон qemu машин
                    #То устанавливается команда для запуска VNC клиента
                    if base_qemu_console <= port < base_qemu_console + deltaVideoPort*numberOfClients:
                        console = vncCommandForQemu + server + ":" + str(5900 + port) + " &"
                    sub.Popen(console, shell=True)
                else:
                    sub.Popen(console)
            else:
                if sys.platform.startswith('darwin'):
                    sub.Popen("/usr/bin/osascript -e 'tell application \"Terminal\" to do script with command \"telnet " + host + " " + str(port) +"; exit\"'", shell=True)
                elif sys.platform.startswith('win'):
                    sub.Popen("start telnet " +  host + " " + str(port), shell=True)
                else:
                    sub.Popen("xterm -T " + name + " -e 'telnet " + host + " " + str(port) + "' > /dev/null 2>&1 &", shell=True)
        except (OSError, IOError), e:
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("Console", "Console"), unicode(translate("Console", "Cannot start %s: %s")) % (console, e.strerror))
            return (False)
예제 #4
0
    def apply(self, message=False):
        """ Apply the IDLE PC to the router
        """
        
        try:
            selection = str(self.comboBox.currentText()).split(':')[0].strip('* ')
            index = int(selection)
            for node in globals.GApp.topology.nodes.values():
                if isinstance(node, IOSRouter) and node.hostname == self.router.hostname:
                    dyn_router = node.get_dynagen_device()
                    if globals.GApp.iosimages.has_key(dyn_router.dynamips.host + ':' + dyn_router.image):
                        image = globals.GApp.iosimages[dyn_router.dynamips.host + ':' + dyn_router.image]
                        debug("Register IDLE PC " + self.idles[index] + " for image " + image.filename)
                        image.idlepc = self.idles[index]
                        # Apply idle pc to devices with the same IOS image
                        for device in globals.GApp.topology.nodes.values():
                            if isinstance(device, IOSRouter) and device.config['image'] == image.filename:
                                debug("Apply IDLE PC " + self.idles[index] + " to " + device.hostname)
                                device.get_dynagen_device().idlepc = self.idles[index]
                                config = device.get_config()
                                config['idlepc'] = self.idles[index]
                                device.set_config(config)
                                device.setCustomToolTip()
                        break

            if message:
                QtGui.QMessageBox.information(self, translate("IDLEPCDialog", "IDLE PC"),
                                              unicode(translate("IDLEPCDialog", "IDLE PC value %s has been applied on %s")) % (self.idles[index], self.router.hostname))
        except lib.DynamipsError, msg:
            QtGui.QMessageBox.critical(self, translate("IDLEPCDialog", "Dynamips error"),  unicode(msg))
            return
예제 #5
0
    def stopProcHypervisors(self):
        """ Shutdown all started hypervisors
        """

        if globals.GApp != None and self.dynamips:
            self.setDefaults()
        hypervisors = globals.GApp.dynagen.dynamips.copy()
        for hypervisor in hypervisors.values():
            if isinstance(hypervisor, lib.Dynamips):
                try:
                    if globals.GApp.dynagen.dynamips.has_key(hypervisor.host +
                                                             ':' +
                                                             hypervisor.port):
                        debug(
                            "Hypervisor manager: reset and close hypervisor on %s port %i"
                            % (hypervisor['host'], hypervisor['port']))
                        hypervisor.reset()
                        hypervisor.close()
                        del globals.GApp.dynagen.dynamips[hypervisor.host +
                                                          ':' +
                                                          hypervisor.port]
                except:
                    continue
        for hypervisor in self.hypervisors:
            debug("Hypervisor manager: close hypervisor on %s port %i" %
                  (hypervisor['host'], hypervisor['port']))
            hypervisor['proc_instance'].terminate()
            time.sleep(0.5)
            hypervisor['proc_instance'].close()
            hypervisor['proc_instance'] = None
        self.hypervisors = []
예제 #6
0
    def __init__(self):

        self.__langs = {}
        self.__langs_code = []
        self.__lang_current = ""
        self.__lastTranslator = None
        self.__lastQtTranslator = None

        # Add i18n dirs depending on platform.
        if sys.platform.startswith('win'):

            # __file__ is not supported by py2exe
            if hasattr(sys, "frozen"):
                self.__i18n_dirs = [os.path.dirname(os.path.abspath(sys.executable)) + os.sep + "Langs"]
            else:
                self.__i18n_dirs = [os.path.dirname(os.path.abspath(GNS3.Langs.__file__))]

            if os.environ.has_key("APPDATA"):
                self.__i18n_dirs.append(os.environ["APPDATA"] + "\\gns3\\Langs")
            else:
                debug('Translation: unable to find APPDATA in environ')

        else:

            self.__i18n_dirs = [os.path.dirname(os.path.abspath(GNS3.Langs.__file__)), os.path.dirname(os.path.abspath(__main__.__file__))]
            if os.environ.has_key("HOME"):
                self.__i18n_dirs.append(os.environ["HOME"] + "/.gns3/Langs")
            else:
                debug('Translation: unable to find HOME in environ')

        # Now find all available languages...
        self.findAvailableLangs()
예제 #7
0
    def reconfigNode(self, new_hostname):
        """ Used when changing the hostname
        """

        old_console = None
        if self.emudev:
            old_console = self.emudev.console
        links = self.getEdgeList()
        if len(links):
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AnyEmuDevice", "New hostname"),
                                       translate("AnyEmuDevice", "Cannot rename a connected emulated device"))
            return
#         if self.hostname != new_hostname:
#             self.emudev.rename(new_hostname)
#             self.set_hostname(new_hostname)

        self.delete_emudev()
        if self.hostname != new_hostname:
            try:
                qemu_name = self.qemu.host + ':' + str(self.qemu.port)
                shutil.move(self.dynagen.dynamips[qemu_name].workingdir + os.sep + self.hostname, self.dynagen.dynamips[qemu_name].workingdir + os.sep + new_hostname)
            except:
                debug("Cannot move emulator's working directory")
        self.set_hostname(new_hostname)
        try:
            self.create_emudev()
            if old_console:
                self.emudev.console = old_console
        except lib.DynamipsError, msg:
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AnyEmuDevice", "Dynamips error"),  unicode(msg))
            self.delete_emudev()
            globals.GApp.topology.deleteNode(self.id)
            return
예제 #8
0
def pipe_connect(hostname, pipe_name):
    """ Start a telnet console and connect to a pipe
    """

    # We use Putty shipped with GNS3
    cmd = globals.GApp.systconf['general'].term_serial_cmd.strip()
    if not cmd:
        QtGui.QMessageBox.critical(
            globals.GApp.mainWindow, translate("Console", "Console"),
            translate(
                "Console",
                "No terminal command defined for local console/serial connections"
            ))
        return False

    if globals.GApp.systconf['general'].use_shell:
        shell = True
    else:
        shell = False

    cmd = cmd.replace('%s', pipe_name)
    cmd = cmd.replace('%d', hostname)
    debug('Start serial console program %s' % cmd)
    try:
        proc = sub.Popen(cmd, shell=shell)
    except (OSError, IOError), e:
        QtGui.QMessageBox.critical(
            globals.GApp.mainWindow, translate("Console", "Console"),
            translate("Console", "Cannot start %s: %s") % (cmd, e.strerror))
        return None
예제 #9
0
    def run(self):

        try:
            in_file = open(self.input_capture_file_path, 'rb')
        except IOError, e:
            debug("Cannot open capture file: %s") % unicode(e)
            self.exit()
            return
예제 #10
0
 def __init__(self, *args, **kwargs):
     AnyEmuDevice.__init__(self, *args, **kwargs)
     IDSDefaults.__init__(self)
     self.emudev_options.extend([
         'image1',
         'image2',
         ])
     debug('Hello, I have initialized and my model is %s' % self.model)
예제 #11
0
    def run(self):

        try:
            in_file = open(self.input_capture_file_path, 'rb')
        except IOError, e:
            debug("Cannot open capture file: %s") % unicode(e)
            self.exit()
            return
예제 #12
0
 def __init__(self, *args, **kwargs):
     AnyEmuDevice.__init__(self, *args, **kwargs)
     ASADefaults.__init__(self)
     self.emudev_options.extend([
         'initrd',
         'kernel',
         'kernel_cmdline',
         ])
     debug('Hello, I have initialized and my model is %s' % self.model)
예제 #13
0
 def __init__(self, *args, **kwargs):
     AnyEmuDevice.__init__(self, *args, **kwargs)
     IDSDefaults.__init__(self)
     self.unbased = False
     self.emudev_options.extend([
         'image1',
         'image2',
     ])
     debug('Hello, I have initialized and my model is %s' % self.model)
예제 #14
0
 def __init__(self, *args, **kwargs):
     AnyEmuDevice.__init__(self, *args, **kwargs)
     ASADefaults.__init__(self)
     self.emudev_options.extend([
         'initrd',
         'kernel',
         'kernel_cmdline',
     ])
     debug('Hello, I have initialized and my model is %s' % self.model)
예제 #15
0
    def waitQemu(self, binding):
        """ Wait Qemu until it accepts connections
        """

        # give 15 seconds to Qemu to accept connections
        count = 15
        progress = None
        connection_success = False
        timeout = 10
        s = None
        debug("Qemu manager: connecting to %s on port %i" %
              (binding, self.port))
        for nb in range(count + 1):
            if nb == 3:
                progress = QtGui.QProgressDialog(
                    translate("QemuManager",
                              "Connecting to Qemu on %s port %i ...") %
                    (binding, self.port), translate("QemuManager", "Abort"), 0,
                    count, globals.GApp.mainWindow)
                progress.setMinimum(1)
                progress.setWindowModality(QtCore.Qt.WindowModal)
                globals.GApp.processEvents(
                    QtCore.QEventLoop.AllEvents
                    | QtCore.QEventLoop.WaitForMoreEvents, 2000)
            if nb > 2:
                progress.setValue(nb)
                globals.GApp.processEvents(
                    QtCore.QEventLoop.AllEvents
                    | QtCore.QEventLoop.WaitForMoreEvents, 2000)
                if progress.wasCanceled():
                    progress.reset()
                    break
            try:
                s = socket.create_connection((binding, self.port), timeout)
            except:
                time.sleep(1)
                continue
            connection_success = True
            break

        if connection_success and s:
            s.close()
            time.sleep(0.2)
        else:
            QtGui.QMessageBox.critical(
                globals.GApp.mainWindow, 'Qemu Manager',
                translate("QemuManager", "Can't connect to Qemu on %s port %i")
                % (binding, self.port))
            self.stopQemu()
            return False
        if progress:
            progress.setValue(count)
            progress.deleteLater()
            progress = None
        return True
예제 #16
0
    def changeHypervisor(self):
        """ Called to change an hypervisor
        """

        if len(self.__edgeList) > 0:
            QtGui.QMessageBox.warning(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"),
                                      translate("AbstractNode", "The device must have no connection to other devices in order to change its hypervisor"))
            return

        if self.d:
            currentHypervisor = self.d
        else:
            currentHypervisor = "hostname:port"
        (text, ok) = QtGui.QInputDialog.getText(globals.GApp.mainWindow, translate("AbstractNode", "Set hypervisor"),
                                    translate("AbstractNode", "New hypervisor:"), QtGui.QLineEdit.Normal,
                                    currentHypervisor)

        if ok and text:
            hypervisor = unicode(text)
            if not re.search(r"""^.*:[0-9]*$""", text, re.UNICODE):
                QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"),
                                           translate("AbstractNode", "Invalid format for hypervisor (hostname:port is required)"))
                return
            (host, port) = hypervisor.rsplit(':',  1)

            if self.dynagen.dynamips.has_key(hypervisor):
                debug("Use an hypervisor: " + hypervisor)
                dynamips_hypervisor = self.dynagen.dynamips[hypervisor]
            else:
                debug("Connection to an hypervisor: " + hypervisor)

                # use project workdir
                if globals.GApp.workspace.projectWorkdir:
                    self.dynagen.defaults_config['workingdir'] = globals.GApp.workspace.projectWorkdir
                elif globals.GApp.systconf['dynamips'].workdir:
                    self.dynagen.defaults_config['workingdir'] = globals.GApp.systconf['dynamips'].workdir

                dynamips_hypervisor = self.dynagen.create_dynamips_hypervisor(host, int(port))
                if not dynamips_hypervisor:
                    QtGui.QMessageBox.critical(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"),
                                               translate("AbstractNode", "Can't connect to the hypervisor on %s") % hypervisor)
                    if self.dynagen.dynamips.has_key(hypervisor):
                        del self.dynagen.dynamips[hypervisor]
                    return

            self.dynagen.update_running_config()
            if self.d and self.dynagen.running_config[self.d].has_key(self.get_running_config_name()):
                config = self.dynagen.running_config[self.d][self.get_running_config_name()]
                self.dynagen.running_config[host + ':' + port][self.get_running_config_name()] = config
                del self.dynagen.running_config[self.d][self.get_running_config_name()]
            self.set_hypervisor(dynamips_hypervisor)
            self.reconfigNode(self.hostname)
            self.dynagen.update_running_config()
            QtGui.QMessageBox.information(globals.GApp.mainWindow, translate("AbstractNode", "Hypervisor"),
                                          translate("AbstractNode", "New hypervisor %s has been set on device %s") % (hypervisor, self.hostname))
예제 #17
0
    def waitQemu(self):
        """ Wait Qemu until it accepts connections
        """

        # give 15 seconds to Qemu to accept connections
        count = 15
        progress = None
        connection_success = False
        debug("Qemu manager: connect on " + str(self.port))
        for nb in range(count + 1):
            s = socket(AF_INET, SOCK_STREAM)
            s.setblocking(0)
            s.settimeout(300)
            if nb == 3:
                progress = QtGui.QProgressDialog(
                    unicode(translate("QemuManager", "Connecting to Qemu on port %i ...")) % self.port,
                    translate("QemuManager", "Abort"),
                    0,
                    count,
                    globals.GApp.mainWindow,
                )
                progress.setMinimum(1)
                progress.setWindowModality(QtCore.Qt.WindowModal)
                globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000)
            if nb > 2:
                progress.setValue(nb)
                globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000)
                if progress.wasCanceled():
                    progress.reset()
                    break
            try:
                s.connect(("localhost", self.port))
            except:
                s.close()
                time.sleep(1)
                continue
            connection_success = True
            break

        if connection_success:
            s.close()
            time.sleep(0.2)
        else:
            QtGui.QMessageBox.critical(
                globals.GApp.mainWindow,
                "Qemu Manager",
                unicode(translate("QemuManager", "Can't connect to Qemu on port %i")) % self.port,
            )
            self.stopQemu()
            return False
        if progress:
            progress.setValue(count)
            progress.deleteLater()
            progress = None
        return True
예제 #18
0
    def preloadDynamips(self):
        """ Preload Dynamips
        """

        proc = QtCore.QProcess(globals.GApp.mainWindow)
        port = globals.hypervisor_baseport

        if self.hypervisor_wd:
            # set the working directory
            proc.setWorkingDirectory(self.hypervisor_wd)
        try:
            # start dynamips in hypervisor mode (-H)
            # Dynamips version 0.2.8-RC3 and before cannot accept a specific port when binding on a chosen address with param -H <IP address:port> (bug is inside Dynamips).
            if self.dynamips.detected_version and StrictVersion(
                    self.dynamips.detected_version.replace("-RC", "b").split(
                        '-', 1)[0]
            ) > '0.2.8b3' and self.dynamips.HypervisorManager_binding != '0.0.0.0':
                proc.start(self.hypervisor_path, [
                    '-H',
                    self.dynamips.HypervisorManager_binding + ':' + str(port)
                ])
            else:
                proc.start(self.hypervisor_path, ['-H', str(port)])
        except:
            debug('Exception with StrictVersion')
            proc.start(self.hypervisor_path, ['-H', str(port)])

        if proc.waitForStarted() == False:
            return False

        if self.dynamips.HypervisorManager_binding != '0.0.0.0':
            binding = self.dynamips.HypervisorManager_binding
        else:
            binding = '127.0.0.1'

        # give 5 seconds to the hypervisor to accept connections
        count = 5
        connection_success = False
        timeout = 60.0
        for nb in range(count + 1):
            try:
                s = socket.create_connection((binding, port), timeout)
            except:
                time.sleep(1)
                continue
            connection_success = True
            break
        if connection_success:
            s.close()
            proc.close()
            return True
        if proc.state():
            proc.close()
        return False
예제 #19
0
    def unallocateHypervisor(self, node, host, port):
        """ Unallocate a hypervisor for a given node
        """

        for hypervisor in self.hypervisors:
            if hypervisor['host'] == host and hypervisor['port'] == int(port):
                debug("Hypervisor manager: unallocate hypervisor on %s port %i for node %s" % (host, port, node.hostname))
                hypervisor['load'] -= node.default_ram
                if hypervisor['load'] <= 0:
                    hypervisor['load'] = 0
                break
예제 #20
0
    def unallocateHypervisor(self, node, port):
        """ Unallocate a hypervisor for a given node
        """

        for hypervisor in self.hypervisors:
            if hypervisor['port'] == int(port):
                debug("Hypervisor manager: unallocate hypervisor (port: " + str(port) + ") for node " + node.hostname)
                hypervisor['load'] -= node.default_ram
                if hypervisor['load'] <= 0:
                    hypervisor['load'] = 0
                break
예제 #21
0
    def changeHypervisorLoad(self, node, port, old_default_ram):
        """ Change the hypervisor RAM load for a given node
        """

        for hypervisor in self.hypervisors:
            if hypervisor['port'] == int(port):
                debug("Hypervisor manager: change hypervisor load (port: " + str(port) + ") for node " + node.hostname)
                hypervisor['load'] -= old_default_ram
                if hypervisor['load'] <= 0:
                    hypervisor['load'] = 0
                hypervisor['load'] += node.default_ram
                break
예제 #22
0
파일: Hub.py 프로젝트: GNS3/gns3-legacy
    def mapping(self):
        """ Configure Ethernet port mapping
        """

        connected_interfaces = map(int, self.getConnectedInterfaceList())
        for port in self.config['ports']:
            if port in connected_interfaces:
                if not self.hub.nios.has_key(port):
                    (destnode, destinterface)= self.getConnectedNeighbor(str(port))
                    if destinterface.lower()[:3] == 'nio':
                        debug("hub_map: " + str(port) + ' to ' + destinterface)
                        self.dynagen.hub_to_nio(self.hub, port, destinterface)
예제 #23
0
    def clearClosedConsoles(self):
        """ Refresh the list of opened terminal programs.
        """

        updated_list = []
        for console in self.consoleProcesses:
            console.poll()
            if console.returncode == None:
                # the process hasn't returned yet (still active)
                updated_list.append(console)
        self.consoleProcesses = updated_list
        debug("%s has %i terminal program(s) connected to itself" % (self.hostname, len(self.consoleProcesses)))
예제 #24
0
파일: Hub.py 프로젝트: kabantsh/gns3-legacy
    def mapping(self):
        """ Configure Ethernet port mapping
        """

        connected_interfaces = map(int, self.getConnectedInterfaceList())
        for port in self.config['ports']:
            if port in connected_interfaces:
                if not self.hub.nios.has_key(port):
                    (destnode,
                     destinterface) = self.getConnectedNeighbor(str(port))
                    if destinterface.lower()[:3] == 'nio':
                        debug("hub_map: " + str(port) + ' to ' + destinterface)
                        self.dynagen.hub_to_nio(self.hub, port, destinterface)
예제 #25
0
    def unallocateHypervisor(self, node, host, port):
        """ Unallocate a hypervisor for a given node
        """

        for hypervisor in self.hypervisors:
            if hypervisor['host'] == host and hypervisor['port'] == int(port):
                debug(
                    "Hypervisor manager: unallocate hypervisor on %s port %i for node %s"
                    % (host, port, node.hostname))
                hypervisor['load'] -= node.default_ram
                if hypervisor['load'] <= 0:
                    hypervisor['load'] = 0
                break
예제 #26
0
    def mapping(self):
        """ Configure Frame-relay DLCI mapping
        """

        connected_interfaces = map(int, self.getConnectedInterfaceList())
        for (source,  destination) in self.config['mapping'].iteritems():
            (srcport, srcdlci) = source.split(':')
            (destport, destdlci) = destination.split(':')
            if int(srcport) in connected_interfaces and int(destport) in connected_interfaces:
                debug('FRSW ' + self.hostname + ' is mapping: ' + source + ' to ' + destination)
                if not self.frsw.pvcs.has_key((int(srcport), int(srcdlci))) and not self.frsw.pvcs.has_key((int(destport), int(destdlci))):
                    self.frsw.map(int(srcport), int(srcdlci), int(destport), int(destdlci))
                    self.frsw.map(int(destport), int(destdlci), int(srcport), int(srcdlci))
예제 #27
0
    def clearClosedConsoles(self):
        """ Refresh the list of opened terminal programs.
        """

        updated_list = []
        for console in self.consoleProcesses:
            console.poll()
            if console.returncode == None:
                # the process hasn't returned yet (still active)
                updated_list.append(console)
        self.consoleProcesses = updated_list
        debug("%s has %i terminal program(s) connected to itself" %
              (self.hostname, len(self.consoleProcesses)))
예제 #28
0
    def apply(self, message=False):
        """ Apply the IDLE PC to the router
        """

        try:
            selection = str(
                self.comboBox.currentText()).split(':')[0].strip('* ')
            index = int(selection)
            for node in globals.GApp.topology.nodes.values():
                if isinstance(
                        node,
                        IOSRouter) and node.hostname == self.router.hostname:
                    dyn_router = node.get_dynagen_device()
                    if globals.GApp.systconf[
                            'dynamips'].HypervisorManager_binding == '0.0.0.0':
                        host = '0.0.0.0'
                    else:
                        host = dyn_router.dynamips.host
                    if globals.GApp.iosimages.has_key(host + ':' +
                                                      dyn_router.image):
                        image = globals.GApp.iosimages[host + ':' +
                                                       dyn_router.image]
                        debug("Register IDLE PC " + self.idles[index] +
                              " for image " + image.filename)
                        image.idlepc = self.idles[index]
                        # Apply idle pc to devices with the same IOS image
                        for device in globals.GApp.topology.nodes.values():
                            if isinstance(
                                    device, IOSRouter
                            ) and device.config['image'] == image.filename:
                                debug("Apply IDLE PC " + self.idles[index] +
                                      " to " + device.hostname)
                                device.get_dynagen_device(
                                ).idlepc = self.idles[index]
                                config = device.get_config()
                                config['idlepc'] = self.idles[index]
                                device.set_config(config)
                                device.setCustomToolTip()
                        break

            if message:
                QtGui.QMessageBox.information(
                    self, translate("IDLEPCDialog", "IDLE PC"),
                    translate("IDLEPCDialog",
                              "IDLE PC value %s has been applied on %s") %
                    (self.idles[index], self.router.hostname))
        except lib.DynamipsError, msg:
            QtGui.QMessageBox.critical(
                self, translate("IDLEPCDialog", "Dynamips error"),
                unicode(msg))
            return
예제 #29
0
    def stopQemu(self):
        """ Stop Qemu
        """

        for hypervisor in globals.GApp.dynagen.dynamips.values():
            if isinstance(hypervisor, qlib.Qemu):
                try:
                    hypervisor.reset()
                    hypervisor.close()
                except:
                    continue
        if self.proc and self.proc.state():
            debug("QemuManager: stop Qemu with pid " + str(self.proc.pid()))
            self.proc.close()
        self.proc = None
예제 #30
0
    def preloadDynamips(self):
        """ Preload Dynamips
        """

        proc = QtCore.QProcess(globals.GApp.mainWindow)
        port = globals.hypervisor_baseport

        if self.hypervisor_wd:
            # set the working directory
            proc.setWorkingDirectory(self.hypervisor_wd)        
        try:
            # start dynamips in hypervisor mode (-H)
            # Dynamips version 0.2.8-RC3 and before cannot accept a specific port when binding on a chosen address with param -H <IP address:port> (bug is inside Dynamips).
            if self.dynamips.detected_version and StrictVersion(self.dynamips.detected_version.replace("-RC", "b").split('-', 1)[0]) > '0.2.8b3' and self.dynamips.HypervisorManager_binding != '0.0.0.0':
                proc.start(self.hypervisor_path,  ['-H', self.dynamips.HypervisorManager_binding + ':' + str(port)])
            else:
                proc.start(self.hypervisor_path,  ['-H', str(port)])
        except:
            debug('Exception with StrictVersion')
            proc.start(self.hypervisor_path,  ['-H', str(port)])

        if proc.waitForStarted() == False:
            return False
        
        if self.dynamips.HypervisorManager_binding != '0.0.0.0':
            binding = self.dynamips.HypervisorManager_binding
        else:
            binding = '127.0.0.1'

        # give 5 seconds to the hypervisor to accept connections
        count = 5
        connection_success = False
        timeout = 60.0
        for nb in range(count + 1):
            try:
                s = socket.create_connection((binding, port), timeout)
            except:
                time.sleep(1)
                continue
            connection_success = True
            break
        if connection_success:
            s.close()
            proc.close()
            return True
        if proc.state():
            proc.close()
        return False
예제 #31
0
    def startVBox(self, port, binding=None):
        """ Start VBox
        """

        if binding == None:
            binding = globals.GApp.systconf['vbox'].VBoxManager_binding
        self.port = port

        if self.proc and self.proc.state():
            debug('VBoxManager: VBox is already started with pid ' + str(self.proc.pid()))
            return True

        self.proc = QtCore.QProcess(globals.GApp.mainWindow)
        if globals.GApp.systconf['vbox'].vboxwrapper_workdir:
            if not os.access(globals.GApp.systconf['vbox'].vboxwrapper_workdir, os.F_OK | os.W_OK):
                QtGui.QMessageBox.warning(globals.GApp.mainWindow, 'VBox Manager',
                                          translate("VBoxManager", "Working directory %s seems to not exist or be writable, please check") % globals.GApp.systconf['vbox'].vboxwrapper_workdir)
            # set the working directory
            self.proc.setWorkingDirectory(globals.GApp.systconf['vbox'].vboxwrapper_workdir)

        # test if VBox is already running on this port
        timeout = 60.0
        try:
            s = socket.create_connection((binding, self.port), timeout)
            QtGui.QMessageBox.warning(globals.GApp.mainWindow, 'VBox Manager',
                                       translate("VBoxManager", "VBox is already running on %s port %i, it will not be shutdown after you quit GNS3") % (binding, self.port))
            s.close()
            return True
        except:
            pass

        # start VBoxwrapper, use python on all platform but Windows (in release mode)
        if sys.platform.startswith('win') and (globals.GApp.systconf['vbox'].vboxwrapper_path.split('.')[-1] == 'exe'):
            # On Windows hosts, we remove python dependency by pre-compiling VBoxwrapper. (release mode)
            self.proc.start('"' + globals.GApp.systconf['vbox'].vboxwrapper_path + '"', ['--listen', binding, '--port', str(self.port), '--no-vbox-checks'])
        elif hasattr(sys, "frozen"):
            self.proc.start(globals.GApp.systconf['vbox'].vboxwrapper_path, ['--listen', binding, '--port', str(self.port), '--no-vbox-checks'])
        else:
            self.proc.start(sys.executable, [globals.GApp.systconf['vbox'].vboxwrapper_path, '--listen', binding, '--port', str(self.port), '--no-vbox-checks'])

        if self.proc.waitForStarted() == False:
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, 'VBox Manager', translate("VBoxManager", "Can't start VBox on %s port %i") % (binding, self.port))
            return False

        self.waitVBox(binding)
        if self.proc and self.proc.state():
            debug('VBoxManager: VBox has been started with pid ' + str(self.proc.pid()))
        return True
예제 #32
0
    def closeAllConsoles(self):
        """ Close all opened terminal programs
        """

        # closing terminal programs
        for console in self.consoleProcesses:
            console.poll()
            if console.returncode == None:
                # the process hasn't returned yet (still active)
                debug("Sending terminate signal to terminal program (pid %i)" % console.pid)
                try:
                    console.terminate()
                except:
                    debug("Error while sending the signal to terminal program (pid %i)" % console.pid)
                    continue
        self.consoleProcesses = []
예제 #33
0
    def delete_router(self):
        """ Delete this router
        """

        if self.router:
            try:
                self.stopNode()
                # don't forget to delete this router in Dynamips
                self.router.delete()
                del self.dynagen.devices[self.hostname]
                if self.router in self.hypervisor.devices:
                    self.hypervisor.devices.remove(self.router)
                self.dynagen.update_running_config()
            except:
                pass
            debug('Router ' + self.hostname + ' deleted')
예제 #34
0
class PipeCapture(QtCore.QThread):
    def __init__(self, input_capture_file_path, capture_cmd, wireshark_pipe):
        self.input_capture_file_path = input_capture_file_path
        self.capture_cmd = capture_cmd
        self.wireshark_pipe = wireshark_pipe
        self.process = None
        self.pipe = None
        QtCore.QThread.__init__(self)

    def __del__(self):

        debug("Deleting pipe thread ...")
        if self.pipe:
            win32file.CloseHandle(self.pipe)

    def run(self):

        try:
            in_file = open(self.input_capture_file_path, 'rb')
        except IOError, e:
            debug("Cannot open capture file: %s") % unicode(e)
            self.exit()
            return
        try:
            self.process = subprocess.Popen(self.capture_cmd.strip())
        except (OSError, IOError), e:
            debug("Cannot start Wireshark: %s") % unicode(e)
            self.exit()
            return
예제 #35
0
 def stopQemu(self):
     """ Stop Qemu
     """
     for hypervisor in globals.GApp.dynagen.dynamips.values():
         if isinstance(hypervisor, qlib.Qemu):
             try:
                 hypervisor.reset()
                 hypervisor.close()
             except:
                 continue
     if self.proc and self.proc.state():
         debug('QemuManager: stop Qemu with pid ' + str(self.proc.pid()))
         self.proc.terminate()
         time.sleep(0.5)
         self.proc.close()
     self.proc = None
예제 #36
0
    def startQemu(self, port, binding=None):
        """ Start Qemu
        """
        self.port = port
        if binding == None:
            binding = globals.GApp.systconf['qemu'].QemuManager_binding
        
        if self.proc and self.proc.state():
            debug('QemuManager: Qemu is already started with pid ' + str(self.proc.pid()))
            return True

        self.proc = QtCore.QProcess(globals.GApp.mainWindow)
        if globals.GApp.systconf['qemu'].qemuwrapper_workdir:
            if not os.access(globals.GApp.systconf['qemu'].qemuwrapper_workdir, os.F_OK | os.W_OK):
                QtGui.QMessageBox.warning(globals.GApp.mainWindow, 'Qemu Manager',
                                          translate("QemuManager", "Working directory %s seems to not exist or be writable, please check") % globals.GApp.systconf['qemu'].qemuwrapper_workdir)

            self.proc.setWorkingDirectory(globals.GApp.systconf['qemu'].qemuwrapper_workdir)

        # test if Qemu is already running on this port
        timeout = 10
        try:
            s = socket.create_connection((binding, self.port), timeout)
            QtGui.QMessageBox.warning(globals.GApp.mainWindow, 'Qemu Manager',
                                      translate("QemuManager", "Qemu is already running on %s port %i, it will not be shutdown after you quit GNS3") % (binding, self.port))
            s.close()
            return True
        except:
            pass

        # start Qemuwrapper, use python on all platform but Windows (in release mode)
        #binding = globals.GApp.systconf['qemu'].QemuManager_binding
        if sys.platform.startswith('win') and (globals.GApp.systconf['qemu'].qemuwrapper_path.split('.')[-1] == 'exe'):
            self.proc.start('"' + globals.GApp.systconf['qemu'].qemuwrapper_path + '"', ['--listen', binding, '--port', str(self.port), '--no-path-check'])
        elif hasattr(sys, "frozen"):
            self.proc.start('python',  [globals.GApp.systconf['qemu'].qemuwrapper_path, '--listen', binding, '--port', str(self.port), '--no-path-check'])
        else:
            self.proc.start(sys.executable,  [globals.GApp.systconf['qemu'].qemuwrapper_path, '--listen', binding, '--port', str(self.port), '--no-path-check'])

        if self.proc.waitForStarted() == False:
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, 'Qemu Manager', translate("QemuManager", "Can't start Qemu on %s port %i") % (binding, self.port))
            return False

        self.waitQemu(binding)
        if self.proc and self.proc.state():
            debug('QemuManager: Qemu has been started with pid ' + str(self.proc.pid()))
        return True
예제 #37
0
    def create_emudev(self):

        model = self.model
        self.dynagen.update_running_config()
        devdefaults = self.get_devdefaults()
        if devdefaults == False:
            return False
        vbox_name = self.vbox.host + ':' + str(self.vbox.port)
        self.emu_vboxdev = self._make_devinstance(vbox_name)
        self.dynagen.setdefaults(self.emu_vboxdev, devdefaults[model])
        self.dynagen.devices[self.hostname] = self.emu_vboxdev
        debug('%s %s created' % (self.friendly_name, self.emu_vboxdev.name))

        self.dynagen.update_running_config()
        self.running_config = self.dynagen.running_config[self.d][self.f]
        self.defaults_config = self.dynagen.defaults_config[self.d][model]
        self.setCustomToolTip()
예제 #38
0
    def create_emudev(self):

        model = self.model
        self.dynagen.update_running_config()
        devdefaults = self.get_devdefaults()
        if devdefaults == False:
            return False
        qemu_name = self.qemu.host + ':' + str(self.qemu.port)
        self.emudev = self._make_devinstance(qemu_name)
        self.dynagen.setdefaults(self.emudev, devdefaults[model])
        self.dynagen.devices[self.hostname] = self.emudev
        debug('%s %s created' % (self.friendly_name, self.emudev.name))

        self.dynagen.update_running_config()
        self.running_config = self.dynagen.running_config[self.d][self.f]
        self.defaults_config = self.dynagen.defaults_config[self.d][model]
        self.setCustomToolTip()
예제 #39
0
    def delete_router(self):
        """ Delete this router
        """

        if self.router:
            try:
                self.stopNode()
                # don't forget to delete this router in Dynamips
                self.router.delete()
                if self.dynagen.devices.has_key(self.hostname):
                    del self.dynagen.devices[self.hostname]
                if self.router in self.hypervisor.devices:
                    self.hypervisor.devices.remove(self.router)
                self.dynagen.update_running_config()
            except:
                pass
            debug('Router ' + self.hostname + ' deleted')
예제 #40
0
    def waitQemu(self, binding):
        """ Wait Qemu until it accepts connections
        """

        # give 15 seconds to Qemu to accept connections
        count = 15
        progress = None
        connection_success = False
        timeout = 10
        s = None
        debug("Qemu manager: connecting to %s on port %i" % (binding, self.port))
        for nb in range(count + 1):
            if nb == 3:
                progress = QtGui.QProgressDialog(translate("QemuManager", "Connecting to Qemu on %s port %i ...") % (binding, self.port),
                                                 translate("QemuManager", "Abort"), 0, count, globals.GApp.mainWindow)
                progress.setMinimum(1)
                progress.setWindowModality(QtCore.Qt.WindowModal)
                globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000)
            if nb > 2:
                progress.setValue(nb)
                globals.GApp.processEvents(QtCore.QEventLoop.AllEvents | QtCore.QEventLoop.WaitForMoreEvents, 2000)
                if  progress.wasCanceled():
                    progress.reset()
                    break
            try:
                s = socket.create_connection((binding, self.port), timeout)
            except:
                time.sleep(1)
                continue
            connection_success = True
            break

        if connection_success and s:
            s.close()
            time.sleep(0.2)
        else:
            QtGui.QMessageBox.critical(globals.GApp.mainWindow, 'Qemu Manager',
                                       translate("QemuManager", "Can't connect to Qemu on %s port %i") % (binding, self.port))
            self.stopQemu()
            return False
        if progress:
            progress.setValue(count)
            progress.deleteLater()
            progress = None
        return True
예제 #41
0
    def reconfigNode(self, new_hostname):
        """ Used when changing the hostname
        """

        old_console = None
        if self.emudev:
            old_console = self.emudev.console
        links = self.getEdgeList()
        if len(links):
            QtGui.QMessageBox.critical(
                globals.GApp.mainWindow,
                translate("AnyEmuDevice", "New hostname"),
                translate("AnyEmuDevice",
                          "Cannot rename a connected emulated device"))
            return


#         if self.hostname != new_hostname:
#             self.emudev.rename(new_hostname)
#             self.set_hostname(new_hostname)

        self.delete_emudev()
        if self.hostname != new_hostname:
            try:
                qemu_name = self.qemu.host + ':' + str(self.qemu.port)
                shutil.move(
                    self.dynagen.dynamips[qemu_name].workingdir + os.sep +
                    self.hostname,
                    self.dynagen.dynamips[qemu_name].workingdir + os.sep +
                    new_hostname)
            except:
                debug("Cannot move emulator's working directory")
        self.set_hostname(new_hostname)
        try:
            self.create_emudev()
            if old_console:
                self.emudev.console = old_console
        except lib.DynamipsError, msg:
            QtGui.QMessageBox.critical(
                globals.GApp.mainWindow,
                translate("AnyEmuDevice", "Dynamips error"), unicode(msg))
            self.delete_emudev()
            globals.GApp.topology.deleteNode(self.id)
            return
예제 #42
0
    def mapping(self):
        """ Configure Ethernet port mapping
        """

        connected_interfaces = map(int, self.getConnectedInterfaceList())
        for (vlan, portlist) in self.config['vlans'].iteritems():
            for port in portlist:
                if port in connected_interfaces:
                    if not self.ethsw.mapping.has_key(port):
                        (destnode,
                         destinterface) = self.getConnectedNeighbor(str(port))
                        porttype = self.config['ports'][port]
                        if self.ethsw.dynamips.intversion < 208.3 and porttype == 'qinq':
                            QtGui.QMessageBox.critical(
                                globals.GApp.mainWindow,
                                translate("ETHSW", "Port type"),
                                translate(
                                    "ETHSW",
                                    "QinQ is only supported with Dynamips > 0.2.8 RC2"
                                ))
                            return

                        if destinterface.lower()[:3] == 'nio':
                            debug("ethsw_map: " + str(port) + ' to ' +
                                  porttype + ' ' + str(vlan) + ' ' +
                                  destinterface)
                            self.dynagen.ethsw_map(
                                self.ethsw, port, porttype + ' ' + str(vlan) +
                                ' ' + destinterface)
                        else:
                            debug("ethsw_map: " + str(port) + ' to ' +
                                  porttype + ' ' + str(vlan))
                            self.dynagen.ethsw_map(self.ethsw, port,
                                                   porttype + ' ' + str(vlan))
                    elif self.ethsw.mapping.has_key(port):
                        porttype = self.config['ports'][port]
                        # check if the vlan or port type has changed
                        # WARNING: see unset_port()
                        if (vlan != self.ethsw.mapping[port][1]) or (
                                porttype != self.ethsw.mapping[port][0]):
                            self.ethsw.unset_port(port)
                            self.dynagen.ethsw_map(self.ethsw, port,
                                                   porttype + ' ' + str(vlan))
예제 #43
0
    def closeAllConsoles(self):
        """ Close all opened terminal programs
        """

        # closing terminal programs
        for console in self.consoleProcesses:
            console.poll()
            if console.returncode == None:
                # the process hasn't returned yet (still active)
                debug("Sending terminate signal to terminal program (pid %i)" %
                      console.pid)
                try:
                    console.terminate()
                except:
                    debug(
                        "Error while sending the signal to terminal program (pid %i)"
                        % console.pid)
                    continue
        self.consoleProcesses = []
예제 #44
0
    def listSnaphosts(self):

        self.SnapshotList.clear()
        if not globals.GApp.workspace.projectFile:
            return
        snapregexp = re.compile(r"""^(.*)_(.*)_snapshot_([0-9]+)_([0-9]+)""")
        projectDir = os.path.dirname(globals.GApp.workspace.projectFile)
        snapshotDir = os.path.join(os.path.dirname(globals.GApp.workspace.projectFile), 'snapshots')
        snapshots = glob.glob(os.path.normpath(projectDir) + os.sep + "*_snapshot_*")

        # Backward compatibility: move snapshots to the snapshot directory (new location in GNS3 0.8.5)
        try:
            if snapshots and not os.path.exists(snapshotDir):
                os.mkdir(snapshotDir)
            for entry in snapshots:
                shutil.move(entry, snapshotDir)
                debug("Moving %s to the snapshot directory" % entry)
        except (OSError, IOError), e:
            debug("Cound't move snapshots to the snapshot directory")
예제 #45
0
    def stopVBox(self):
        """ Stop VBox
        """
        #print "Entered VBoxManager::stopVBox()"

        try:
            for hypervisor in globals.GApp.dynagen.dynamips.values():
                if isinstance(hypervisor, vboxlib.VBox):
                    try:
                        hypervisor.reset()
                        hypervisor.close()
                    except:
                        continue
        except:
            pass
        if self.proc and self.proc.state():
            debug('VBoxManager: stop VBox with pid ' + str(self.proc.pid()))
            self.proc.terminate()
            time.sleep(0.5)
            self.proc.close()
        self.proc = None
예제 #46
0
    def __captureQemuDevice(self, device, interface):
        """ Capture for Qemu based devices
        """

        host = globals.GApp.dynagen.devices[device].dynamips.host
        match_obj = dynagen_namespace. qemu_int_re.search(interface)
        if not match_obj:
            debug("Cannot parse interface " + interface)
            return
        port = match_obj.group(2)
        
        capture_conf = globals.GApp.systconf['capture']
        if capture_conf.workdir and (host == globals.GApp.systconf['qemu'].QemuManager_binding or host == 'localhost'):
            workdir = capture_conf.workdir
        else:
            workdir = globals.GApp.dynagen.devices[device].dynamips.workingdir
        if '/' in workdir:
            sep = '/'
        else:
            sep = '\\'
        self.capfile = unicode(workdir + sep + self.source.hostname + '_to_' + self.dest.hostname + '.cap')
        debug("Start capture to " + self.capfile)
        
        globals.GApp.dynagen.devices[device].capture(int(port), self.capfile)
        self.captureInfo = (device, port)
        self.capturing = True
        debug("Capturing to " + self.capfile)
예제 #47
0
    def reconfigNode(self, new_hostname):
        """ Used when changing the hostname
        """

        old_hostname = self.hostname
        old_console = None
        old_aux = None
        if self.router:
            old_console = self.router.console
            old_aux = self.router.aux
        links = self.getEdgeList().copy()
        for link in links:
            globals.GApp.topology.deleteLink(link)
        self.delete_router()
        dynamips_files = glob.glob(os.path.normpath(self.hypervisor.workingdir) + os.sep + self.get_platform() + '?' + self.hostname + '*')
        for file in dynamips_files:
            try:
                new_file_name = os.path.basename(file).replace(self.hostname, new_hostname)
                shutil.move(file, os.path.dirname(file) + os.sep + new_file_name)
            except (OSError, IOError), e:
                debug("Warning: cannot move " + file + " to " + os.path.dirname(file) + os.sep + new_file_name)
                continue
예제 #48
0
    def create_router(self):

        model = self.model
        #first let's gather all defaults/setting for each model from running config
        self.dynagen.update_running_config()
        devdefaults = self.get_devdefaults()
        if devdefaults == False:
            return False

        #now we have everything ready to create routers
        router = self.routerInstanceMap[model](self.hypervisor,
                                               chassis=model,
                                               name=self.hostname)
        self.dynagen.setdefaults(router, devdefaults[model])

        #implement IOS ghosting when creating the router from configConsole
        #use devdefaults to find out whether we have ghostios = True, and simply set the ghostios
        if devdefaults[model].has_key('ghostios'):
            if devdefaults[model]['ghostios']:
                ghost_file = router.formatted_ghost_file()
                router.ghost_status = 2
                router.ghost_file = '"' + ghost_file + '"'

        #add router to frontend
        self.dynagen.devices[self.hostname] = router
        self.router = router
        debug('Router ' + router.name + ' created')

        #implement JIT blocks sharing
        if devdefaults[model].has_key('jitsharing'):
            if devdefaults[model]['jitsharing']:
                if self.dynagen.jitshareddevices.has_key(self.hostname):
                    globals.GApp.dynagen.jitsharing()

        self.dynagen.update_running_config()
        self.running_config = self.dynagen.running_config[self.d][self.r]
        self.defaults_config = self.dynagen.defaults_config[self.d][
            self.router.model_string]
        self.setCustomToolTip()
예제 #49
0
    def __captureDynamipsDevice(self, device, interface, encapsulation):
        """ Capture for Dynamips based devices
        """
        
        host = globals.GApp.dynagen.devices[device].dynamips.host

        match_obj = dynagen_namespace.interface_re.search(interface)
        if match_obj:
            (inttype, slot, port) = match_obj.group(1, 2, 3)
            slot = int(slot)
            port = int(port)
        else:
            # Try checking for WIC interface specification (e.g. S1)
            match_obj = dynagen_namespace.interface_noport_re.search(interface)
            (inttype, port) = match_obj.group(1, 2)
            slot = 0

        try:
            encapsulation = encapsulation[1:-1].split(':')[1]
            encapsulation = self.encapsulationTransform[encapsulation]
            capture_conf = globals.GApp.systconf['capture']

            if capture_conf.workdir and (host == globals.GApp.systconf['dynamips'].HypervisorManager_binding or host == 'localhost'):
                workdir = capture_conf.workdir
            else:
                workdir = globals.GApp.dynagen.devices[device].dynamips.workingdir
            if '/' in workdir:
                sep = '/'
            else:
                sep = '\\'
            self.capfile = unicode(workdir + sep + self.source.hostname + '_to_' + self.dest.hostname + '.cap')
            debug("Start capture to " + self.capfile)
            globals.GApp.dynagen.devices[device].slot[slot].filter(inttype, port,'capture','both', encapsulation + " " + '"' + self.capfile + '"')
            self.captureInfo = (device, slot, inttype, port)
            self.capturing = True
            debug("Capturing to " + self.capfile)
        except lib.DynamipsError, msg:
            QtGui.QMessageBox.critical(self, translate("AbstractEdge", "Dynamips error"),  unicode(msg))
            return
예제 #50
0
    def stopProcHypervisors(self):
        """ Shutdown all started hypervisors
        """

        if globals.GApp != None and globals.GApp.systconf['dynamips']:
            self.setDefaults()
        hypervisors = globals.GApp.dynagen.dynamips.copy()
        for hypervisor in hypervisors.values():
            if isinstance(hypervisor, lib.Dynamips):
                try:
                    if globals.GApp.dynagen.dynamips.has_key(hypervisor.host + ':' + hypervisor.port):
                        debug("Hypervisor manager: reset and close hypervisor on port " + str(hypervisor['port']))
                        hypervisor.reset()
                        hypervisor.close()
                        del globals.GApp.dynagen.dynamips[hypervisor.host + ':' + hypervisor.port]
                except:
                    continue
        for hypervisor in self.hypervisors:
            debug("Hypervisor manager: close hypervisor on port " + str(hypervisor['port']))
            hypervisor['proc_instance'].close()
            hypervisor['proc_instance'] = None
        self.hypervisors = []
예제 #51
0
    def waitHypervisor(self, hypervisor, binding=None):
        """ Wait the hypervisor until it accepts connections
        """

        if binding == None:
            if self.dynamips.HypervisorManager_binding and self.dynamips.HypervisorManager_binding != '0.0.0.0':
                binding = self.dynamips.HypervisorManager_binding
            else:
                debug(
                    "Hypervisor manager: warning: no default binding, defaulting to 127.0.0.1"
                )
                binding = '127.0.0.1'

        last_exception = None
        # give 15 seconds to the hypervisor to accept connections
        count = 15
        progress = None
        timeout = 60.0
        connection_success = False
        debug("Hypervisor manager: connecting on %s:%i" %
              (binding, hypervisor['port']))
        for nb in range(count + 1):
            if nb == 3:
                progress = QtGui.QProgressDialog(
                    translate("HypervisorManager",
                              "Connecting to an hypervisor on %s port %i ...")
                    % (binding, hypervisor['port']),
                    translate("HypervisorManager",
                              "Abort"), 0, count, globals.GApp.mainWindow)
                progress.setMinimum(1)
                progress.setWindowModality(QtCore.Qt.WindowModal)
                globals.GApp.processEvents(
                    QtCore.QEventLoop.AllEvents
                    | QtCore.QEventLoop.WaitForMoreEvents, 2000)
            if nb > 2:
                progress.setValue(nb)
                globals.GApp.processEvents(
                    QtCore.QEventLoop.AllEvents
                    | QtCore.QEventLoop.WaitForMoreEvents, 2000)
                if progress.wasCanceled():
                    progress.reset()
                    break
            try:
                s = socket.create_connection((binding, hypervisor['port']),
                                             timeout)
            except Exception, ex:
                time.sleep(1)
                last_exception = ex
                continue
            debug("Hypervisor manager: connected to hypervisor on %s port %i" %
                  (binding, hypervisor['port']))
            connection_success = True
            break
예제 #52
0
def connect(host, port, name):
    """ Start a telnet console and connect to it
    """

    try:
        console = globals.GApp.systconf['general'].term_cmd.strip()
        if console:
            #            if globals.GApp.systconf['general'].bring_console_to_front:
            #                if bringConsoleToFront(console, host, port, name):
            #                    # On successful attempt, we skip further processing
            #                    return (True)
            console = console.replace('%h', host)
            console = console.replace('%p', str(port))
            console = console.replace('%d', name)
            debug('Start console program %s' % console)
            if globals.GApp.systconf['general'].use_shell:
                proc = sub.Popen(console, shell=True)
            else:
                proc = sub.Popen(console)

            if globals.GApp.systconf['general'].bring_console_to_front:
                if bringConsoleToFront(console, name):
                    debug("Successful bringConsoleToFront() for %s" % name)
                else:
                    debug("Unsuccessful bringConsoleToFront() for %s" % name)
        else:
            if sys.platform.startswith('darwin'):
                proc = sub.Popen(
                    "/usr/bin/osascript -e 'tell application \"Terminal\" to do script with command \"telnet "
                    + host + " " + str(port) + "; exit\"'",
                    shell=True)
            elif sys.platform.startswith('win'):
                proc = sub.Popen("putty.exe -telnet %s %i -wt %s -gns3 5" %
                                 (host, port, name))
            else:
                proc = sub.Popen("xterm -T " + name + " -e 'telnet " + host +
                                 " " + str(port) + "' > /dev/null 2>&1 &",
                                 shell=True)
    except (OSError, IOError), e:
        QtGui.QMessageBox.critical(
            globals.GApp.mainWindow, translate("Console", "Console"),
            translate("Console", "Cannot start %s: %s") %
            (console, e.strerror))

        return None
예제 #53
0
    def open_config(self, FILENAME):
        """ Open the config file
        """
        debugmsg(2, "DynagenSub::open_config(%s)" % unicode(FILENAME))

        if sys.platform.startswith('win'):
            self.check_replace_GUID_NIO(FILENAME)
        config = Dynagen.open_config(self, FILENAME)
        debugmsg(2, ("DynagenSub::open_config(): config = ", config))
        self.filename = FILENAME
        self.gns3_data = None
        if 'GNS3-DATA' in config.sections:
            debugmsg(
                3, "DynagenSub::open_config(), entered into: if 'GNS3-DATA'")
            self.gns3_data = config['GNS3-DATA'].copy()
            if self.gns3_data.has_key('configs'):
                if os.path.exists(self.gns3_data['configs']):
                    projectConfigsDir = self.gns3_data['configs']
                else:
                    projectConfigsDir = os.path.join(
                        os.path.dirname(FILENAME),
                        unicode(self.gns3_data['configs']))
                globals.GApp.workspace.projectConfigs = os.path.abspath(
                    projectConfigsDir)
            if self.gns3_data.has_key('workdir'):
                if os.path.exists(self.gns3_data['workdir']):
                    projectWorkdir = self.gns3_data['workdir']
                else:
                    projectWorkdir = os.path.join(
                        os.path.dirname(FILENAME),
                        unicode(self.gns3_data['workdir']))
                globals.GApp.workspace.projectWorkdir = os.path.abspath(
                    projectWorkdir)
            config.sections.remove('GNS3-DATA')

        count = len(config.sections)
        progress = QtGui.QProgressDialog(
            translate("DynagenSub", "Starting hypervisors ..."),
            translate("DynagenSub", "Abort"), 0, count,
            globals.GApp.mainWindow)
        progress.setMinimum(1)
        progress.setWindowModality(QtCore.Qt.WindowModal)
        globals.GApp.processEvents(QtCore.QEventLoop.AllEvents)
        current = 0
        debugmsg(
            3,
            ("DynagenSub::open_config(), config.sections = ", config.sections))
        for section in config.sections:
            progress.setValue(current)
            globals.GApp.processEvents(
                QtCore.QEventLoop.AllEvents
                | QtCore.QEventLoop.WaitForMoreEvents, 1000)
            if progress.wasCanceled():
                progress.reset()
                break

            server = config[section]
            #debugmsg(3, ("DynagenSub::open_config(), server = ", server))  # Returns long config of hypervisor
            if ' ' in server.name:
                (emulator, host) = server.name.split(' ')
                debugmsg(
                    2, "DynagenSub::open_config(), emulator = %s, host = %s" %
                    (unicode(emulator), unicode(host)))
                if ':' in host:
                    # unpack the server and port
                    # controlPort is ignored
                    controlPort = host.split(':')[-1]
                    host = self.getHost(host)
                if emulator == 'qemu' and globals.GApp.systconf[
                        'qemu'].enable_QemuManager and globals.GApp.systconf[
                            'qemu'].import_use_QemuManager and host in self.local_addresses:
                    globals.GApp.QemuManager.startQemu(int(controlPort), host)
                    debugmsg(2,
                             "DynagenSub::open_config(), entered QemuManager")

                    # Override qemu & qemu-img paths
                    server['qemupath'] = globals.GApp.systconf[
                        'qemu'].qemu_path
                    server['qemuimgpath'] = globals.GApp.systconf[
                        'qemu'].qemu_img_path

                    # Check if this is a relative working directory path and convert to an absolute path if necessary
                    if server['workingdir']:
                        abspath = os.path.join(os.path.dirname(FILENAME),
                                               unicode(server['workingdir']))
                        if os.path.exists(abspath):
                            server['workingdir'] = abspath
                            debug(
                                unicode(
                                    "Converting relative working directory path to absolute path: %s"
                                ) % server['workingdir'])

                    if server['workingdir'] == '.':
                        server['workingdir'] = os.path.dirname(FILENAME)

                    # check if the working directory is accessible, if not find an alternative working directory
                    if not server.has_key('workingdir') or not server[
                            'workingdir'] or not os.access(
                                server['workingdir'], os.F_OK):
                        if globals.GApp.workspace.projectWorkdir and os.access(
                                globals.GApp.workspace.projectWorkdir,
                                os.F_OK):
                            workdir = globals.GApp.workspace.projectWorkdir
                        else:
                            workdir = globals.GApp.systconf[
                                'qemu'].qemuwrapper_workdir
                        debug(translate("DynagenSub", "Local working directory %s cannot be found for hypervisor %s:%s, use working directory %s instead") \
                        % (server['workingdir'], host, controlPort, workdir))
                        server['workingdir'] = workdir

                    for subsection in server.sections:
                        device = server[subsection]
                        # ASA has no image
                        if device.name == '5520' and device[
                                'initrd'] and device['kernel']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, ASA 5520"
                            )
                            if not os.access(device['initrd'], os.F_OK):

                                if len(globals.GApp.asaimages.keys()):
                                    initrd_name = globals.GApp.asaimages.values(
                                    )[0].initrd
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "ASA initrd",
                                            "ASA initrd %s cannot be found and cannot find an alternative initrd"
                                        ) % device['initrd'])
                                    continue
                                print translate("DynagenSub", "Local ASA initrd %s cannot be found, use initrd %s instead") \
                                                % (unicode(device['initrd']), initrd_name)
                                device['initrd'] = initrd_name

                            if not os.access(device['kernel'], os.F_OK):
                                if len(globals.GApp.asaimages.keys()):
                                    kernel_name = globals.GApp.asaimages.values(
                                    )[0].kernel
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "ASA kernel",
                                            "ASA kernel %s cannot be found and cannot find an alternative kernel"
                                        ) % device['kernel'])
                                    continue
                                print translate("DynagenSub", "Local ASA kernel %s cannot be found, use kernel %s instead") \
                                                % (unicode(device['kernel']), kernel_name)
                                device['kernel'] = kernel_name
                            continue

                        # AWP has no default image
                        if device.name == 'Soft32' and device[
                                'initrd'] and device['kernel']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, AWP Soft32"
                            )
                            if not os.access(device['initrd'], os.F_OK):

                                if len(globals.GApp.awprouterimages.keys()):
                                    initrd_name = globals.GApp.awprouterimages.values(
                                    )[0].initrd
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "AWP initrd",
                                            "AWP initrd %s cannot be found and cannot find an alternative initrd"
                                        ) % device['initrd'])
                                    continue
                                print translate("DynagenSub", "Local AWP initrd %s cannot be found, use initrd %s instead") \
                                                % (unicode(device['initrd']), initrd_name)
                                device['initrd'] = initrd_name

                            if not os.access(device['kernel'], os.F_OK):
                                if len(globals.GApp.awprouterimages.keys()):
                                    kernel_name = globals.GApp.awprouterimages.values(
                                    )[0].kernel
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "AWP kernel",
                                            "AWP kernel %s cannot be found and cannot find an alternative kernel"
                                        ) % device['kernel'])
                                    continue
                                print translate("DynagenSub", "Local AWP kernel %s cannot be found, use kernel %s instead") \
                                                % (unicode(device['kernel']), kernel_name)
                                device['kernel'] = kernel_name
                            continue

                        # IDS has no default image
                        if device.name == 'IDS-4215' and device[
                                'image1'] and device['image2']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, IDS"
                            )
                            if not os.access(device['image1'], os.F_OK):

                                if len(globals.GApp.idsimages.keys()):
                                    image1_name = globals.GApp.idsimages.values(
                                    )[0].image1
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "IDS image (hda)",
                                            "IDS image %s cannot be found and cannot find an alternative image"
                                        ) % device['image1'])
                                    continue
                                print translate("DynagenSub", "Local IDS image %s cannot be found, use image %s instead") \
                                % (unicode(device['image1']), image1_name)
                                device['image1'] = image1_name

                            if not os.access(device['image2'], os.F_OK):
                                if len(globals.GApp.idsimages.keys()):
                                    image2_name = globals.GApp.idsimages.values(
                                    )[0].image2
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "IDS image (hdb)",
                                            "IDS image %s cannot be found and cannot find an alternative image"
                                        ) % device['image2'])
                                    continue
                                print translate("DynagenSub", "Local IDS image %s cannot be found, use image %s instead") \
                                % (unicode(device['image2']), image2_name)
                                device['image2'] = image2_name

                            continue

                        if device.name not in ('525', 'O-series',
                                               'QemuDevice'):
                            continue
                        # Check if the image path is a relative path
                        if os.path.exists(device['image']) == False:
                            abspath = os.path.join(os.path.dirname(FILENAME),
                                                   unicode(device['image']))
                            if os.path.exists(abspath):
                                device['image'] = abspath

                        if device.name == 'O-series' and device['image']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, JunOS"
                            )
                            if not os.access(device['image'], os.F_OK):
                                if len(globals.GApp.junosimages.keys()):
                                    image_name = globals.GApp.junosimages.values(
                                    )[0].filename
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "JunOS image",
                                            "JunOS image %s cannot be found and cannot find an alternative image"
                                        ) % device['image'])
                                    continue
                                print translate("DynagenSub", "Local JunOS image %s cannot be found, use image %s instead") \
                                                % (unicode(device['image']), image_name)
                                device['image'] = image_name

                        if device.name == 'QemuDevice' and device['image']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, QemuDevice"
                            )
                            if not os.access(device['image'], os.F_OK):
                                if len(globals.GApp.qemuimages.keys()):
                                    image_name = globals.GApp.qemuimages.values(
                                    )[0].filename
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "Qemu image",
                                            "Qemu guest image %s cannot be found and cannot find an alternative image"
                                        ) % device['image'])
                                    continue
                                print translate("DynagenSub", "Local Qemu guest image %s cannot be found, use image %s instead") \
                                % (unicode(device['image']), image_name)
                                device['image'] = image_name
                        elif device['image']:
                            debugmsg(
                                2,
                                "DynagenSub::open_config(), entered QemuManager, elif device, possibly PIX"
                            )
                            # must be a PIX device
                            # check if the PIX image is accessible, if not find an alternative image
                            if not os.access(device['image'], os.F_OK):
                                if len(globals.GApp.piximages.keys()):
                                    image_name = globals.GApp.piximages.values(
                                    )[0].filename
                                else:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow, 'DynagenSub',
                                        translate(
                                            "PIX image",
                                            "PIX image %s cannot be found and cannot find an alternative image"
                                        ) % device['image'])
                                    continue
                                print translate("DynagenSub", "Local PIX image %s cannot be found, use image %s instead") \
                                % (unicode(device['image']), image_name)
                                device['image'] = image_name
                elif emulator == 'vbox' and globals.GApp.systconf[
                        'vbox'].enable_VBoxManager and globals.GApp.systconf[
                            'vbox'].import_use_VBoxManager and host in self.local_addresses:
                    debugmsg(2,
                             "DynagenSub::open_config(), entered VBoxManager")
                    globals.GApp.VBoxManager.startVBox(int(controlPort), host)

                    # Check if this is a relative working directory path and convert to an absolute path if necessary
                    if server['workingdir']:
                        abspath = os.path.join(os.path.dirname(FILENAME),
                                               unicode(server['workingdir']))
                        debugmsg(
                            3,
                            "DynagenSub::open_config(), 'vbox', abspath = %s" %
                            unicode(abspath))
                        if os.path.exists(abspath):
                            server['workingdir'] = abspath
                            debug(
                                unicode(
                                    "Converting relative working directory path to absolute path: %s"
                                ) % server['workingdir'])

                    debugmsg(
                        3,
                        "DynagenSub::open_config(), 'vbox', os.path.dirname(FILENAME) = %s"
                        % unicode(os.path.dirname(FILENAME)))
                    if server['workingdir'] == '.':
                        server['workingdir'] = os.path.dirname(FILENAME)

                    # check if the working directory is accessible, if not find an alternative working directory
                    if not server.has_key('workingdir') or not server[
                            'workingdir'] or not os.access(
                                server['workingdir'], os.F_OK):
                        if globals.GApp.workspace.projectWorkdir and os.access(
                                globals.GApp.workspace.projectWorkdir,
                                os.F_OK):
                            workdir = globals.GApp.workspace.projectWorkdir
                        else:
                            workdir = globals.GApp.systconf[
                                'vbox'].vboxwrapper_workdir
                        debug(translate("DynagenSub", "Local working directory %s cannot be found for hypervisor %s:%s, use working directory %s instead") \
                        % (server['workingdir'], host, controlPort, workdir))
                        server['workingdir'] = workdir

                    for subsection in server.sections:
                        device = server[subsection]
                        debugmsg(
                            3, "DynagenSub::open_config(), 'vbox', device...")
            else:
                server.host = server.name
                debugmsg(
                    3,
                    "DynagenSub::open_config(), server.host = %s, server.name = %s"
                    % (unicode(server.host), unicode(server.name)))
                controlPort = None
                if ':' in server.host:
                    #(server.host, controlPort) = server.host.split(':')
                    controlPort = server.host.split(':')[-1]
                    server.host = self.getHost(server.host)
                if server['port'] != None:
                    controlPort = server['port']
                if controlPort == None:
                    controlPort = '7200'

                # need to start local hypervisors

                if globals.GApp.HypervisorManager and globals.GApp.systconf[
                        'dynamips'].import_use_HypervisorManager and server.host in self.local_addresses:
                    debugmsg(
                        2,
                        "DynagenSub::open_config(), entered Dynamips HypervisorManager"
                    )

                    # update server.host and server.name to match with Hypervisor Manager Binding configuration,
                    # having hypervisors using 127.0.0.1 mixed with others using localhost will bring issues ...
                    if (server.host == 'localhost'
                            and server.host != globals.GApp.
                            systconf['dynamips'].HypervisorManager_binding):
                        print "Warning: using localhost in your topology file is not recommended"
#                        server.host = globals.GApp.systconf['dynamips'].HypervisorManager_binding
#                        server.name = server.host + ':' + controlPort

                    debug("Start hypervisor on port: " + str(controlPort))

                    try:
                        s = socket.create_connection(
                            (server.host, int(controlPort)), 60.0)
                        s.close()
                        print "Warning: a process is already running on port %i, please consider closing it or killing it as this may negatively impact your topology" % int(
                            controlPort)
                    except:
                        pass

                    hypervisor = globals.GApp.HypervisorManager.startNewHypervisor(
                        int(controlPort),
                        binding=server.host,
                        processcheck=False)
                    globals.GApp.HypervisorManager.waitHypervisor(
                        hypervisor, binding=server.host)

                    # Check if this is a relative working directory path and convert to an absolute path if necessary
                    if server['workingdir']:
                        abspath = os.path.join(os.path.dirname(FILENAME),
                                               unicode(server['workingdir']))
                        if os.path.exists(abspath):
                            server['workingdir'] = abspath
                            debug(
                                unicode(
                                    "Converting relative working directory path to absolute path: %s"
                                ) % server['workingdir'])

                    if server['workingdir'] == '.':
                        server['workingdir'] = os.path.dirname(FILENAME)

                    # check if the working directory is accessible, if not find an alternative working directory
                    if not server.has_key('workingdir') or not server[
                            'workingdir'] or not os.access(
                                server['workingdir'], os.F_OK):
                        if globals.GApp.workspace.projectWorkdir and os.access(
                                globals.GApp.workspace.projectWorkdir,
                                os.F_OK):
                            workdir = globals.GApp.workspace.projectWorkdir
                        else:
                            workdir = globals.GApp.systconf['dynamips'].workdir
                        debug(translate("DynagenSub", "Local working directory %s cannot be found for hypervisor %s:%s, use working directory %s instead") \
                        % (server['workingdir'], server.host, controlPort, workdir))
                        server['workingdir'] = workdir

                    debugmsg(3,
                             ("DynagenSub::open_config(), server.sections = ",
                              server.sections))
                    for subsection in server.sections:
                        device = server[subsection]

                        # check if the IOS image is accessible, if not find an alternative image
                        if device.name in DEVICETUPLE:
                            # Check if this is a relative image path and convert to an absolute path if necessary
                            abspath = os.path.join(os.path.dirname(FILENAME),
                                                   unicode(device['image']))
                            if os.path.exists(abspath):
                                device['image'] = abspath
                                debug(
                                    unicode(
                                        "Converting relative image path to absolute path: %s"
                                    ) % device['image'])

                            if not os.access(device['image'], os.F_OK):

                                selected_images = []
                                image_to_use = None
                                for (image, conf
                                     ) in globals.GApp.iosimages.iteritems():
                                    if conf.chassis == device.name:
                                        selected_images.append(image)

                                if len(selected_images):
                                    message = unicode(
                                        "Local IOS image %s\ncannot be found for hypervisor %s:%s\n\nPlease choose an alternative image:"
                                    ) % (device['image'], server.host,
                                         controlPort)
                                    selected_images.sort()
                                    (selection,
                                     ok) = QtGui.QInputDialog.getItem(
                                         globals.GApp.mainWindow,
                                         translate("DynagenSub", "IOS image"),
                                         translate("DynagenSub", message),
                                         selected_images, 0, False)
                                    if ok:
                                        image_to_use = unicode(selection)

                                if image_to_use == None and len(
                                        selected_images) == 0:
                                    QtGui.QMessageBox.critical(
                                        globals.GApp.mainWindow,
                                        translate("DynagenSub", "IOS image"),
                                        translate(
                                            "DynagenSub",
                                            "IOS image %s cannot be found and cannot find an alternative %s image"
                                        ) % (device['image'], device.name))
                                    continue
                                if image_to_use == None and len(
                                        selected_images) > 1:
                                    for image in selected_images:
                                        conf = globals.GApp.iosimages[image]
                                        if conf.default:
                                            image_to_use = image
                                            break
                                if not image_to_use:
                                    image_to_use = selected_images[0]
                                image_name = globals.GApp.iosimages[
                                    image_to_use].filename
                                ram = globals.GApp.iosimages[
                                    image_to_use].default_ram
                                idlepc = globals.GApp.iosimages[
                                    image_to_use].idlepc
                                print translate(
                                    "DynagenSub",
                                    "Local IOS image %s cannot be found, use image %s instead"
                                ) % (device['image'], image_name)
                                device['image'] = image_name
                                device['ram'] = ram
                                if idlepc:
                                    device['idlepc'] = idlepc
                                else:
                                    print translate(
                                        "DynagenSub",
                                        "WARNING: no IDLE PC value found for %s, please apply one before using this topology!"
                                    ) % device['image']

                        # check if the config file is accessible, if not find an alternative config
                        elif device.has_key('cnfg') and device['cnfg']:

                            # Check if this is a relative config path and convert to an absolute path if necessary
                            debugmsg(
                                3,
                                "DynagenSub::open_config(), device.has_key('cnfg') and device['cnfg']"
                            )
                            abspath = os.path.join(os.path.dirname(FILENAME),
                                                   unicode(device['cnfg']))
                            if os.path.exists(abspath):
                                device['cnfg'] = abspath
                                debug(
                                    unicode(
                                        "Converting relative config path to absolute path: %s"
                                    ) % device['cnfg'])

                            if not os.access(device['cnfg'], os.F_OK):
                                if globals.GApp.workspace.projectConfigs:

                                    basename = os.path.basename(device['cnfg'])
                                    if sys.platform.startswith(
                                            'win'
                                    ) and basename == device['cnfg']:
                                        # basename is the same as the original path, maybe it's an unix/posix path
                                        import posixpath
                                        basename = posixpath.basename(
                                            device['cnfg'])
                                    elif basename == device['cnfg']:
                                        # basename is the same as the original path, maybe it's a Windows path
                                        import ntpath
                                        basename = ntpath.basename(
                                            device['cnfg'])

                                    new_config_path = globals.GApp.workspace.projectConfigs + os.sep + basename
                                    if not os.path.exists(new_config_path):
                                        # this case is handled in NETFile
                                        print translate("DynagenSub", "Local configuration %s cannot be found for router %s, use default base configuration instead") \
                                        % (device['cnfg'], device.name)
                                    else:
                                        print translate("DynagenSub", "Local configuration %s cannot be found for router %s, use configuration %s instead") \
                                        % (device['cnfg'], device.name, new_config_path)
                                    device['cnfg'] = new_config_path
                current += 1

        progress.setValue(count)
        progress.deleteLater()
        progress = None
        debugmsg(2, "DynagenSub::open_config(), returning config")
        #debugmsg(3, ("config = ", config))
        return config
예제 #54
0
            self.exit()
            return
        try:
            self.process = subprocess.Popen(self.capture_cmd.strip())
        except (OSError, IOError), e:
            debug("Cannot start Wireshark: %s") % unicode(e)
            self.exit()
            return
        try:
            self.pipe = win32pipe.CreateNamedPipe(
                self.wireshark_pipe, win32pipe.PIPE_ACCESS_OUTBOUND,
                win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536,
                65536, 300, None)
            win32pipe.ConnectNamedPipe(self.pipe, None)
        except win32pipe.error:
            debug("Error while creating and connecting the pipe ...")
            win32file.CloseHandle(self.pipe)
            self.exit()
            return

        while True:
            data = in_file.read()
            if not self.process or self.process.returncode != None:
                win32file.CloseHandle(self.pipe)
                debug("Wireshark is not running, deleting pipe ...")
                self.exit()
                return
            if data:
                try:
                    win32file.WriteFile(self.pipe, data)
                except:
예제 #55
0
    def __del__(self):

        debug("Deleting pipe thread ...")
        if self.pipe:
            win32file.CloseHandle(self.pipe)
                    except (OSError, IOError), e:
                        QtGui.QMessageBox.critical(
                            globals.preferencesWindow,
                            translate("UiConfig_PreferencesGeneral",
                                      "Images directory"),
                            translate("UiConfig_PreferencesGeneral",
                                      "Cannot create images directory: %s") %
                            e.strerror)

        try:
            if not os.path.exists(self.conf.ios_path + os.sep +
                                  'baseconfig.txt'):
                shutil.copyfile(BASECONFIG_DIR + 'baseconfig.txt',
                                self.conf.ios_path + os.sep + 'baseconfig.txt')
                debug("Copying %s to %s" %
                      (BASECONFIG_DIR + 'baseconfig.txt',
                       self.conf.ios_path + os.sep + 'baseconfig.txt'))
        except (OSError, IOError), e:
            debug("Warning: cannot copy baseconfig.txt to " +
                  self.conf.ios_path + ": " + e.strerror)

        try:
            if not os.path.exists(self.conf.ios_path + os.sep +
                                  'baseconfig_sw.txt'):
                shutil.copyfile(
                    BASECONFIG_DIR + 'baseconfig_sw.txt',
                    self.conf.ios_path + os.sep + 'baseconfig_sw.txt')
                debug("Copying %s to %s" %
                      (BASECONFIG_DIR + 'baseconfig_sw.txt',
                       self.conf.ios_path + os.sep + 'baseconfig_sw.txt'))
        except (OSError, IOError), e: