W hite W inter W olf Practical IT security, *nix systems & networking
How to add Cisco IOS -based devices in GNS3
Published: Sat 19 August 2017 in Cookbook.
- lab
- networking
- cisco
- gns3
- virtualization
In this article:
GNS3 historical use-case was to act as a GUI around Dynamips to emulate Cisco devices. However, while stable, this emulation may not be as straightforward as it could be and has some limitations.
To understand the negatives, we first need to understand how IOS -based Cisco hardware work.
How real gear works
Professional switch and router devices cannot be reduced to a general purpose small-factor computer with a few additional network interfaces.
When using a general purpose computer with classical network adapters to build a router/firewall appliance, all the processing occurs at the software level, generally the operating system kernel.
On specialized hardware such as Cisco switches and routers, the operating system (here IOS ) works tightly with some underlying specific (and usually proprietary) hardware and delegates parts or all of the processing to dedicated chips, the Application Specific Integrated Circuits or ASICs, to allow faster processing.
On general-purpose computers, this can be compared with the GPU located on graphical cards which allows to delegate 3D computation to allow a faster rendition than with the main general-purpose CPU .
Data processed at the hardware level do not involve the main CPU running IOS , only the dedicated ASIC , and is handled faster resulting in lower latency. On the other side, data processed at the software level allows more complex processing.
Most of the switching logic of Cisco Catalyst devices is implemented at the hardware level. Thus, emulating a Cisco catalyst device to run its IOS images would imply to reverse-engineer and reimplement most of the switch features.
On the other side, most of Cisco routers logic occurs at the software level as part of the IOS firmware. Emulating a Cisco router hardware to run its IOS images is therefore easier than emulating Cisco switches.
Dynamips, the Cisco devices emulator used by GNS3 , only emulates router devices. However, we will see some workarounds allowing to still have some Cisco switching features in your GNS3 topologies.
Cisco devices virtualization and emulation
There are several possibilities to add Cisco devices in your GNS3 topologies, some go through virtualization and other through emulation. These two notions must not be confused in order to better understand the advantages and limitations of each solution:
Virtualization software emulate Cisco devices hardware to execute unmodified Cisco IOS firmware images.
This is slower and consumes more resources than emulation software, but by running a genuine IOS it provides an experience closer to using a real Cisco device.
Emulation software emulate a whole Cisco device, including the IOS operating system.
This is faster and is more resource efficient, but depending on the fidelity of the emulation the final result may not have the same options or behavior as real gear.
Dynamips
Dynamips is a free software emulating Cisco routers hardware, thus allowing to run unmodified IOS firmware images in a virtualized environment.
While Dynamips allows to emulate a wide range of routers, two are of special interest and are the most widely used: the c3725/c3745 and c7200 devices.
Any valid image for these devices is sufficient in most situation. If, however, you require some specific features or would-like more information on the features proposed by a given firmware image, you can freely check the on-line Cisco Feature Navigator.
Cisco 3725/3745 integrated services routers
These routers accept Cisco EtherSwitch modules, allowing to add some switching ability to the router, and the good news is that Dynamips offer a basic but stable emulation of these modules.
These devices are end-of-life now, they only run IOS 12.x, but they are very versatile as they can act not only as a router but also as a layer-2 or layer-3 switch in your GNS -3 topology.
There is still a few difference between an EtherSwitch router module and an actual Catalyst switch (note that these differences come from how the EtherSwitch module itself works, not from Dynamips):
- Some commands are slightly different. For instance, the show vlan command from Catalyst devices becomes show vlan-switch on routers with the EtherSwitch module.
- DTP is not supported by the EtherSwitch module: no dynamic mode available on the EtherSwitch ports and the command switchport nonegotiate is not available.
- Only standard versions of the STP and EtherChannel protocols are available, Cisco extensions are not available for these protocols.
- No Gigabit port available (but it remains possible to “cheat” by setting the bandwidth value manually without negative impact in a virtual topology).
- The port-security feature is not available.
The GNS3 users forum hosts a more complete list of missing features.
As we will see below, some of these limitation can be solved by using IOU .
Cisco 7200 series routers
These devices are more recent and allow to run IOS 15.x images.
They have no switching capability, but they remain useful when you want to test some feature specific to IOS 15.x (for instance entry-level Cisco certifications require students to be familiar with the new licenses management features which came with IOS 15.0).
Finding IOS firmware images for Dynamips
IOS firmware images are proprietary software. Their license forbids free redistribution (yes, even the old obsolete ones!).
If your company is a Cisco Partner, then it should have access to Cisco’s IOS firmwares download pages.
Otherwise, you are expected to extract the firmware from a device you bought (it can be a second-hand router, this doesn’t matter, as long as it is the right model) and extract its firmware image as you would do to back it up on a TFTP server.
Alternatively, you can do as Keith Barker and do some “snooping around” 😉 .
Install IOS firmware images in GNS3
Installing an IOS firmware in GNS3 requires several steps. Most of them are shown during the first four minutes in this video by Anthony Sequeira (note that this video shows an older version of GNS3 ).
The complete procedure goes as follow:
From GNS3 option tab, go in Edit > Preferences to open the Preferences window.
On the left pane, go in Dynamips > IOS routers, then click the New button.
Select you IOS image file location. When asked, it is recommended to accept to copy it to GNS3 own directory tree.
With a sane image file, the device type should be automatically detected.
If the selected device supports EtherSwitch modules, a supplementary checkbox labeled This is an EtherSwitch router becomes available. This checkbox tells GNS3 to consider this device more as a switch than a router.
Ticking this box sets the following template properties:
- It adds by default a NM — ESW16 EtherSwitch module in the first device slot. This is the only really important action, the other ones are merely cosmetic.
- It enables the use of a specific startup script which set the default port configuration to better mimic those from a switch and set a specific hostname.
- The device template is associated to the Switches category instead of the Routers one.
- The device icon is changed accordingly.
Each of these settings can also be set later manually by right-clicking on the device template to access the Configure template window.
Unless you have some specific needs, the RAM size and modules can be left at their default values.
Now you need to determine a valid Idle- PC value for your IOS image. Simply click on the Idle- PC finder button and let GNS3 do all the work.
If the Idle- PC finder does not work, try to use it several times. With some images it will work only on the second or third attempt.
If this still doesn’t work:
- Finish the procedure normally.
- Add the newly created device in a new topology.
- Start it and open its console (right-click > Console) and wait the end of boot process, when the device is indeed Idle and showing its prompt.
- Now right-click and select Auto Idle- PC , this should work now.
For the curious who wonder what this value means:
When Dynamips executes your IOS image code, at some point the execution flow enters in an infinite loop waiting for an event to happen (a incoming packet on a network interface, a key pressed on the console, etc.). This infinite loop makes Dynamips to consume 100% of a host CPU core.
The solution is to determine the address of an instruction within the firmware file corresponding to this loop (and nothing else). This address is called the Idle- PC , it is a value of the Program Counter allowing to recognize when the device is in idle state.
As we will see later, the Dynamips process will regularly pause for some milliseconds when the IOS execution flow passes through this instruction, thus reducing the CPU consumption to a reasonable value.
Click on the Finish button to create the template.
The default idle settings are very conservative. When using relatively large topologies, Dynamips will still consume a noticeable amount of CPU even while idle.
Right-click on your newly created device template and click Configure Template.
Below the Advanced tab you will find the previously determined Idle- PC accompanied by an Idlemax and an Idlesleep values.
To reduce the host CPU consumption, Dynamips process counts the number of time the IOS firmware instruction at the address Idle- PC is executed, each time this number reaches Idlemax the Dynamips process sleeps for Idlesleep milliseconds.
The default value for Idlemax is 500, meaning that Dynamips sleep every 500 executions of the instruction at the Idle- PC address.
Setting Idlemax to 100 allows to reduce Dynamips CPU consumption even further with no noticeable side-effect.
IOU stands for IOS on Unix. This is a Cisco device emulator, allegedly initially designed to run on SunOS systems and later ported to other platforms such as Linux.
This was initially a internal project within Cisco, not designed to be distributed of even discussed outside of the circle of Cisco employees. If you are not a Cisco employee, you may not be authorized to use this software.
Nevertheless, an experimental version of this software leaked outside of Cisco offices. While being experimental and having its own serious issues, it is still an interesting alternative solving some of Dynamips-based IOS virtualization issues.
Unlike IOS firmwares which run in a virtualized environment controlled by the Dynamips process, IOU are native executable files which execute directly on your environment.
In other words: they are executable programs.
Would you be tempted in searching and downloading IOU from some untrusted shady sources, keep in mind that they may potentially embed some malware targeting your host and/or your network.
Several IOU binaries are available, emulating various options but more importantly emulating devices acting at the layer 2 (switching) or the layer 3 (routing). Layer 3 is well covered by Dynamips, however IOU is a really interesting alternative to test some layer 2 functionalities not available when using Dynamips.
Advantages of IOU compared to Dynamips-based virtualization:
- This is the lighter and faster option available to emulate Cisco devices.
- Port-security is functional (note though that while real gear CAM size is limited to a few thousands entries, on IOU it can host tens of millions of addresses, making MAC -flooding tests impractical).
- EtherChannel is functional.
- STP options are available, but are severely broken and nearly unusable.
Disadvantages of IOU :
- This is not a real IOS , so several options and behavior may be different from real gear (see the CAM table size for instance).
- While available, the Spanning Tree Protocol ( STP ) is severely broken. The election process works correctly, but if there is a loop in your topology (which is precisely what this protocol is meant to handle) any broadcast systematically results in a broadcast storm with a very high CPU consumption. The CPU consumption immediately gets back to normal as soon as the loop is broken (by disabling an interface through IOS for instance).
- According to various sources, QoS is not functional either.
- Chances are that several other things are missing or broken (impossible for instance to set a port speed).
If you want to learn more about IOU , the reference on the subject is Evil Router’s FAQ . More background information is available on Free CCNA labs, another blog maintained by the same author.
Install IOU in GNS3
I am using Debian on a 64 bit architecture, depending on your system and host architecture the exact steps you need to follow may vary.
IOU is a 32 bits executable file. To use it on a 64 bit environment, you need to enable the 32-bits repository to install the GNS3 module in charge of handling IOU images and all required libraries:
The IOU attempts to notify the host xml.cisco.com upon start, to disable this edit your /etc/hosts/ file and associate this name to some black-hole loopback address:
You usually also need a license key to run IOU , this key is calculated from your hostname and IP address. Usually a key generator ( keygen.py ) is provided with the IOU binaries allowing to generate the appropriate key file.
In GNS3 , don’t forget to specify the location of your license key file in the general IOS on UNIX section from the Preferences screen.
Then go in IOU devices, click New, this should be straight-forward.
My personal guess is that IOU is an early development snapshot of what later became the vIOS once freely downloadable from Cisco website as part of their SDK Cisco’s One Platform Kit (onePK), later replaced by the paid VIRL virtualization platform not freely downloadable anymore.
vIOS usually presents itself as a virtual machine image hosting IOS . It is very similar in its form and behavior with IOU , there are images available for the layer 2 and 3 but layer 2 are the most useful ones ( IMHO ).
Compared to IOU , the fact that it does not run natively on the host raises some limitations:
- It consumes more resources than IOU , even if under some condition it may remain more efficient that Dynamips images but I’m not even sure about this.
- As with any VM -based images, GNS3 doesn’t allow to modify its network links while the VM is running. Although this is usually not a problem with real end-devices nodes such as workstations and servers, having to shutdown and restart half of your switches each time you want to change your topology seems like a major drawback to me.
The advantage compared to IOU :
- STP is fixed.
I know, this is very short, that’s why I usually prefer to use IOU over vIOS.
Maybe there is a way to extract the emulated IOS from the virtual machine image. Due to the low benefits I did not do any research in this area, but this would allow to get the best of the two worlds.
Idle pc gns3 что это
Firstly let me say thanks to Jeremy Grossmann (principal programmer for GNS3) for helping me finally get my head around this concept. I have to admit that I’d I had only a vague idea of what was happening when I wrote this post on the GNS3 forum, but recently I decided I had to nail it.
In a nutshell:
Without an Idle-PC set, dynamips attempts to emulate instructions one at a time as fast as it can, consuming up to 100% of the available CPU.
The Idle-PC is a guess at where the Program Counter might be pointing to an idle-loop in the emulated router.
When emulator has visits this PC value Idle-Max times, it suspends itself for Idle-Sleep ms to allow other processes to get on their tasks.
Details
To understand the dynamips/GNS3 Idle-PC concept, you have to start by looking at the way software operates.
A normal piece of software generally has one or more places in the code where the program just sits in an “idle” loop – say waiting for a key press. Or a message to arrive. Or for a timer to expire to remind it to send a message.
However dynamips is a different kind of program. It is an emulator. It takes a binary image of MIPS machine code and interprets each instruction one at a time and then executes that instruction on the host computer. The basic logic is something like this:
So there are no idle states – dynamips just screams through those instructions one at a time around and around – except that there will be many, many places where the instruction that is executed is one that changes the program counter, causing dynamips to extract the instructions in a non-linear sequence.
And some of those instructions will be be in little groups where the emulated router is sitting in an idle state – as in waiting for a packet to arrive or a key to be pressed at the console. The problem is, dynamips has no idea whether the current Program Counter (PC) is pointing to an instruction that is doing something important, or one that is just part of the few instructions that get repeated over and over in an idle loop.
Now if dynamips could somehow know that when the Program Counter (PC) was pointing to a certain pice of code that was just an idle loop, it could suspend itself for a while, so the logic would change to:
But dynamips has no way of knowing “IF the new PC is pointing to an idle loop” – because dynamips cannot predict future instructions nor understand them. This makes it impossible to optimise the executed code like compilers do or to know if the instructions are worth being executed.
So we make some guesses at when the Program Counter MIGHT be executing an idle loop. We call this value the Idle-PC value.
If we guess at a place where the emulated router spends a lot of idle time, then the host computer gets lots of chances to get on with other stuff. If we guess a PC (remember PC=Program Counter) where the code is only executed rarely, then the host computer will spend 100% of its CPU executing the dynamips simple loop.
Since every Cisco router image has a different set of instructions, these idle lops will be in different places on different images. But once a good Idle-PC has been found for one image, it should be good for all emulations of that image – no matter whether you are running your dynamips on a Windows computer, and OS X Macintosh, a Linux box or an iPad :J
The only other issue then, is how long and low often should dynamips sleep for when it has found the PC for the idle loop? This is where the Idle-Max and Idle-Sleep values found under the Advanced settings of the GNS3 IOS images and hypervisors dialogue come in. (Note: This feature was added to GNS3 in version 0.8.4)
Dynamips doesn’t go to sleep EVERY time the PC hits the Idle-PC. It waits until it has hit the Idle-PC Idle-Max times before sleeping for Idle-Sleep ms. That way the router still gets a chance to do the things it needs to do between visits to the Idle-PC value. If you adjust the Idle-Max too low or the Idle-Sleep too high, your emulated routers will slow to a crawl, they will loose connections with their neighbours and bad things will happen. However some folk have had good success at playing with these numbers.
To summarise:
Without an Idle-PC set, dynamips attempts to emulate instructions one at a time as fast as it can, consuming up to 100% of the available CPU.
The Idle-PC is a guess at where the Program Counter might be pointing to an idle-loop in the emulated router.
When emulator has visits this PC value Idle-Max times, it suspends itself for Idle-Sleep ms to allow other processes to get on their tasks.
Remember, if you found this post helpful, you can make it easier for others to find by giving it a good rating, or by clicking on one of the sharing options.
GNS3 Setup Wizard — Local server
This document explains how use the GNS3 Setup Wizard to configure a GNS3 local server. This is also called a local Dynamips implementation of GNS3.
If you want to use IOSvL2, IOU, IOSv, IOS-XRv, ASAv or want to create more complex topologies, the GNS3 VM is recommended for Windows and Mac OS implementations (it’s optional for Linux users).
Overview#
The GNS3 Setup Wizard is displayed when GNS3 starts up for the first time. This provides an easy way to initially configure GNS3 options:
Manually starting the Setup Wizard#
You can also manually start the Setup Wizard at any time by clicking ‘Help’ and then ‘Setup Wizard’ in the GNS3 GUI:
Disable the Setup Wizard#
As of the GNS3 2.2.0 release, the default is for “Don’t show this again” on the first Setup Wizard screen to be selected.
With previous GNS3 releases (like the 2.1.x series), this was not the case.
Using the GNS3 Setup Wizard#
Select "Run appliances on my local computer" in the Wizard and click 'Next >':
This guide explains the Local server set up. For the Local GNS3 VM guide click here
For Windows and Mac OSX users, running appliances on your local computer will limit you to only running certain devices, like the legacy IOS images that Dynamips supports (see here), VPCS, and the other devices that GNS3 includes in the base installation (like VPCS, the built-in hub and ethernet switches, etc…)
This is not the case with users running GNS3 in Linux. GNS3 can run IOS images, QEMU/KVM VMs, and Docker containers natively, so they should select the local server optional, unless they are optionally using the GNS3 VM instead.
The next screen shows the server path (the directory gns3server.exe is stored in locally), the Host binding, and the port GNS3 will use to connect to gns3server.exe. Alter these settings to suit your local environment, and click 'Next':
While there is a lengthy dropdown list of possible host binding addresses, opting for the 127.0.0.1 local loopback address tends to be the most trouble-free option.
After clicking ‘Next’, you should get a validation screen:
Some anti-virus suites will block the connection attempt, so you may need to create exception/whitelist entries for the gns3server, ubridge, and dynamips executables in order for the connection validation to be successful.
Performing that operation varies between antivirus suites, so you’ll need to refer to their relevant documentation to learn how to do this.
By default, gns3server, ubridge, and dynamips should already be allowed through the Windows firewall. It’s worth double checking to ensure that’s the case.
Once the connection to the local server has been validated, clicking 'Next' will show you a brief summary:
(notice that the Server Type lists “Local”, in the above image)
Click 'Finish'
With recent releases of GNS3, devices are typically installed using the Import Appliance wizard (File->Import Appliance). The appropriate appliance templates for the devices you wish to use, are available in the GNS3 Marketplace. However, this article will discuss adding and configuring a supported IOS image manually, as the articles here and here discuss appliance templates, and using the Import Appliance Wizard to automate installation of images/VMs/docker containers.
In the GNS3 GUI, click Edit > Preferences, to open the preferences menu.
In the preferences menu, select 'IOS Routers and New', to begin the process of importing an image.
You’ll be prompted which server you’d like to run the image with, but everything except 'Run the IOS router on my local computer' should be greyed out.
(the option to run the image via the GNS3 VM isn’t greyed out in the above picture, since the GNS3 VM had previously been set up on this PC)
On the next screen, click 'Browse' to import a supported IOS image:
Browse to the folder where you have stored your Cisco IOS images, select the image, and click 'Open':
Some vendors provide images of their systems for free. Others do not, and you are required to provide your own images. The GNS3 team are unable to legally provide Cisco IOS images to anyone.
GNS3 can decompress IOS images to allow for quicker booting of routers in your GNS3 topologies. This is recommended for a better user experience. Click 'Yes' to decompress the image:
The directory where the decompressed image is stored is displayed. Click 'Next' to continue the setup:
The Name and platform window displays. Confirm the Platform selection, and configure the router Name. Click 'Next' :
A Default RAM setting is displayed. It is important that you check your Router's minimum memory requirements using the Cisco website. Click the 'Check for minimum and maximum RAM requirement' option:
The Cisco Feature Navigator is opened in your default web browser. Select Image Name and enter the name of the image you are using:
Click Search for Image(s):
The minimum DRAM requirements for the IOS are displayed. Note the value for your IOS image:
Set the Default RAM value to the value recommended by the Cisco Feature Navigator (yours may be different to the screenshot) and click 'Next':
Select your preferred Network adapters. This is device dependant.
In this example both Ethernet Serial interfaces will be added to the router. Once selected, click 'Next':
The c3725 IOS images will have the GT96100-FE dual Fast Ethernet adapter installed in slot 0 by default, and you can add extra adapters in slots 1 and 2. The types of adapters, and how many slots you are allowed to add will depend on the IOS image in use.
Once you have configured the network adapters, click 'Next' to add WIC adapters (again, this is IOS image dependent):
When you have added WIC adapters (if available), click 'Next >'
It is important for optimum GNS3 performance that an Idle-PC value be selected. Occasionally, some images will already display an Idle-PC value:
If a green Idle-PC value is NOT shown then click the 'Idle-PC finder' button to find an Idle-PC value:
If you selected the 'Idle-PC finder' button (only necessary if no value was detected automatically), GNS3 will calculate a value:
(note, this may take a few moments, depending on the speed of your PC) An Idle-PC value is displayed. Click 'OK' to complete:
If no Idle-PC value is displayed, try clicking the Idle-PC finder button again. You may also need to reboot your computer and try again is no value is found. It’s incredibly important to have an idle-pc value when using supported IOS images. Without this value, DynaMIPS can’t prevent an instance of an IOS image from consuming 100% of a CPU core or hardware thread (in the case of CPUs capable of hyperthreading).
Click 'Finish' to complete the GNS3 Setup Wizard:
In this instance, the IDLE PC value was already specified, according to the value listed in this page, so you can click 'Finish', instead of going through the IDLE-PC finder process.
The Preferences window displays showing the settings you have configured through the Setup Wizard. Click 'OK' to complete the process:
(notice that the name of your PC will be listed next to ‘Server’ in the shown settings. That is further indication that this router will be run via the local computer, as opposed to the GNS3 VM)
The New Project Window displays. Give your new Project a Name and click 'OK':
The GNS3 workspace displays:
Congratulations! You are now ready to create your first GNS3 topologies. Click here to create a basic GNS3 topology
Сети для самых маленьких. Микровыпуск №1. Переход на GNS3
Мы немножко нарушим хронологию цикла Сети для самых маленьких.
Компания ЛифтМиАП разрастается, покупая новые филиалы по всей стране. Поэтому следующая наша статья будет посвящена технологиям VPN и подключению удалённых офисов к центральному. Будут обсуждаться такие темы, как GRE, IPSec и DMVN. Тут Packet Tracer уже едва ли может нам чем-то помочь.
Пришло время для больших игр и перехода на профессиональное ПО для симулирования сети. Да и темы, положа руку на сердце, уже не для самых маленьких.
На выбор в сегодняшнем меню:
- GNS3 — Graphical Network Simulator
- IOU — IOS on UNIX
Под катом аргументы за и против и частичный перенос топологию из РТ в GNS, а сначала традиционное видео, на этот раз умеренной длины.
GNS или IOU? IOU или GNS? Начнём с IOU, потому что его мы использовать не будем.
IOS On UNIX
Как видно из названия — ставится поверх UNIX. Раньше это был только Solaris, теперь же поддерживается и Linux.
Самые существенные его плюсы:
1) Практически полноценная поддержка как L3, так и L2. Этот эмулятор используется при сдаче лабораторных экзаменов CCIE.
2) Низкие требования к ресурсам ПК. Точнее к CPU. Памяти тоже надо немало.
3) Нет ограничений по платам и интерфейсам. В настройках вы просто указываете сколько и чего вы хотите.
Минусы:
1) Самое главное — это проприетарный софт, который официально не распространяется вообще никак. В торрентах существуют образы L2IOU, L3IOU, но это незаконно.
Вообще ходит легенда, что на сайте cisco одно время было написано:
Это основная причина, по которой мы отказались от идеи использования IOU в нашем цикле.
2) Установка и настройка IOU не отличается простотой. Нужно обладать недюжим спокойствием и кое-каким опытом работы в никсах, чтобы разобраться с топологиями, файлами настройки и сохранением конфигурации устройств.
Тоже немаловажная причина — нам бы с меньшими жертвами осуществить переход и не отпугнуть “самых маленьких”.
3) Нет графического интерфейса.
В общем это годная утилита для беспринципных тру ИТшников. Если вам нужна лаба из 20+ устройств или надо поработать с QinQ, Rapid PVST (и прочие L2-технологии) или хочется всерьёз заняться Tshoot, то это для вас.
Graphical Network Simulator
Наш выбор. Имеет два серьёзных недостатка:
— Сильно требователен к CPU и памяти. 10 маршрутизаторов уже всерьёз нагрузят ПК. Использование процессора можно снизить с помощью механизма Idle PC. Без этого и 3-4 с трудом бы, пожалуй, пошли.
— Очень слабо поддерживает функции L2. Есть только подобие коммутаторов, на которых можно максимум настроить Access/Trunk порты и свичовые платы для маршрутизаторов, L2-функционал которых также очень ограничен.
Необходимо ещё где-то раздобыть образы IOS. GNS — это практически виртуальный маршрутизатор и для запуска ему также необходимо ПО, которым и является IOS.
Взять его можно с сайта cisco, если у вас там есть аккаунт с необходимыми правами, скачать с имеющегося у вас оборудования или другой всем известный способ.
Зато при этом GNS имеет графический интерфейс (технически это и есть GUI для Dynamips), что сильно облегчает создание виртуальных лабораторий.
Компьютер можно подключить в реальную сеть в качестве виртуального маршрутизатора.
Установка и подготовка к работе
Скачать можно тут. Для Ubuntu, Debian GNS доступен из репозитария.
apt-get install gns3
После установки выполняем начальную настройку.
Полагаем, что образы у вас уже есть. Добавим их:
Автоматически определяется модель маршрутизатора.
Обратите внимание на поле IDLE PC. Пока не трогаем.
Save.
При создании нового проекта вам предлагается ввести название и параметры.
Самое главное тут не забудьте поставить галку «Save nvram and other disk files», иначе после перезапуска приложения у вас не сохранится конфигурация.
Перетаскиваем маршрутизатор на рабочую площадку. Естественно, берём ту модель, для которой есть образ. Ошибок быть не должно.
Жмакаем сверху на кнопку . Обратите внимание на то, как возросла нагрузка на CPU:
. Теперь волнение нужно успокоить. Для этого выбираем в контекстном меню Idle PC.
Именно этот механизм позволяет оптимизировать использование ресурсов процессора.
ПК вычисляет несколько значений и предлагает вам целый их список. Рекомендуется выбирать значения со знаком *. Как только они применяются, загрузка CPU падает
Если вдруг не получилось, итерируем до тех пор, пока не достигнем желаемого.
Теперь самое удачное значение перепишите на листочек, откройте окно управления образами Edit->IOS Image and hyervisors и заполняете то самое поле IDLE PC. Теперь при следующем запуске после загрузки IOS GNS не должен отожрать всё процессорное время.
Всё готово для подключения.
У GNS есть стандартные средства для этого:
По умолчанию он использует приложение xTerm, которое, наверняка, есть почти в любом дистрибутиве.
Признаться, у меня почему-то он не работает — нельзя набирать символы. В настройках терминальных программ можно выбрать другое приложение, например, Konsole — оно у меня заработало.
Для оболочки Gnome (Unity) при настройке терминала можно выбрать родной терминал, несмотря на то, что его нет в списке по-умолчанию. Достаточно вставить следующую строчку в поле Preconfigurated terminal commands:
gnome-terminal -t %d -e ‘telnet %h %p’ >/dev/null 2>&1 &
Но на самом деле вы можете пользоваться любым другим терминальным приложением, к которому привыкли. Более того, вы можете подключаться даже с другого компьютера в сети, потому что выполняется это командой:
telnet a.b.c.d 2000
Что такое telnet — понятно, a.b.c.d — адрес компьютера (если вы подключаетесь с этого же ПК, то адрес 127.0.0.1), 2000 — номер TCP порта, выделенного для этого устройства (как правило начинается с 2000 для таких программ). У каждого маршрутизатора будет свой.
Номер порта можно посмотреть так:
Перенос конфигурации из РТ в GNS
Тут кроется дьявол. В GNS у нас максимум 3 интерфейса: FE0/0, Fe0/1 и можно добавить ещё плату с FE1/0, а в лабе на РТ мы иногда используем FE1/1. Поэтому нельзя просто скопировать и вставить — местами придётся переработать конфигурацию.
Схема, которую мы будем воспроизводить:
Мы взяли только Сибирское кольцо, чтобы показать, как это делается, и не загружать схему другими филиалами.
Добавляем маршрутизаторы. Будем работать, например, с 2691-ми.
Названия устройств ограничены в используемых символах, поэтому мы добавим им описания:
Также добавляем коммутаторы: один для «Балаган Телеком», второй для «Филькин сертификат».
Прежде чем, запускать, добавим в МСК плату.
В списке только одна плата с FE портами. Мы вполне могли бы добавить платы с последовательными портами, но зачем?
Настроим так называемые коммутаторы. Для этого доступен только GUI.
Удаляем все порты.
Добавляем несколько новых, но в качестве номера влана указываете 0, а тип порта dot1q. Это означает транковый порт, который пропускает все вланы.
То же и со вторым.
Перед запуском маршрутизаторов, нужно создать все линки хотя бы примерно согласно старой схеме.
Выбрать нужно Manual, тогда можно указывать конкретные порты.
А можно вообще в настройках указать, чтобы всегда выбиралось только Manual.
Если до этого не подбирали значение Idle PС для этого образа, лучше запустить одно устройство и сделать это.
Запускаем остальные. Можно можно по очереди, можно все разом, если поставили паузу между запусками в настройках.
Если у вас старый компьютер, в этот момент он может серьёзно повиснуть. Нужно будет подождать.
Конфигурацию для маршрутизатора в Москве можно просто скопировать — с интерфейсами всё в порядке.
- Будьте аккуратнее при копировании команды
- После вставки конфигурации интерфейсы остаются в состоянии shutdown.
Neighbor ID Pri State Dead Time Address Interface
172.16.255.112 1 FULL/DR 00:00:36 172.16.2.197 FastEthernet1/0.911
172.16.255.80 1 FULL/BDR 00:00:34 172.16.2.130 FastEthernet0/1.8
msk-arbat-gw1#sh ip route
Codes: C — connected, S — static, R — RIP, M — mobile, B — BGP
D — EIGRP, EX — EIGRP external, O — OSPF, IA — OSPF inter area
N1 — OSPF NSSA external type 1, N2 — OSPF NSSA external type 2
E1 — OSPF external type 1, E2 — OSPF external type 2
i — IS-IS, su — IS-IS summary, L1 — IS-IS level-1, L2 — IS-IS level-2
ia — IS-IS inter area, * — candidate default, U — per-user static route
o — ODR, P — periodic downloaded static route
Gateway of last resort is 198.51.100.1 to network 0.0.0.0
172.16.0.0/16 is variably subnetted, 17 subnets, 3 masks
O 172.16.255.80/32
[110/11] via 172.16.2.130, 01:32:53, FastEthernet0/1.8
O 172.16.2.160/30 [110/20] via 172.16.2.130, 01:32:53, FastEthernet0/1.8
O 172.16.255.96/32
[110/12] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
O 172.16.255.112/32
[110/2] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
C 172.16.2.128/30 is directly connected, FastEthernet0/1.8
C 172.16.255.1/32 is directly connected, Loopback0
C 172.16.2.196/30 is directly connected, FastEthernet1/0.911
O 172.16.2.192/30
[110/11] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
C 172.16.2.32/30 is directly connected, FastEthernet0/1.7
C 172.16.2.16/30 is directly connected, FastEthernet0/1.5
C 172.16.4.0/24 is directly connected, FastEthernet0/0.102
C 172.16.5.0/24 is directly connected, FastEthernet0/0.103
C 172.16.6.0/24 is directly connected, FastEthernet0/0.104
C 172.16.0.0/24 is directly connected, FastEthernet0/0.3
C 172.16.1.0/24 is directly connected, FastEthernet0/0.2
C 172.16.2.0/30 is directly connected, FastEthernet0/1.4
C 172.16.3.0/24 is directly connected, FastEthernet0/0.101
198.51.100.0/28 is subnetted, 1 subnets
C 198.51.100.0 is directly connected, FastEthernet0/1.6
S* 0.0.0.0/0 [1/0] via 198.51.100.1
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.197 860 msec 64 msec 4 msec
2 172.16.2.193 412 msec 56 msec *
msk-arbat-gw1(config)#int fa1/0.911
msk-arbat-gw1(config-subif)#sh
*Mar 1 00:57:43.995: %OSPF-5-ADJCHG: Process 1, Nbr 172.16.255.112 on FastEthernet1/0.911 from FULL to DOWN, Neighbor Down: Interface down or detached
msk-arbat-gw1#
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.130 4 msec 12 msec 12 msec
2 172.16.2.162 28 msec 20 msec *
msk-arbat-gw1(config)#int fa1/0.911
msk-arbat-gw1(config-subif)#no sh
msk-arbat-gw1(config-subif)#
*Mar 1 00:59:21.179: %OSPF-5-ADJCHG: Process 1, Nbr 172.16.255.112 on FastEthernet1/0.911 from LOADING to FULL, Loadingping 172.16.255.96
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 172.16.255.96, timeout is 2 seconds:
.
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/28/60 ms
msk-arbat-gw1#tracer 172.16.255.96
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.197 8 msec 16 msec 12 msec
2 172.16.2.193 12 msec 8 msec *
После возвращения интерфейса в исходное, маршрут тоже переключается обратно на Владивосток.
С помощью GNS можно легко снимать дампы трафика. Для этого достаточно Wireshark. Но под линуксом у меня почему-то не получилось запустить.
Для этого нужно сделать всего лишь следующее:
1) кликнуть правой кнопкой на линк между двумя устройствами
2) Выбрать capture в контекстном меню. Если после этого запустился вайршарк, его можно закрыть — в реальном времени он не собирает данные. Чтобы он не запускался в будущем, можно убрать галочку в настройках:
3) Выполнить запланированные действия.
4) Из контекстного меню линка выберите Start Wireshark.
В открывшемся окне будут все пакеты, которые вы хотели отловить.
Существуют и другие сетевые симуляторы, которые не охвачены данной статьёй.
Например, Bosson, который просит вменяемых денег за свой продукт для подготовки к сдаче CCNA/CCNP. К сожалению, не тестировал его, не могу сказать ничего о его качестве.
В русскоязычном сегменте совершенно незаслуженно обделён вниманием OpenSource проект NS3. Очень мощная утилита без привязки к конкретным вендорам.
Совершенная иная парадигма создания топологий и настройки, напоминающая скорее язык программирования.
Продукт хорошо документирован, но, видимо, в силу своей сложности всё же не сыскал большой известности в сети.
NS3 используется преимущественно в зарубежных ВУЗах, но даже у нас на его основе проворачивали интересные проекты.
Кроме того, наверняка, у каждого вендора есть какой-то внутренний симулятор их оборудования.
Точно могу сказать за Huawei, что у них имеется два мощных приложения:
WVRP — внутренний продукт, требует лицензий и работает только в корпоративной сети. Аналог GNS3, но с большими возможностями и меньшим потреблением ресурсов.
eNSP — публичный симулятор оборудования Huawei. Имеет урезанный функционал по сравнению с WVRP. Скорее похож на Packet Tracer по простоте работы, но с гораздо большими возможностями.
Есть видеоинструкция.
Бесплатен, свободен для загрузки (достаточно завести аккаунт на сайте). Скорее всего, на нём мы и будем в будущем отрабатывать Multicast — в eNSP это можно сделать довольно наглядно.
Я находил в сети симулятор Juniper, но не знаю, насколько он функционален и является ли официальным.
Полезные ссылки по теме
Данную статью вы также можете читать на нашем сайте: linkmeup.ru/blog/36.html.
Возможно, вам будет удобнее воспользоваться ЖЖ
Друзья и коллеги, наша команда ведущих подкаста остро нуждается в женском голосе, который скрасит мужские басы в эфире.
GNS3 Setup Wizard — Local server
This document explains how use the GNS3 Setup Wizard to configure a GNS3 local server. This is also called a local Dynamips implementation of GNS3.
If you want to use IOSvL2, IOU, IOSv, IOS-XRv, ASAv or want to create more complex topologies, the GNS3 VM is recommended for Windows and Mac OS implementations (it’s optional for Linux users).
Overview#
The GNS3 Setup Wizard is displayed when GNS3 starts up for the first time. This provides an easy way to initially configure GNS3 options:
Manually starting the Setup Wizard#
You can also manually start the Setup Wizard at any time by clicking ‘Help’ and then ‘Setup Wizard’ in the GNS3 GUI:
Disable the Setup Wizard#
As of the GNS3 2.2.0 release, the default is for “Don’t show this again” on the first Setup Wizard screen to be selected.
With previous GNS3 releases (like the 2.1.x series), this was not the case.
Using the GNS3 Setup Wizard#
Select "Run appliances on my local computer" in the Wizard and click 'Next >':
This guide explains the Local server set up. For the Local GNS3 VM guide click here
For Windows and Mac OSX users, running appliances on your local computer will limit you to only running certain devices, like the legacy IOS images that Dynamips supports (see here), VPCS, and the other devices that GNS3 includes in the base installation (like VPCS, the built-in hub and ethernet switches, etc…)
This is not the case with users running GNS3 in Linux. GNS3 can run IOS images, QEMU/KVM VMs, and Docker containers natively, so they should select the local server optional, unless they are optionally using the GNS3 VM instead.
The next screen shows the server path (the directory gns3server.exe is stored in locally), the Host binding, and the port GNS3 will use to connect to gns3server.exe. Alter these settings to suit your local environment, and click 'Next':
While there is a lengthy dropdown list of possible host binding addresses, opting for the 127.0.0.1 local loopback address tends to be the most trouble-free option.
After clicking ‘Next’, you should get a validation screen:
Some anti-virus suites will block the connection attempt, so you may need to create exception/whitelist entries for the gns3server, ubridge, and dynamips executables in order for the connection validation to be successful.
Performing that operation varies between antivirus suites, so you’ll need to refer to their relevant documentation to learn how to do this.
By default, gns3server, ubridge, and dynamips should already be allowed through the Windows firewall. It’s worth double checking to ensure that’s the case.
Once the connection to the local server has been validated, clicking 'Next' will show you a brief summary:
(notice that the Server Type lists “Local”, in the above image)
Click 'Finish'
With recent releases of GNS3, devices are typically installed using the Import Appliance wizard (File->Import Appliance). The appropriate appliance templates for the devices you wish to use, are available in the GNS3 Marketplace. However, this article will discuss adding and configuring a supported IOS image manually, as the articles here and here discuss appliance templates, and using the Import Appliance Wizard to automate installation of images/VMs/docker containers.
In the GNS3 GUI, click Edit > Preferences, to open the preferences menu.
In the preferences menu, select 'IOS Routers and New', to begin the process of importing an image.
You’ll be prompted which server you’d like to run the image with, but everything except 'Run the IOS router on my local computer' should be greyed out.
(the option to run the image via the GNS3 VM isn’t greyed out in the above picture, since the GNS3 VM had previously been set up on this PC)
On the next screen, click 'Browse' to import a supported IOS image:
Browse to the folder where you have stored your Cisco IOS images, select the image, and click 'Open':
Some vendors provide images of their systems for free. Others do not, and you are required to provide your own images. The GNS3 team are unable to legally provide Cisco IOS images to anyone.
GNS3 can decompress IOS images to allow for quicker booting of routers in your GNS3 topologies. This is recommended for a better user experience. Click 'Yes' to decompress the image:
The directory where the decompressed image is stored is displayed. Click 'Next' to continue the setup:
The Name and platform window displays. Confirm the Platform selection, and configure the router Name. Click 'Next' :
A Default RAM setting is displayed. It is important that you check your Router's minimum memory requirements using the Cisco website. Click the 'Check for minimum and maximum RAM requirement' option:
The Cisco Feature Navigator is opened in your default web browser. Select Image Name and enter the name of the image you are using:
Click Search for Image(s):
The minimum DRAM requirements for the IOS are displayed. Note the value for your IOS image:
Set the Default RAM value to the value recommended by the Cisco Feature Navigator (yours may be different to the screenshot) and click 'Next':
Select your preferred Network adapters. This is device dependant.
In this example both Ethernet Serial interfaces will be added to the router. Once selected, click 'Next':
The c3725 IOS images will have the GT96100-FE dual Fast Ethernet adapter installed in slot 0 by default, and you can add extra adapters in slots 1 and 2. The types of adapters, and how many slots you are allowed to add will depend on the IOS image in use.
Once you have configured the network adapters, click 'Next' to add WIC adapters (again, this is IOS image dependent):
When you have added WIC adapters (if available), click 'Next >'
It is important for optimum GNS3 performance that an Idle-PC value be selected. Occasionally, some images will already display an Idle-PC value:
If a green Idle-PC value is NOT shown then click the 'Idle-PC finder' button to find an Idle-PC value:
If you selected the 'Idle-PC finder' button (only necessary if no value was detected automatically), GNS3 will calculate a value:
(note, this may take a few moments, depending on the speed of your PC) An Idle-PC value is displayed. Click 'OK' to complete:
If no Idle-PC value is displayed, try clicking the Idle-PC finder button again. You may also need to reboot your computer and try again is no value is found. It’s incredibly important to have an idle-pc value when using supported IOS images. Without this value, DynaMIPS can’t prevent an instance of an IOS image from consuming 100% of a CPU core or hardware thread (in the case of CPUs capable of hyperthreading).
Click 'Finish' to complete the GNS3 Setup Wizard:
In this instance, the IDLE PC value was already specified, according to the value listed in this page, so you can click 'Finish', instead of going through the IDLE-PC finder process.
The Preferences window displays showing the settings you have configured through the Setup Wizard. Click 'OK' to complete the process:
(notice that the name of your PC will be listed next to ‘Server’ in the shown settings. That is further indication that this router will be run via the local computer, as opposed to the GNS3 VM)
The New Project Window displays. Give your new Project a Name and click 'OK':
The GNS3 workspace displays:
Congratulations! You are now ready to create your first GNS3 topologies. Click here to create a basic GNS3 topology
Mastering GNS3
Unlike something like Packet Tracer which emulates Cisco devices and provides common commands that a CCNA candidate might need, GNS3 is a network simulator that runs actual Cisco IOS so you have access to the full command line and features.It also allows for nodes to have external connectivity so you can connect your routers to connect to the internet or your local servers.
Using GNS3 you can effectively study from the CCNA level to the CCIE level across several tracks. It also allows you to throw other vendors into the mix through VirtualBox or VMware Workstation integration.
Pros
- It is free
- It is fairly flexible
- Multi-Vendor friendly
- Relatively simple
- Self contained, you can run GNS3 directly on your computer.
- You can add and remove links on the fly.
Cons
- You need to get your hands on Cisco IOS or IOU images.
- You can occasionally experience weird behavior due in IOS if you are doing advanced tasks. Also there is the odd bug and such with the solution.
- Native switching is very poor though IOU provides a switching experience that is closer to VIRL.
Note: A word about IOU, IOU is a leaked internal tool that Cisco uses to simulate network topologies, the CCIE lab is also run on a variant of IOU. However Cisco doesn’t condone by the public so while I will likely use IOU from time to time in this workbook I won’t provide any pointers on how to set it up or get its images. Likewise your on your own when it comes to getting your hands on IOS images.
Installation
Let’s look into installing GNS3, it supports Windows, Linux, and Mac so pick what makes sense for you. I’ll be doing the Windows installation, the Mac version isn’t terribly different aside from the actual setup screens, Linux is a bit more involved but you are probably expecting that to be the case if your a Linux user
- Download GNS3 and also the GNS3 VM image.
2. Now we will go through the fairly boring install, basically keep clicking next.
3. When you get the components you can choose what else you want installed, you will likely want to keep everything checked unless you already have Wireshark etc installed. If your system happens to have WinPCAP 4.1.3 already installed I recommend unchecking it to save some time.
4. GNS3 also offers a free version of Solarwind’s Standard Toolset, I like the tool but already have it so I’ll say no.
Now we will turn our attention to the GNS3 VM, this is an optional component but I prefer working with the VM for a number of reasons. If you choose not to install it for whatever reason then you will pick the “Local Server” option for anything we do here on out.
I will also be using VMware Workstation for the virtualization solution, if you happen to use VirtualBox then the steps will be similar though you may have more troubleshooting ahead of you.
- Unzip the download and import the OVA file by either double checking it or by opening VMware Workstation and going File -> Open
2. GNS3 looks for a VM named “GNS3 VM” by default and it isn’t really worth the trouble of changing that, though you can call it whatever you want then click the “Import” button.
3. Once that is done right click the VM and go to “Settings”
4. Make sure the networking is setup correctly for your environment. In my case VMnet2 is the connection I use. The other interface is fine for now.
5. Start the VM and once it boots have a look at the networking section.
6. By default the VM will use DHCP but if you want to use static, comment out the DHCP line, uncomment out the static lines and change the info to match your network. Press Ctrl + X to save and exit. The VM will reboot after.
.
It is finally time to actually open GNS3! When you do for the first time you’ll get this setup wizard asking if you are using the VM or just local server (boo local server! Boo!)
- Select Local GNS3 VM and press next.
2. Select VMware and make sure it finds your GNS3 VM.
3. Adjust the amount of ram etc that the VM can use, generally the more the merrier.
When you click Next GNS3 will try to start the VM and connect to it.
4. Now we need to add IOS images for GNS3 to use. Make sure the “Add an IOS router” checkbox is checked. We’ll look at the other options as we need them.
5. We will be running everything off of the GNS3 VM.
6. When you add an IOS image GNS3 will attempt to decompress the image for better performance, it is a good idea to do so. Once that is done it will upload the IOS image to the server.
7. On this screen you can name the image and tweak some of the platform settings if the image allows it. I typically prefer the c7200-advipservicesk9-mz.152-4.M9 image since it supports most of the things I want but you can experiment with other images.
8. GNS3 will automatically select how much ram it thinks your image will need, you can click the link on the page to bring up Cisco’s Feature Navigator to lookup your images requirements.
9. On this page we tell GNS3 what interfaces the router will have be default.
I typically set the first few slots as dual ethernet ports and the last slot as serial in case I want to do some PPP or something.
9. On this page GNS3 will try to find the ideal idle-pc valve for your image. Idle-pc greatly reduces the CPU it takes to run a virtual router so it is highly recommended to set this value. If you are running GNS3 locally you will find GNS3 maxes out your CPU until you find a working idle-pc value, then it typically drops to around 20%
The GNS3 User Interface
First things first lets see what all the various buttons on the top of the program do. We’ll talk about what the features mean as we go.
On the left hand side of the screen we see all the various nodes we can use.
Routers – This has all the routers that GNS3 is configured to use, our C7200 is in the list.
Switches – Since GNS3 doesn’t directly support switching this section has IOU switches GNS3 is configured to use, Router images that are configured with switch moduels, and logical switches that GNS3 provides these include:
- Ethernet Hub – a logical hub that just a real hub doesn’t offer any configuration aside from how many ports it supports.
- Ethernet Switch – a logical switch that supports basic vlans and trunking.
- Frame-Relay Switch – a logical FR switch that can be configured, this will be mostly ignored by me since I’m focusing on the new CCNA.
Hosts – This section provides external connectivity via the Cloud node as well as either VPCS PCs for the topology to use or VMware Workstation / VirtualBox VMs.
Firewalls – This section would have any ASAs that are configured by GNS3, I’ll probably skip this section since it doesn’t quite apply to us.
All Nodes – This section just displays everything GNS3 knows about.
Connections – This button lets you add links between nodes.
We don’t need to mess around with the preferences all that much however you may want to change the default SSH program that GNS3 uses for consoling into the devices. By default it uses SuperPutty but I since I prefer SecureCRT I’ll change it by going Edit -> Preferences -> General -> Console Applications and editing the console command to match my screenshot.
Alright lets start making a topology!
When you first open GNS3 it will ask you to either make a new project or open a new one. You can also just click cancel but it does cause you some mild headaches if you want to use all the features in your session so it is better to just make a new project.
Now we are in GNS3, click the router section and then click the router node we created. Once that is selected click on the center canvas to add a router into the topology. We aren’t getting fancy yet so lets stick with two routers for now. GNS3 will automatically name the routers R1 and R2 respectively, it will simply prefix R to the number of routers in the topology.
Now click the connections button and click on R1, you will see all the available interfaces on the node that we defined when we added the router image. Select the first interface then click the second router, it will also display the list of available interfaces, click the first interface again.
We have now connected R1’s F0/0 interface to R2’s F0/0 interface. Cool!
Next we will add a logical switch into the mix, go to the switch section and select Ethernet Switch then click on the screen. GNS3 is going to ask you if you want the switch to be local or in the VM. Pick the VM since it is a bit cleaner to keep everything together.
Then we’ll click our Add a link button and click on R1. Notice that FastEthernet0/0 shows it is already connected so we will select F1/0 instead.
Then we will connect R1 to SW1’s port 1.
Finally we will connect SW1 port 2 to R2 F1/0.
If we want to customize the logical switch we can right click it and select Configure.
From here we can assign vlans to ports or create trunk ports.
If we wanted to customize one of the router nodes we could select the router and press configure. The take away is that Configure is contextual.
The most common thing to edit on a router is adjusting the slots. You can also change the hostname of the router under general or by right clicking the node and selecting Change Hostname
Drawings
We can GNS3’s drawing tools to add some logic (or kitties) to the topology, it is no Visio but it is flexible enough to create scenarios or add logical information like showing routing domains.
Working with Devices
At this point we can start the routers (if you haven’t already) and connect to them by either pressing the Console to All devices button or selecting the devices you want, right clicking and selecting Console. GNS3 will add each new device as a tab in your choosen SSH program.
In modern GNS3 whenever you save your config in the devices, the changes are preserved in the project so you can stop the project and continue later on if need be.
You can choose to import or export configurations by either right clicking nodes and selecting the config option you want.
Or you can do it for all devices by selecting Import/Export device configs from the File menu. This is useful for quickly loading configs for a workbook (like this one perhaps!)
Packet Captures
GNS3 allows for easy packet captures, simply right click the link you want to capture and click Start Capture.
GNS3 will then ask you what end of the link you want to capture.
Once that is done Wireshark will open in live capture mode, all traffic across the link will be shown! When you are done with the capture you can stop it by right clicking and picking Stop Capture.
Response Analyzer
GNS3 is also bundled with Solarwind’s Response Analyzer which is a simple tool for keeping track of connections and their stats. Once a capture is started, you can right click the link for a second time and choose Analyze Capture then pick the link.
Alternately you can save the wireshark file and open it within the Response Analyzer.
Remote Servers
Running GNS3 locally is great but there are some cases where you may want to run it remotely. Some reasons might include you want to install the GNS3 VM on a more powerful ESX server or you want to do a large topology so you want to load balance between a few GNS servers.
Fortunately it is pretty easy to add a remote server, go to Edit -> Preferences -> Server -> Remote Servers and enter in your server information. HTTP is typically fine and your default login for a GNS3 VM is gns3/gns3, if you are connecting a local server you will need to use credentials that let you connect to that computer. When you are done press Add.
Now we have a remote server, move down to Dynamips -> IOS routers then click Add.
In the new image screen (we saw this from the beginning) we will pick Run the IOS on a remote computer option and make sure our remote server is shown on the bottom. If you have multiple remote servers you can choose to load balance between them.
Then we can either pick an existing image running on the remote server or upload a new one. One caveat is that GNS3 can’t remote start a VM so the GNS3 VM will need to be always running.
Hosts
GNS3 also includes the Virtual PC Simulator node which is a simple lightweight “PC” that lets do basic testing in your environment. Lets test this out by adding a VPCS node to the topology and connecting it to our switch.
Lets test this out by setting up HSRP on the router’s F1/0 interface.
The VPCS node has a simple CLI that lets you setup an IP address and do a variety of diag tests like pings.
To see what kind of options we have for setting an ip we’ll just type ip all by its self.
Finally we’ll set the ip address to be 10.0.123.100
Now we should be able to ping our router’s VIP.
We can also use the host node to make our GNS3 VM or local server reachable to the topology. Alternately we can add a VM found in VMware Workstation or VirtualBox into the mix by selecting the virtual machine in Preferences under VirtualBox VMs or VMware VMs.
Snapshots
One advantage that running a Local Server has over the VM is that you can use the snapshot feature to “go back” to an earlier topology. This can be handy when say working through a workbook where you are using a standard topology for most of the section but then you get to a single lab where you need to change a bunch of interfaces around or add some nodes. With Snapshots you can simply save where you were and go back to it later.
To take a snapshot, stop the devices if they are running and then press the Manage Snapshots button. Click create and enter a name for the snapshot.
Once it is done we will see the snapshot and the time it was created. Now our topology is saved which is a good thing because it would take us weeks to remake it!
Now we will change our topology a bit.
Next we will test this out by going back into Snapshot Manager and press the restore button.
It will give us a warning and then it will restore our original topology.
Cloud Connectivity
We’ll close this up by talking about providing external connectivity, this is achieved by using the cloud node, once you add it to the topology you have to configure it to suit your setup. Most of the time using the Generic Ethernet section is all you need for this work, add your VMs second interface and click ok. You may need to adjust your VMs networking for the second nic in VMware Workstation if you didn’t do it earlier.
Next we simply connect the cloud node to a router. You can only connect a single cloud node to a single device so you will need to create multiple clouds if you want a bunch of external connectivity.
Now on the router if I give the F2/0 interface a LAN IP on my network and enable OSPF it peers with my lab routers and switches!
Idle pc gns3 что это
Firstly let me say thanks to Jeremy Grossmann (principal programmer for GNS3) for helping me finally get my head around this concept. I have to admit that I’d I had only a vague idea of what was happening when I wrote this post on the GNS3 forum, but recently I decided I had to nail it.
In a nutshell:
Without an Idle-PC set, dynamips attempts to emulate instructions one at a time as fast as it can, consuming up to 100% of the available CPU.
The Idle-PC is a guess at where the Program Counter might be pointing to an idle-loop in the emulated router.
When emulator has visits this PC value Idle-Max times, it suspends itself for Idle-Sleep ms to allow other processes to get on their tasks.
Details
To understand the dynamips/GNS3 Idle-PC concept, you have to start by looking at the way software operates.
A normal piece of software generally has one or more places in the code where the program just sits in an “idle” loop – say waiting for a key press. Or a message to arrive. Or for a timer to expire to remind it to send a message.
However dynamips is a different kind of program. It is an emulator. It takes a binary image of MIPS machine code and interprets each instruction one at a time and then executes that instruction on the host computer. The basic logic is something like this:
So there are no idle states – dynamips just screams through those instructions one at a time around and around – except that there will be many, many places where the instruction that is executed is one that changes the program counter, causing dynamips to extract the instructions in a non-linear sequence.
And some of those instructions will be be in little groups where the emulated router is sitting in an idle state – as in waiting for a packet to arrive or a key to be pressed at the console. The problem is, dynamips has no idea whether the current Program Counter (PC) is pointing to an instruction that is doing something important, or one that is just part of the few instructions that get repeated over and over in an idle loop.
Now if dynamips could somehow know that when the Program Counter (PC) was pointing to a certain pice of code that was just an idle loop, it could suspend itself for a while, so the logic would change to:
But dynamips has no way of knowing “IF the new PC is pointing to an idle loop” – because dynamips cannot predict future instructions nor understand them. This makes it impossible to optimise the executed code like compilers do or to know if the instructions are worth being executed.
So we make some guesses at when the Program Counter MIGHT be executing an idle loop. We call this value the Idle-PC value.
If we guess at a place where the emulated router spends a lot of idle time, then the host computer gets lots of chances to get on with other stuff. If we guess a PC (remember PC=Program Counter) where the code is only executed rarely, then the host computer will spend 100% of its CPU executing the dynamips simple loop.
Since every Cisco router image has a different set of instructions, these idle lops will be in different places on different images. But once a good Idle-PC has been found for one image, it should be good for all emulations of that image – no matter whether you are running your dynamips on a Windows computer, and OS X Macintosh, a Linux box or an iPad :J
The only other issue then, is how long and low often should dynamips sleep for when it has found the PC for the idle loop? This is where the Idle-Max and Idle-Sleep values found under the Advanced settings of the GNS3 IOS images and hypervisors dialogue come in. (Note: This feature was added to GNS3 in version 0.8.4)
Dynamips doesn’t go to sleep EVERY time the PC hits the Idle-PC. It waits until it has hit the Idle-PC Idle-Max times before sleeping for Idle-Sleep ms. That way the router still gets a chance to do the things it needs to do between visits to the Idle-PC value. If you adjust the Idle-Max too low or the Idle-Sleep too high, your emulated routers will slow to a crawl, they will loose connections with their neighbours and bad things will happen. However some folk have had good success at playing with these numbers.
To summarise:
Without an Idle-PC set, dynamips attempts to emulate instructions one at a time as fast as it can, consuming up to 100% of the available CPU.
The Idle-PC is a guess at where the Program Counter might be pointing to an idle-loop in the emulated router.
When emulator has visits this PC value Idle-Max times, it suspends itself for Idle-Sleep ms to allow other processes to get on their tasks.
Remember, if you found this post helpful, you can make it easier for others to find by giving it a good rating, or by clicking on one of the sharing options.
Сети для самых маленьких. Микровыпуск №1. Переход на GNS3
Мы немножко нарушим хронологию цикла Сети для самых маленьких.
Компания ЛифтМиАП разрастается, покупая новые филиалы по всей стране. Поэтому следующая наша статья будет посвящена технологиям VPN и подключению удалённых офисов к центральному. Будут обсуждаться такие темы, как GRE, IPSec и DMVN. Тут Packet Tracer уже едва ли может нам чем-то помочь.
Пришло время для больших игр и перехода на профессиональное ПО для симулирования сети. Да и темы, положа руку на сердце, уже не для самых маленьких.
На выбор в сегодняшнем меню:
- GNS3 — Graphical Network Simulator
- IOU — IOS on UNIX
Под катом аргументы за и против и частичный перенос топологию из РТ в GNS, а сначала традиционное видео, на этот раз умеренной длины.
GNS или IOU? IOU или GNS? Начнём с IOU, потому что его мы использовать не будем.
IOS On UNIX
Как видно из названия — ставится поверх UNIX. Раньше это был только Solaris, теперь же поддерживается и Linux.
Самые существенные его плюсы:
1) Практически полноценная поддержка как L3, так и L2. Этот эмулятор используется при сдаче лабораторных экзаменов CCIE.
2) Низкие требования к ресурсам ПК. Точнее к CPU. Памяти тоже надо немало.
3) Нет ограничений по платам и интерфейсам. В настройках вы просто указываете сколько и чего вы хотите.
Минусы:
1) Самое главное — это проприетарный софт, который официально не распространяется вообще никак. В торрентах существуют образы L2IOU, L3IOU, но это незаконно.
Вообще ходит легенда, что на сайте cisco одно время было написано:
Это основная причина, по которой мы отказались от идеи использования IOU в нашем цикле.
2) Установка и настройка IOU не отличается простотой. Нужно обладать недюжим спокойствием и кое-каким опытом работы в никсах, чтобы разобраться с топологиями, файлами настройки и сохранением конфигурации устройств.
Тоже немаловажная причина — нам бы с меньшими жертвами осуществить переход и не отпугнуть “самых маленьких”.
3) Нет графического интерфейса.
В общем это годная утилита для беспринципных тру ИТшников. Если вам нужна лаба из 20+ устройств или надо поработать с QinQ, Rapid PVST (и прочие L2-технологии) или хочется всерьёз заняться Tshoot, то это для вас.
Graphical Network Simulator
Наш выбор. Имеет два серьёзных недостатка:
— Сильно требователен к CPU и памяти. 10 маршрутизаторов уже всерьёз нагрузят ПК. Использование процессора можно снизить с помощью механизма Idle PC. Без этого и 3-4 с трудом бы, пожалуй, пошли.
— Очень слабо поддерживает функции L2. Есть только подобие коммутаторов, на которых можно максимум настроить Access/Trunk порты и свичовые платы для маршрутизаторов, L2-функционал которых также очень ограничен.
Необходимо ещё где-то раздобыть образы IOS. GNS — это практически виртуальный маршрутизатор и для запуска ему также необходимо ПО, которым и является IOS.
Взять его можно с сайта cisco, если у вас там есть аккаунт с необходимыми правами, скачать с имеющегося у вас оборудования или другой всем известный способ.
Зато при этом GNS имеет графический интерфейс (технически это и есть GUI для Dynamips), что сильно облегчает создание виртуальных лабораторий.
Компьютер можно подключить в реальную сеть в качестве виртуального маршрутизатора.
Установка и подготовка к работе
Скачать можно тут. Для Ubuntu, Debian GNS доступен из репозитария.
apt-get install gns3
После установки выполняем начальную настройку.
Полагаем, что образы у вас уже есть. Добавим их:
Автоматически определяется модель маршрутизатора.
Обратите внимание на поле IDLE PC. Пока не трогаем.
Save.
При создании нового проекта вам предлагается ввести название и параметры.
Самое главное тут не забудьте поставить галку «Save nvram and other disk files», иначе после перезапуска приложения у вас не сохранится конфигурация.
Перетаскиваем маршрутизатор на рабочую площадку. Естественно, берём ту модель, для которой есть образ. Ошибок быть не должно.
Жмакаем сверху на кнопку . Обратите внимание на то, как возросла нагрузка на CPU:
. Теперь волнение нужно успокоить. Для этого выбираем в контекстном меню Idle PC.
Именно этот механизм позволяет оптимизировать использование ресурсов процессора.
ПК вычисляет несколько значений и предлагает вам целый их список. Рекомендуется выбирать значения со знаком *. Как только они применяются, загрузка CPU падает
Если вдруг не получилось, итерируем до тех пор, пока не достигнем желаемого.
Теперь самое удачное значение перепишите на листочек, откройте окно управления образами Edit->IOS Image and hyervisors и заполняете то самое поле IDLE PC. Теперь при следующем запуске после загрузки IOS GNS не должен отожрать всё процессорное время.
Всё готово для подключения.
У GNS есть стандартные средства для этого:
По умолчанию он использует приложение xTerm, которое, наверняка, есть почти в любом дистрибутиве.
Признаться, у меня почему-то он не работает — нельзя набирать символы. В настройках терминальных программ можно выбрать другое приложение, например, Konsole — оно у меня заработало.
Для оболочки Gnome (Unity) при настройке терминала можно выбрать родной терминал, несмотря на то, что его нет в списке по-умолчанию. Достаточно вставить следующую строчку в поле Preconfigurated terminal commands:
gnome-terminal -t %d -e ‘telnet %h %p’ >/dev/null 2>&1 &
Но на самом деле вы можете пользоваться любым другим терминальным приложением, к которому привыкли. Более того, вы можете подключаться даже с другого компьютера в сети, потому что выполняется это командой:
telnet a.b.c.d 2000
Что такое telnet — понятно, a.b.c.d — адрес компьютера (если вы подключаетесь с этого же ПК, то адрес 127.0.0.1), 2000 — номер TCP порта, выделенного для этого устройства (как правило начинается с 2000 для таких программ). У каждого маршрутизатора будет свой.
Номер порта можно посмотреть так:
Перенос конфигурации из РТ в GNS
Тут кроется дьявол. В GNS у нас максимум 3 интерфейса: FE0/0, Fe0/1 и можно добавить ещё плату с FE1/0, а в лабе на РТ мы иногда используем FE1/1. Поэтому нельзя просто скопировать и вставить — местами придётся переработать конфигурацию.
Схема, которую мы будем воспроизводить:
Мы взяли только Сибирское кольцо, чтобы показать, как это делается, и не загружать схему другими филиалами.
Добавляем маршрутизаторы. Будем работать, например, с 2691-ми.
Названия устройств ограничены в используемых символах, поэтому мы добавим им описания:
Также добавляем коммутаторы: один для «Балаган Телеком», второй для «Филькин сертификат».
Прежде чем, запускать, добавим в МСК плату.
В списке только одна плата с FE портами. Мы вполне могли бы добавить платы с последовательными портами, но зачем?
Настроим так называемые коммутаторы. Для этого доступен только GUI.
Удаляем все порты.
Добавляем несколько новых, но в качестве номера влана указываете 0, а тип порта dot1q. Это означает транковый порт, который пропускает все вланы.
То же и со вторым.
Перед запуском маршрутизаторов, нужно создать все линки хотя бы примерно согласно старой схеме.
Выбрать нужно Manual, тогда можно указывать конкретные порты.
А можно вообще в настройках указать, чтобы всегда выбиралось только Manual.
Если до этого не подбирали значение Idle PС для этого образа, лучше запустить одно устройство и сделать это.
Запускаем остальные. Можно можно по очереди, можно все разом, если поставили паузу между запусками в настройках.
Если у вас старый компьютер, в этот момент он может серьёзно повиснуть. Нужно будет подождать.
Конфигурацию для маршрутизатора в Москве можно просто скопировать — с интерфейсами всё в порядке.
- Будьте аккуратнее при копировании команды
- После вставки конфигурации интерфейсы остаются в состоянии shutdown.
Neighbor ID Pri State Dead Time Address Interface
172.16.255.112 1 FULL/DR 00:00:36 172.16.2.197 FastEthernet1/0.911
172.16.255.80 1 FULL/BDR 00:00:34 172.16.2.130 FastEthernet0/1.8
msk-arbat-gw1#sh ip route
Codes: C — connected, S — static, R — RIP, M — mobile, B — BGP
D — EIGRP, EX — EIGRP external, O — OSPF, IA — OSPF inter area
N1 — OSPF NSSA external type 1, N2 — OSPF NSSA external type 2
E1 — OSPF external type 1, E2 — OSPF external type 2
i — IS-IS, su — IS-IS summary, L1 — IS-IS level-1, L2 — IS-IS level-2
ia — IS-IS inter area, * — candidate default, U — per-user static route
o — ODR, P — periodic downloaded static route
Gateway of last resort is 198.51.100.1 to network 0.0.0.0
172.16.0.0/16 is variably subnetted, 17 subnets, 3 masks
O 172.16.255.80/32
[110/11] via 172.16.2.130, 01:32:53, FastEthernet0/1.8
O 172.16.2.160/30 [110/20] via 172.16.2.130, 01:32:53, FastEthernet0/1.8
O 172.16.255.96/32
[110/12] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
O 172.16.255.112/32
[110/2] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
C 172.16.2.128/30 is directly connected, FastEthernet0/1.8
C 172.16.255.1/32 is directly connected, Loopback0
C 172.16.2.196/30 is directly connected, FastEthernet1/0.911
O 172.16.2.192/30
[110/11] via 172.16.2.197, 01:32:53, FastEthernet1/0.911
C 172.16.2.32/30 is directly connected, FastEthernet0/1.7
C 172.16.2.16/30 is directly connected, FastEthernet0/1.5
C 172.16.4.0/24 is directly connected, FastEthernet0/0.102
C 172.16.5.0/24 is directly connected, FastEthernet0/0.103
C 172.16.6.0/24 is directly connected, FastEthernet0/0.104
C 172.16.0.0/24 is directly connected, FastEthernet0/0.3
C 172.16.1.0/24 is directly connected, FastEthernet0/0.2
C 172.16.2.0/30 is directly connected, FastEthernet0/1.4
C 172.16.3.0/24 is directly connected, FastEthernet0/0.101
198.51.100.0/28 is subnetted, 1 subnets
C 198.51.100.0 is directly connected, FastEthernet0/1.6
S* 0.0.0.0/0 [1/0] via 198.51.100.1
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.197 860 msec 64 msec 4 msec
2 172.16.2.193 412 msec 56 msec *
msk-arbat-gw1(config)#int fa1/0.911
msk-arbat-gw1(config-subif)#sh
*Mar 1 00:57:43.995: %OSPF-5-ADJCHG: Process 1, Nbr 172.16.255.112 on FastEthernet1/0.911 from FULL to DOWN, Neighbor Down: Interface down or detached
msk-arbat-gw1#
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.130 4 msec 12 msec 12 msec
2 172.16.2.162 28 msec 20 msec *
msk-arbat-gw1(config)#int fa1/0.911
msk-arbat-gw1(config-subif)#no sh
msk-arbat-gw1(config-subif)#
*Mar 1 00:59:21.179: %OSPF-5-ADJCHG: Process 1, Nbr 172.16.255.112 on FastEthernet1/0.911 from LOADING to FULL, Loadingping 172.16.255.96
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 172.16.255.96, timeout is 2 seconds:
.
Success rate is 100 percent (5/5), round-trip min/avg/max = 12/28/60 ms
msk-arbat-gw1#tracer 172.16.255.96
Type escape sequence to abort.
Tracing the route to 172.16.255.96
1 172.16.2.197 8 msec 16 msec 12 msec
2 172.16.2.193 12 msec 8 msec *
После возвращения интерфейса в исходное, маршрут тоже переключается обратно на Владивосток.
С помощью GNS можно легко снимать дампы трафика. Для этого достаточно Wireshark. Но под линуксом у меня почему-то не получилось запустить.
Для этого нужно сделать всего лишь следующее:
1) кликнуть правой кнопкой на линк между двумя устройствами
2) Выбрать capture в контекстном меню. Если после этого запустился вайршарк, его можно закрыть — в реальном времени он не собирает данные. Чтобы он не запускался в будущем, можно убрать галочку в настройках:
3) Выполнить запланированные действия.
4) Из контекстного меню линка выберите Start Wireshark.
В открывшемся окне будут все пакеты, которые вы хотели отловить.
Существуют и другие сетевые симуляторы, которые не охвачены данной статьёй.
Например, Bosson, который просит вменяемых денег за свой продукт для подготовки к сдаче CCNA/CCNP. К сожалению, не тестировал его, не могу сказать ничего о его качестве.
В русскоязычном сегменте совершенно незаслуженно обделён вниманием OpenSource проект NS3. Очень мощная утилита без привязки к конкретным вендорам.
Совершенная иная парадигма создания топологий и настройки, напоминающая скорее язык программирования.
Продукт хорошо документирован, но, видимо, в силу своей сложности всё же не сыскал большой известности в сети.
NS3 используется преимущественно в зарубежных ВУЗах, но даже у нас на его основе проворачивали интересные проекты.
Кроме того, наверняка, у каждого вендора есть какой-то внутренний симулятор их оборудования.
Точно могу сказать за Huawei, что у них имеется два мощных приложения:
WVRP — внутренний продукт, требует лицензий и работает только в корпоративной сети. Аналог GNS3, но с большими возможностями и меньшим потреблением ресурсов.
eNSP — публичный симулятор оборудования Huawei. Имеет урезанный функционал по сравнению с WVRP. Скорее похож на Packet Tracer по простоте работы, но с гораздо большими возможностями.
Есть видеоинструкция.
Бесплатен, свободен для загрузки (достаточно завести аккаунт на сайте). Скорее всего, на нём мы и будем в будущем отрабатывать Multicast — в eNSP это можно сделать довольно наглядно.
Я находил в сети симулятор Juniper, но не знаю, насколько он функционален и является ли официальным.
Полезные ссылки по теме
Данную статью вы также можете читать на нашем сайте: linkmeup.ru/blog/36.html.
Возможно, вам будет удобнее воспользоваться ЖЖ
Друзья и коллеги, наша команда ведущих подкаста остро нуждается в женском голосе, который скрасит мужские басы в эфире.