class StopLocalServerWorker(QtCore.QObject): """ Worker for displaying a progress dialog when closing the server """ # signals to update the progress dialog. error = QtCore.pyqtSignal(str, bool) finished = QtCore.pyqtSignal() updated = QtCore.pyqtSignal(int) def __init__(self, local_server_process): super().__init__() self._local_server_process = local_server_process self._precision = 100 # In MS self._remaining_trial = int(10 * (1000 / self._precision)) @qslot def _callbackSlot(self, *params): self._local_server_process.poll() if self._local_server_process.returncode is None and self._remaining_trial > 0: self._remaining_trial -= 1 QtCore.QTimer.singleShot(self._precision, self._callbackSlot) else: self.finished.emit() def run(self): QtCore.QTimer.singleShot(1000, self._callbackSlot) def cancel(self): return
class StopLocalServerWorker(QtCore.QObject): """ Worker for displaying a progress dialog when closing the server """ # signals to update the progress dialog. error = QtCore.pyqtSignal(str, bool) finished = QtCore.pyqtSignal() updated = QtCore.pyqtSignal(int) def __init__(self, local_server_process): super().__init__() self._local_server_process = local_server_process def run(self): precision = 1 remaining_trial = 4 / precision # 4 Seconds while remaining_trial > 0: if self._local_server_process.returncode is None: remaining_trial -= 1 self.thread().sleep(precision) else: break self.finished.emit() def cancel(self): return
class DecompressIOSWorker(QtCore.QObject): """ Thread to decompress an IOS image. :param ios_image: IOS image path :param destination_file: destination path for the decompressed IOS image """ # signals to update the progress dialog. error = QtCore.pyqtSignal(str, bool) finished = QtCore.pyqtSignal() updated = QtCore.pyqtSignal(int) def __init__(self, ios_image, destination_file): super().__init__() self._is_running = False self._ios_image = ios_image self._destination_file = destination_file def run(self): """ Thread starting point. """ self._is_running = True try: decompressIOS(self._ios_image, self._destination_file) except (zipfile.BadZipFile, zlib.error) as e: self.error.emit( "File {} is corrupted {}".format(self._ios_image, e), True) return except (OSError, MemoryError) as e: self.error.emit( "Could not decompress {}: {}".format(self._ios_image, e), True) return # IOS image has successfully been decompressed self.finished.emit() def cancel(self): """ Cancel this worker. """ if not self: return self._is_running = False
def get_default_base_config(base_config_template_path): """ Copy the default base config template to settings directory (if not already present) and returns the path. :param base_config_template_path: path to the base config template :return: path to the base config """ config_dir = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), "base_configs") if base_config_template_path: try: os.makedirs(config_dir) except FileExistsError: pass except OSError as e: log.error( "could not create the base configs directory {}: {}".format( config_dir, e)) return "" try: base_config_path = os.path.join( config_dir, os.path.basename(base_config_template_path)) if not os.path.isfile(base_config_path): shutil.copyfile(base_config_template_path, base_config_path) return os.path.normpath(base_config_path) except OSError as e: log.error("could not copy {} to {}: {}".format( base_config_template_path, base_config_path, e)) return ""
def openConsole(self, command=None, aux=False): if command is None: if aux: command = self.consoleCommand(console_type="telnet") else: command = self.consoleCommand() console_type = "telnet" if aux: console_port = self.auxConsole() if console_port is None: raise ValueError( "AUX console port not allocated for {}".format( self.name())) # Aux console is always telnet console_type = "telnet" else: console_port = self.console() if "console_type" in self.settings(): console_type = self.settings()["console_type"] if console_type == "telnet": from .telnet_console import nodeTelnetConsole nodeTelnetConsole(self, console_port, command) elif console_type == "vnc": from .vnc_console import vncConsole vncConsole(self.consoleHost(), console_port, command) elif console_type == "http" or console_type == "https": QtGui.QDesktopServices.openUrl( QtCore.QUrl("{console_type}://{host}:{port}{path}".format( console_type=console_type, host=self.consoleHost(), port=console_port, path=self.consoleHttpPath())))
def __init__(self, parent): super().__init__(parent) self._notifs = [] self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowDoesNotAcceptFocus | QtCore.Qt.SubWindow) # QtCore.Qt.Tool) # QtCore.Qt.WindowStaysOnTopHint) self.setAttribute(QtCore.Qt.WA_ShowWithoutActivating) # | QtCore.Qt.WA_TranslucentBackground) self._layout = QtWidgets.QVBoxLayout() self._timer = QtCore.QTimer() self._timer.setInterval(1000) self._timer.timeout.connect(self._refreshSlot) self._timer.start() for i in range(0, MAX_ELEMENTS): l = QtWidgets.QLabel() l.setAlignment(QtCore.Qt.AlignTop) l.setWordWrap(True) l.hide() self._layout.addWidget(l) self.setLayout(self._layout)
def _loadIOUImages(self): """ Load the IOU images from the persistent settings file. """ # load the settings settings = QtCore.QSettings() settings.beginGroup("IOUImages") # load the IOU images size = settings.beginReadArray("iou_image") for index in range(0, size): settings.setArrayIndex(index) path = settings.value("path", "") image = settings.value("image", "") startup_config = settings.value("startup_config", "") use_default_iou_values = settings.value("use_default_iou_values", True, type=bool) ram = settings.value("ram", 256, type=int) nvram = settings.value("nvram", 128, type=int) server = settings.value("server", "local") key = "{server}:{image}".format(server=server, image=image) self._iou_images[key] = {"path": path, "image": image, "startup_config": startup_config, "use_default_iou_values": use_default_iou_values, "ram": ram, "nvram": nvram, "server": server} settings.endArray() settings.endGroup()
def __init__(self): QtGui.QWidget.__init__(self) self.setupUi(self) self._widget_slots = {0: self.uiSlot0comboBox, 1: self.uiSlot1comboBox, 2: self.uiSlot2comboBox, 3: self.uiSlot3comboBox, 4: self.uiSlot4comboBox, 5: self.uiSlot5comboBox, 6: self.uiSlot6comboBox} self._widget_wics = {0: self.uiWic0comboBox, 1: self.uiWic1comboBox, 2: self.uiWic2comboBox} self.uiStartupConfigToolButton.clicked.connect(self._startupConfigBrowserSlot) self.uiPrivateConfigToolButton.clicked.connect(self._privateConfigBrowserSlot) self.uiIOSImageToolButton.clicked.connect(self._iosImageBrowserSlot) self._idle_valid = False idle_pc_rgx = QtCore.QRegExp("^(0x[0-9a-fA-F]{8})?$") validator = QtGui.QRegExpValidator(idle_pc_rgx, self) self.uiIdlepcLineEdit.setValidator(validator) self.uiIdlepcLineEdit.textChanged.connect(self._idlePCValidateSlot) self.uiIdlepcLineEdit.textChanged.emit(self.uiIdlepcLineEdit.text())
def _loadSettings(self): """ Loads the settings from the persistent settings file. """ local_config = LocalConfig.instance() # restore the IOU settings from QSettings (for backward compatibility) legacy_settings = {} settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name in IOU_SETTINGS.keys(): if settings.contains(name): legacy_settings[name] = settings.value( name, type=IOU_SETTING_TYPES[name]) if "iourc" in legacy_settings: legacy_settings["iourc_path"] = legacy_settings["iourc"] del legacy_settings["iourc"] settings.remove("") settings.endGroup() if legacy_settings: local_config.saveSectionSettings(self.__class__.__name__, legacy_settings) self._settings = local_config.loadSectionSettings( self.__class__.__name__, IOU_SETTINGS) if sys.platform.startswith("linux") and not os.path.exists( self._settings["iouyap_path"]): iouyap_path = shutil.which("iouyap") if iouyap_path: self._settings["iouyap_path"] = iouyap_path # keep the config file sync self._saveSettings()
def __init__(self, ios_routers, parent): QtGui.QWizard.__init__(self, parent) self.setupUi(self) self.setPixmap(QtGui.QWizard.LogoPixmap, QtGui.QPixmap(":/symbols/router.normal.svg")) self.setWizardStyle(QtGui.QWizard.ModernStyle) if sys.platform.startswith("darwin"): # we want to see the cancel button on OSX self.setOptions(QtGui.QWizard.NoDefaultButton) self.uiRemoteRadioButton.toggled.connect(self._remoteServerToggledSlot) self.uiLoadBalanceCheckBox.toggled.connect(self._loadBalanceToggledSlot) self.uiIOSImageToolButton.clicked.connect(self._iosImageBrowserSlot) self.uiTestIOSImagePushButton.clicked.connect(self._testIOSImageSlot) self.uiIdlePCFinderPushButton.clicked.connect(self._idlePCFinderSlot) self.uiEtherSwitchCheckBox.stateChanged.connect(self._etherSwitchSlot) self.uiPlatformComboBox.currentIndexChanged[str].connect(self._platformChangedSlot) self.uiPlatformComboBox.addItems(list(PLATFORMS_DEFAULT_RAM.keys())) self._router = None # Validate the Idle PC value self._idle_valid = False idle_pc_rgx = QtCore.QRegExp("^(0x[0-9a-fA-F]{8})?$") validator = QtGui.QRegExpValidator(idle_pc_rgx, self) self.uiIdlepcLineEdit.setValidator(validator) self.uiIdlepcLineEdit.textChanged.connect(self._idlePCValidateSlot) self.uiIdlepcLineEdit.textChanged.emit(self.uiIdlepcLineEdit.text()) # location of the base config templates self._base_startup_config_template = get_resource(os.path.join("configs", "ios_base_startup-config.txt")) self._base_private_config_template = get_resource(os.path.join("configs", "ios_base_private-config.txt")) self._base_etherswitch_startup_config_template = get_resource(os.path.join("configs", "ios_etherswitch_startup-config.txt")) # FIXME: hide because of issue on Windows. self.uiTestIOSImagePushButton.hide() # Mandatory fields self.uiNamePlatformWizardPage.registerField("name*", self.uiNameLineEdit) self.uiIOSImageWizardPage.registerField("image*", self.uiIOSImageLineEdit) self._widget_slots = {0: self.uiSlot0comboBox, 1: self.uiSlot1comboBox, 2: self.uiSlot2comboBox, 3: self.uiSlot3comboBox, 4: self.uiSlot4comboBox, 5: self.uiSlot5comboBox, 6: self.uiSlot6comboBox} self._widget_wics = {0: self.uiWic0comboBox, 1: self.uiWic1comboBox, 2: self.uiWic2comboBox} self._ios_routers = ios_routers if Dynamips.instance().settings()["use_local_server"]: # skip the server page if we use the local server self.setStartId(1) if not ENABLE_CLOUD: self.uiCloudRadioButton.hide()
def __init__(self): QtGui.QWidget.__init__(self) self.setupUi(self) self._remote_servers = {} # Load the pre-configured console commands for name, cmd in sorted(PRECONFIGURED_TELNET_CONSOLE_COMMANDS.items()): self.uiTelnetConsolePreconfiguredCommandComboBox.addItem(name, cmd) for name, cmd in sorted(PRECONFIGURED_SERIAL_CONSOLE_COMMANDS.items()): self.uiSerialConsolePreconfiguredCommandComboBox.addItem(name, cmd) # Display the path of the settings file settings = QtCore.QSettings() self.uiConfigurationFileLabel.setText(settings.fileName()) self.uiProjectsPathToolButton.clicked.connect(self._projectsPathSlot) self.uiImagesPathToolButton.clicked.connect(self._imagesPathSlot) self.uiTemporaryFilesPathToolButton.clicked.connect( self._temporaryFilesPathSlot) self.uiImportConfigurationFilePushButton.clicked.connect( self._importConfigurationFileSlot) self.uiExportConfigurationFilePushButton.clicked.connect( self._exportConfigurationFileSlot) self.uiTelnetConsolePreconfiguredCommandPushButton.clicked.connect( self._telnetConsolePreconfiguredCommandSlot) self.uiSerialConsolePreconfiguredCommandPushButton.clicked.connect( self._serialConsolePreconfiguredCommandSlot)
def _loadSettings(self): """ Loads the settings from the persistent settings file. """ local_config = LocalConfig.instance() # restore the Qemu settings from QSettings (for backward compatibility) legacy_settings = {} settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name in QEMU_SETTINGS.keys(): if settings.contains(name): legacy_settings[name] = settings.value( name, type=QEMU_SETTING_TYPES[name]) settings.remove("") settings.endGroup() if legacy_settings: local_config.saveSectionSettings(self.__class__.__name__, legacy_settings) self._settings = local_config.loadSectionSettings( self.__class__.__name__, QEMU_SETTINGS) # keep the config file sync self._saveSettings()
def _loadSettings(self): """ Loads the settings from the persistent settings file. """ local_config = LocalConfig.instance() # restore the VPCS settings from QSettings (for backward compatibility) legacy_settings = {} settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name in VPCS_SETTINGS.keys(): if settings.contains(name): legacy_settings[name] = settings.value( name, type=VPCS_SETTING_TYPES[name]) settings.remove("") settings.endGroup() if legacy_settings: local_config.saveSectionSettings(self.__class__.__name__, legacy_settings) self._settings = local_config.loadSectionSettings( self.__class__.__name__, VPCS_SETTINGS) if not self._settings["base_script_file"]: self._settings["base_script_file"] = get_default_base_config( get_resource(os.path.join("configs", "vpcs_base_config.txt"))) if not os.path.exists(self._settings["vpcs_path"]): self._settings["vpcs_path"] = self._findVPCS(self) # keep the config file sync self._saveSettings()
def __init__(self): super().__init__() self.setupUi(self) self._widget_slots = {0: self.uiSlot0comboBox, 1: self.uiSlot1comboBox, 2: self.uiSlot2comboBox, 3: self.uiSlot3comboBox, 4: self.uiSlot4comboBox, 5: self.uiSlot5comboBox, 6: self.uiSlot6comboBox} self._widget_wics = {0: self.uiWic0comboBox, 1: self.uiWic1comboBox, 2: self.uiWic2comboBox} self.uiStartupConfigToolButton.clicked.connect(self._startupConfigBrowserSlot) self.uiPrivateConfigToolButton.clicked.connect(self._privateConfigBrowserSlot) self.uiSymbolToolButton.clicked.connect(self._symbolBrowserSlot) self.uiIOSImageToolButton.clicked.connect(self._iosImageBrowserSlot) self._server = None self._idle_valid = False idle_pc_rgx = QtCore.QRegExp("^(0x[0-9a-fA-F]{8})?$") validator = QtGui.QRegExpValidator(idle_pc_rgx, self) self.uiIdlepcLineEdit.setValidator(validator) self.uiIdlepcLineEdit.textChanged.connect(self._idlePCValidateSlot) self.uiIdlepcLineEdit.textChanged.emit(self.uiIdlepcLineEdit.text()) self._default_configs_dir = Servers.instance().localServerSettings()["configs_path"] # add the categories for name, category in Node.defaultCategories().items(): self.uiCategoryComboBox.addItem(name, category)
def _gns3UpdateReplySlot(self): network_reply = self.sender() if network_reply.error() != QtNetwork.QNetworkReply.NoError: if not self._silent: QtWidgets.QMessageBox.critical( self._parent, "Check For Update", "Cannot check for update: {}".format( network_reply.errorString())) return try: latest_release = bytes( network_reply.readAll()).decode("utf-8").rstrip() except UnicodeDecodeError: log.warning("Invalid answer from the update server") return if re.match(r"^[a-z0-9\.]+$", latest_release) is None: log.warning("Invalid answer from the update server") return if parse_version(version.__version__) < parse_version(latest_release): reply = QtWidgets.QMessageBox.question( self._parent, "Check For Update", "Newer GNS3 version {} is available, do you want to visit our website to download it?" .format(latest_release), QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: QtGui.QDesktopServices.openUrl( QtCore.QUrl("http://www.gns3.net/download/")) elif not self._silent: QtWidgets.QMessageBox.information(self._parent, "Check For Update", "GNS3 is up-to-date!")
def test_get_connected_auth(http_client, http_request, network_manager, response): http_client._connected = True http_client._user = "******" http_client._password = "******" callback = unittest.mock.MagicMock() http_client.createHTTPQuery("GET", "/test", callback) http_request.assert_called_with( QtCore.QUrl("http://[email protected]:3080/v2/test")) http_request.setRawHeader.assert_any_call(b"Content-Type", b"application/json") http_request.setRawHeader.assert_any_call(b"Authorization", b"Basic Z25zMzozc25n") http_request.setRawHeader.assert_any_call( b"User-Agent", "GNS3 QT Client v{version}".format(version=__version__).encode()) assert network_manager.sendCustomRequest.called args, kwargs = network_manager.sendCustomRequest.call_args assert args[0] == http_request assert args[1] == b"GET" # Trigger the completion response.finished.emit() assert callback.called
def __init__(self, ios_routers, parent): super().__init__(ios_routers, Dynamips.instance().settings()["use_local_server"], parent) self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/symbols/router.svg")) self.uiTestIOSImagePushButton.clicked.connect(self._testIOSImageSlot) self.uiIdlePCFinderPushButton.clicked.connect(self._idlePCFinderSlot) self.uiEtherSwitchCheckBox.stateChanged.connect(self._etherSwitchSlot) self.uiPlatformComboBox.currentIndexChanged[str].connect( self._platformChangedSlot) self.uiPlatformComboBox.addItems(list(PLATFORMS_DEFAULT_RAM.keys())) self._router = None # Validate the Idle PC value self._idle_valid = False idle_pc_rgx = QtCore.QRegExp("^(0x[0-9a-fA-F]{8})?$") validator = QtGui.QRegExpValidator(idle_pc_rgx, self) self.uiIdlepcLineEdit.setValidator(validator) self.uiIdlepcLineEdit.textChanged.connect(self._idlePCValidateSlot) self.uiIdlepcLineEdit.textChanged.emit(self.uiIdlepcLineEdit.text()) # location of the base config templates self._base_startup_config_template = get_resource( os.path.join("configs", "ios_base_startup-config.txt")) self._base_etherswitch_startup_config_template = get_resource( os.path.join("configs", "ios_etherswitch_startup-config.txt")) # FIXME: hide because of issue on Windows. self.uiTestIOSImagePushButton.hide() # Mandatory fields self.uiNameWizardPage.registerField("name*", self.uiNameLineEdit) self.uiIOSImageWizardPage.registerField("image*", self.uiIOSImageLineEdit) self._widget_slots = { 0: self.uiSlot0comboBox, 1: self.uiSlot1comboBox, 2: self.uiSlot2comboBox, 3: self.uiSlot3comboBox, 4: self.uiSlot4comboBox, 5: self.uiSlot5comboBox, 6: self.uiSlot6comboBox } self._widget_wics = { 0: self.uiWic0comboBox, 1: self.uiWic1comboBox, 2: self.uiWic2comboBox } from ..pages.ios_router_preferences_page import IOSRouterPreferencesPage self.addImageSelector(self.uiIOSExistingImageRadioButton, self.uiIOSImageListComboBox, self.uiIOSImageLineEdit, self.uiIOSImageToolButton, IOSRouterPreferencesPage.getIOSImage)
def _loadSettings(self): """ Loads the settings from the server settings file. """ local_config = LocalConfig.instance() # restore the VirtualBox settings from QSettings (for backward compatibility) legacy_settings = {} settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name in VBOX_SETTINGS.keys(): if settings.contains(name): legacy_settings[name] = settings.value( name, type=VBOX_SETTING_TYPES[name]) settings.remove("") settings.endGroup() if legacy_settings: local_config.saveSectionSettings(self.__class__.__name__, legacy_settings) self._settings = local_config.loadSectionSettings( self.__class__.__name__, VBOX_SETTINGS) if not os.path.exists(self._settings["vboxmanage_path"]): self._settings["vboxmanage_path"] = self._findVBoxManage(self) # keep the config file sync self._saveSettings()
def _loadSettings(self): """ Loads the settings from the persistent settings file. """ local_config = LocalConfig.instance() # restore the Dynamips settings from QSettings (for backward compatibility) legacy_settings = {} settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name in DYNAMIPS_SETTINGS.keys(): if settings.contains(name): legacy_settings[name] = settings.value(name, type=DYNAMIPS_SETTING_TYPES[name]) settings.remove("") settings.endGroup() if legacy_settings: local_config.saveSectionSettings(self.__class__.__name__, legacy_settings) self._settings = local_config.loadSectionSettings(self.__class__.__name__, DYNAMIPS_SETTINGS) if not os.path.exists(self._settings["dynamips_path"]): self._settings["dynamips_path"] = self._findDynamips(self) # keep the config file sync self._saveSettings()
def _importConfigurationFileSlot(self): """ Slot to import a configuration file. """ settings = QtCore.QSettings() configuration_file_path = settings.fileName() directory = os.path.dirname(configuration_file_path) path = QtGui.QFileDialog.getOpenFileName( self, "Import configuration file", directory, "Configuration file (*.conf);;All files (*.*)") if not path: return try: shutil.copyfile(path, configuration_file_path) except (shutil.Error, IOError) as e: QtGui.QMessageBox.critical( self, "Import configuration file", "Cannot import configuration file: {}".format(e)) return QtGui.QMessageBox.information( self, "Configuration file", "Configuration file imported, default settings will be applied after a restart" ) # restart the application from ..main_window import MainWindow main_window = MainWindow.instance() main_window.reboot_signal.emit()
class DecompressIOSThread(QtCore.QThread): """ Thread to decompress an IOS image. :param ios_image: IOS image path :param destination_file: destination path for the decompressed IOS image """ # signals to update the progress dialog. error = QtCore.pyqtSignal(str, bool) completed = QtCore.pyqtSignal() update = QtCore.pyqtSignal(int) def __init__(self, ios_image, destination_file): QtCore.QThread.__init__(self) self._ios_image = ios_image self._destination_file = destination_file self._is_running = False def run(self): """ Thread starting point. """ self._is_running = True try: decompressIOS(self._ios_image, self._destination_file) except zipfile.BadZipFile as e: self.error.emit( "File {} is corrupted {}".format(self._ios_image, e), True) return except OSError as e: self.error.emit( "Could not decompress {}: {}".format(self._ios_image, e), True) return # IOS image has successfully been decompressed self.completed.emit() def stop(self): """ Stops this thread as soon as possible. """ self._is_running = False
def _showContextualMenu(self): """ Contextual menu. """ menu = QtGui.QMenu() change_symbol_action = QtGui.QAction("Change symbol", menu) change_symbol_action.setIcon(QtGui.QIcon(":/icons/node_conception.svg")) self.connect(change_symbol_action, QtCore.SIGNAL('triggered()'), self._changeSymbolSlot) menu.addAction(change_symbol_action) menu.exec_(QtGui.QCursor.pos())
def _saveSettings(self): """ Saves the settings to the persistent settings file. """ # save the settings settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name, value in self._settings.items(): settings.setValue(name, value) settings.endGroup()
def _loadSettings(self): """ Loads the settings from the persistent settings file. """ # load the settings settings = QtCore.QSettings() settings.beginGroup(self.__class__.__name__) for name, value in VPCS_SETTINGS.items(): self._settings[name] = settings.value(name, value, type=VPCS_SETTING_TYPES[name]) settings.endGroup()
class SSHConnectionThread(QtCore.QThread): error_signal = QtCore.pyqtSignal(str) connected_signal = QtCore.pyqtSignal() def __init__(self, ssh_client, parent=None): self._ssh_client = ssh_client super().__init__(parent) def run(self): port = Endpoint.find_unused_port(1000, 10000) if port is None: self.error_signal.emit( "No port available in order to create SSH tunnel") return try: self._ssh_client.transport = paramiko.Transport(( self._ssh_client.host(), self._ssh_client.ssh_port(), )) self._ssh_client.transport.set_keepalive(30) with open(self._ssh_client.ssh_key()) as f: self._ssh_client.transport.connect( username=self._ssh_client.user(), pkey=paramiko.RSAKey.from_private_key(f)) endpoint = Endpoint(("127.0.0.1", port), ("127.0.0.1", self._ssh_client._http_port), self._ssh_client.transport) endpoint.enable() self._ssh_client._endpoints[port] = endpoint except (paramiko.ssh_exception.SSHException, OSError) as e: self.error_signal.emit(str(e)) return self._ssh_client._http_port = port self.connected_signal.emit()
def openConsole(self, command=None, aux=False): """ Opens a console. :param command: console command line :param aux: indicates an auxiliary console """ if command is None: if aux: command = self.consoleCommand(console_type="telnet") else: command = self.consoleCommand() console_type = "telnet" if aux: console_port = self.auxConsole() if console_port is None: raise ValueError( "AUX console port not allocated for {}".format( self.name())) # AUX console is always telnet console_type = "telnet" else: console_port = self.console() if console_port is None: log.debug("No console port allocated for {}".format( self.name())) return if "console_type" in self.settings(): console_type = self.consoleType() if console_type == "telnet": from .telnet_console import nodeTelnetConsole nodeTelnetConsole(self, console_port, command) elif console_type == "vnc": from .vnc_console import vncConsole vncConsole(self.consoleHost(), console_port, command) elif console_type.startswith("spice"): from .spice_console import spiceConsole spiceConsole(self.consoleHost(), console_port, command) elif console_type == "http" or console_type == "https": QtGui.QDesktopServices.openUrl( QtCore.QUrl("{console_type}://{host}:{port}{path}".format( console_type=console_type, host=self.consoleHost(), port=console_port, path=self.consoleHttpPath())))
def _scriptFileBrowserSlot(self): """ Slot to open a file browser and select a base script file for VPCS """ config_dir = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), "base_configs") path = QtGui.QFileDialog.getOpenFileName(self, "Select a script file", config_dir) if not path: return if not os.access(path, os.R_OK): QtGui.QMessageBox.critical(self, "Script file", "{} cannot be read".format(os.path.basename(path))) return self.uiScriptFileEdit.setText(os.path.normpath(path))
def __init__(self): self._config = configparser.ConfigParser() if sys.platform.startswith("win"): filename = "gns3_server.ini" else: filename = "gns3_server.conf" self._config_file = os.path.join( os.path.dirname(QtCore.QSettings().fileName()), filename) try: # create the config file if it doesn't exist open(self._config_file, 'a').close() except OSError as e: log.error("Could not create the local server configuration {}: {}". format(self._config_file, e)) self.readConfig()
def _privateConfigBrowserSlot(self): """ Slot to open a file browser and select a private-config file. """ config_dir = os.path.join(os.path.dirname(QtCore.QSettings().fileName()), "base_configs") path = QtGui.QFileDialog.getOpenFileName(self, "Select a private configuration", config_dir) if not path: return if not os.access(path, os.R_OK): QtGui.QMessageBox.critical(self, "Private configuration", "Cannot read {}".format(path)) return self.uiPrivateConfigLineEdit.clear() self.uiPrivateConfigLineEdit.setText(path)
def _get(self, url, finished_slot, user_attribute=None): """ HTTP get :param url: Url to download :param user_attribute: Param to pass to the finished slot :returns: QNetworkReply """ if self._network_manager is None: self._network_manager = QtNetwork.QNetworkAccessManager() request = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) request.setRawHeader(b'User-Agent', b'GNS3 Check For Update') request.setAttribute(QtNetwork.QNetworkRequest.User, user_attribute) reply = self._network_manager.get(request) reply.finished.connect(finished_slot) log.debug('Download %s', url) return reply