Что такое cisco ios cli

ИТ База знаний

Полезно

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Навигация

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Структура команд Cisco IOS

Как и куда печатать?

Всем привет! Мы продолжаем знакомиться с операционной системой Cisco IOS. Недавно в статьях мы уже рассмотрели операционную систему Cisco IOSи ее режимы. В этой статье мы рассмотрим основную структуру команд Cisco IOS.

Базовый курс по Asterisk

Мы собрали концентрат всех must have знаний в одном месте, которые позволят тебе сделать шаг вперед на пути к экспертному владению Asterisk

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Структура команд

Команда представляет собой начальное слово или слова, введенные в командной строке. Команды не чувствительны к регистру. После каждой введенной команды, включая любые ключевые слова и аргументы, нужно нажать Enter, чтобы отправить команду командному интерпретатору.

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Ключевые слова описывают конкретные параметры командного интерпретатора. Например, команда show используется для отображения информации об устройстве. Эта команда имеет различные ключевые слова, которые должны использоваться для определения того, какой конкретный вывод должен отображаться.

За командой show следует ключевое слово running-config, которое указывает, что текущая конфигурация должна отображаться в качестве вывода.

Контекстно-зависимая справка

Контекстно-зависимая справка содержит список команд и аргументов, связанных с этими командами в контексте текущего режима. Чтобы получить доступ к контекстно-зависимой справке, нужно ввести знак вопроса “?” в любом меню. Результат появится сразу, даже без нажатия клавиши Enter.

И еще один тип контекстно-зависимой справки используется для определения того, какие параметры, ключевые слова или аргументы сопоставляются с определенной командой. При вводе команды введите пробел, за которым следует символ “?” определить, что может или должно быть введено дальше.

Проверка синтаксиса команд

Когда команда отправляется нажатием клавиши Enter, интерпретатор командной строки анализирует команду слева направо, чтобы определить, какое действие запрашивается. Обычно IOS обеспечивает только отрицательную обратную связь, если что-то было введено неверно. Если интерпретатор не может понять введенную команду, он предоставит информацию о том, что не так с командой.

Двойственная команда (Ambiguous command) – введено недостаточно символов для, чтобы система распознала команду.

Неполная команда (Incomplete command) – не все необходимые ключевые слова или аргументы были введены.

Неверная команда (Invalid input) – команда введена некорректно. Ошибка произошла в месте, на которое указывает маркер

Горячие клавиши и сочетания клавиш

В CLI IOS есть возможность использовать горячие клавиши и сочетания клавиш, которые облегчают использование системы. Рассмотрим наиболее полезные из них:

Рассмотрим их подробнее.

Клавиша Tab используется для завершения оставшейся части сокращенной команды и параметра, если аббревиатура содержит достаточно букв, чтобы отличаться от любых других доступных в данный момент команд или параметров. Когда для ввода уникальной команды или ключевого слова было введено достаточно символов, нужно нажать Tab, и CLI отобразит остальную часть команды или ключевого слова.

Повторное отображение строки обновит только что напечатанную строку. Например, IOS может отобразить сообщение в CLI во время набора команды пользователем. Ctrl-R можно использовать для обновления строки и избегать повторного ее ввода.

Выход из режима конфигурации выйдет из любого режима конфигурации и вернется в привилегированный режим EXEC. Поскольку IOS имеет иерархическую структуру, вместо того, чтобы выходить из каждого подрежима отдельно, можно использовать Ctrl-Z, привилегированный режим EXEC.

Стрелки вверх и вниз

При помощи стрелок можно отображать историю введенных команд. Cisco IOS выполняет буферизацию нескольких прошлых команд и символов, чтобы записи могли быть снова отображены. Буфер полезен для повторного ввода команд без повторного набора.

Эта последовательность прерывает любой выполняющийся процесс. Когда процесс IOS инициируется из CLI, например, ping или traceroute, команда работает до тех пор, пока не будет завершена или не будет прервана. Пока процесс выполняется, CLI не отвечает. Чтобы прервать вывод и взаимодействовать с CLI, нужно нажать Ctrl-Shift-6.

Прерывает ввод команды и выходит из режима конфигурации. Это может быть полезно после ввода команды, которая должна быть отменена.

Сокращенные команды или ключевые слова

Команды и ключевые слова могут быть сокращены до минимального количества символов, которые идентифицируют уникальный выбор. Например, команда configure может быть сокращена до conf, поскольку configure является единственной командой, которая начинается с conf. Аббревиатура con не будет работать, потому что более чем одна команда начинается с con. Ключевые слова также могут быть сокращены.

Продвинутый курс по Asterisk

Концентрат редких знаний, для внедрения Asterisk в крупных предприятиях. Все это мы собрали в одном курсе для тебя.

Источник

Introduction to Cisco IOS CLI (Command-Line Interface)

Most Cisco devices (including routers and switches) use a CLI (Command Line Interface) to configure the network device. The CLI is an interface, based on text. You type in configuration commands and use show commands to get the output from the router or switch. There are also GUIs (Graphical User Interface) for the routers, switches and firewalls but the majority of the work is done on the CLI.

This might sound dated but with so many commands that are available to use, the CLI is much easier to work with than any of the graphical interfaces. It’s also much easier to copy entire configurations from one device to another.

In this lesson, I’ll explain how to access the CLI and the basics of how Cisco IOS works.

Access to Cisco IOS CLI

Before we can enter any commands, we need access to the CLI. There are three options:

The console is a physical port on the switch that allows access to the CLI. We typically use this the first time we configure the switch. Telnet and SSH are both options for remote access.

Console Cabling

On the switch, you will find one or two physical connectors for the console. Take a look at the picture below:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

On the left side of this 2960 Catalyst switch, you see the light blue RJ45 port and a micro-USB port on the left of it. Older switches only have the RJ45 port, newer switches (and other devices) often have both options.

Even though it’s an RJ45 port, it’s not an Ethernet port. We use this connection to connect the switch to a serial port on your computer with the following cable:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

This cable is called a Cisco console cable and you will need a serial port on your computer. Modern computers or laptops don’t have these serial ports anymore so you might have to use a serial-to-USB cable like this one:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

This cable emulates a serial port and has a USB connection. Once you have connected your computer to the switch, we can start a terminal application to access the CLI.

Terminal Emulator

There are many terminal emulator applications. If you are new to this, the best one to start with is Putty. It’s free and allows you to connect using a serial connection, telnet and SSH. Once you have downloaded it, you will see the main screen:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Make sure you select the “Serial” option. The default speed is 9600 (baud rate). The COM port will depend on your computer, it might be COM1 but if you are unsure, check the device manager in Windows. Click on Start > Run and enter “devmgmt.msc”:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Here is the device manager:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Above you can see that on my computer, I have to use COM4. Change the COM port and click on Open to start the console:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Now is a good time to power on your switch or in case it is already powered on, pull the plug so it can reload.

First Boot

When the switch boots, you will see a lot of stuff on the console. First, it will initialize the flash memory:

Initializing the flash memory is required since it contains the IOS image (Operating System) of the switch. Its next step is to load the IOS image from the flash memory:

The IOS image is compressed so the switch uncompresses the image and loads it in RAM. You are then presented with some legal information and information about the switch:

This tells us the version of the IOS image. IOS is now up and running, it also initializes the flash memory:

IOS starts with a POST (Power on Self Test) for some of the switch components:

It then warns us about the cryptographic features:

You might be wondering what a switch has to do with cryptography. Depending on your IOS image, your switch is able to run SSH server. This allows encrypted remote access. Another feature that uses cryptography is SNMP version 3, this is used by network management software to read statistics from the switch. In certain countries, cryptography is forbidden or limited.

The final part of the boot process gives us some general information about the switch:

Above we can see the switch model, the interfaces it has, some serial numbers, etc. It ends with the following message:

Now it’s up to us to configure the switch.

Depending if your switch already has a configuration or not, you might see the following message:

If there is no configuration, the switch will ask you if you would like to follow a wizard called the initial configuration dialog. If you see this, type “no” to continue so that we can start with a blank configuration. We will configure the device ourselves.

User and Enable mode (Privileged Exec Mode)

Once the switch has booted and we have pressed the enter key, we end up in what we call the user mode or user EXEC mode. In this mode, we have permission to use some simple commands but we are restricted to configure anything or use some more advanced commands.

Right now, the command line will show you this:

The > symbol tells us that we are currently in user mode. To get full access to the switch, we have to enter privileged mode, also called enabled mode. Here is how to do this:

Above you can see that the > symbol changed to #. This tells us we are now in enabled mode, granting us full access to the switch. bliep…

The disable command lets you jump back to user mode.

Erasing the Switch Configuration

If you are using used hardware, it’s possible that the previous owner did not erase the configuration of the switch. To start with a clean slate, we’ll wipe the configuration of the switch before we continue. Here’s how to do this:

Type erase startup-config and the switch will ask you to remove all configuration files. Between the brackets, you see confirm. If you see anything between [] you only have to press enter. You don’t have to type “confirm”.

Switches also store VLAN (Virtual LAN) information in another file. What a VLAN is and what it does is something that we will cover in another lesson, for now, let’s just make sure it is deleted. Here’s how to do it:

Type delete flash:vlan.dat to delete the file. You only have to press enter to confirm what Cisco IOS tells us between the brackets. If you get an error that there is no such file, do not worry. It means someone else already deleted the VLAN information and you can continue.

Type reload and the switch will reboot:

Once the switch has reloaded, we can try something else…

Show commands

The show command is probably the most used command for Cisco IOS. We can use it to fetch any information from the switch. Let’s start with a simple example, let’s say we want to see some general information about the switch:

The show version command gives us a lot of information about the switch, including the model, IOS image, and more. What if we want to see what MAC addresses the switch has learned? There is another command for that:

The show mac address-table dynamic command tells us all MAC addresses that the switch has learned. In this example, it only learned one MAC address on interface Fa0/12 (FastEthernet port 12).

What if we want to see the entire configuration of the switch? There’s a show command for that:

The show running-config command gives us the entire active configuration of the switch. Even though we haven’t configured anything yet, there is a basic configuration.

In all these Cisco lessons, you will see a LOT of show commands that I use to explain things. There are also debug commands. These show commands only produce “static” information. If you want to see changes, you have to use the same show command a couple of times. Debug commands allow us to see things in real-time. You will see some examples of debug commands in other lessons.

Configuration

When you take a new switch out of the box, it will work right away with its default (empty) configuration. It will behave just like any other unmanaged switch, it will start learning MAC addresses and forwards Ethernet frames.

However, you probably want to make some changes to the configuration of your switch. Change its default hostname, perhaps add an IP address so you can manage it remotely, etc.

To do this, we have to use configuration mode. In this mode, we can make changes to the configuration of the switch. Here’s how you enter configuration mode:

First, you need to make sure you are in enable mode. Now you can use the following command:

With the configure terminal command, we enter configuration mode. Now we can make changes to the switch.

Let’s start with something simple, let’s change the name of our switch with the hostname command:

You can see this is applied immediately. Our switch is now called SW1.

The command above was executed in “global” configuration mode. When we want to make changes to interfaces or console settings, we have to dive into one of the configuration sub modes. Let me give you an example, let’s say we want to add a password to the console:

First, we use the line console 0 command to dive into the line configuration. You can recognize this because it shows (config-line). I used the password command to specify a password (cisco) and the login command to tell the switch to ask for this password. Next time you access the console, it will ask for this password.

If I want to get back to global configuration, I have to type exit or press CTRL+Z:

I’m now back in the global configuration mode.

Let me give you one more example, let’s say we want to make changes to one of our interfaces:

First, I use the interface command and specify the interface that I want to make changes to. You can see we are now in the interface sub-mode as it shows (config-if) to us.

I can now make some changes to this interface, let’s try a few commands:

Above you can see I added a description and changed the duplex/speed settings of this interface. If I want to get back, I can use the exit command or CTRL-Z:

The first time, it jumps back to global configuration mode. The second time I do it, we jump back to enable mode and exit the configuration mode:

Here is a picture to help you visualize the different modes and how to move from one to another:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Saving the configuration

We entered a couple of commands but once we pull the power plug, everything is gone…

Why? Everything we configure on our switch is applied to the running configuration. This configuration is only active in RAM, pull the plug and it’s gone.

If we want to save our configuration, we have to save it as the startup configuration which is saved in NVRAM. Next time we boot our switch, it will look for the startup configuration and use that.

Here’s how to copy our running configuration to the startup configuration:

Use the copy command to copy the running configuration to the startup configuration.

Here’s a simple illustration to help you visualize the two configuration files:

Что такое cisco ios cli. Смотреть фото Что такое cisco ios cli. Смотреть картинку Что такое cisco ios cli. Картинка про Что такое cisco ios cli. Фото Что такое cisco ios cli

Help Features

You have now seen the basics of Cisco IOS. We used some show commands and a few configuration commands. The CLI has some tricks up its sleeve to make your life easier. Let’s discuss these…

Question Mark

Not sure what the command was again or how to type it? The question mark is your friend. If you use it, it will tell you all possible commands:

The question mark works in user, enable and configuration mode so go ahead and try it everywhere. It also helps you finding out which commands are possible. For example:

If I type cl? then the CLI tells me there are two possible commands:

Let’s take a closer look at the clock command as it’s a great example to explain the question mark a bit more. If I want to set the time, what format should it be? It could be 18:00, 6PM, 6:00PM or anything else. the question mark will help us figure out what the command requires:

First, it tells us that we need to use clock set. Let’s try that:

Clock set tells us that time should be in hh:mm:ss format so let’s enter that:

Now it tell us that it needs a day and month. Let’s try the month first:

We still have to enter the day, let’s do that:

Finally, we have to enter the year. Let’s do this:

Now we only see which means that the clock command has everything it needs. Remove the question mark and hit enter:

The clock is now configured.

Abbreviation

There is no need to type the exact command for CLI to accept it. You can also shorten commands. For example, I just used copy running-config startup config but I don’t have to type the entire thing. This will also work:

After the copy command, there is only one parameter that starts with “run” which is running-config. The only parameter that starts with “st” is startup-config. Once you get more experience with the CLI and become familiar with the different commands, you will automatically use this more often.

Errors and incomplete commands

In a perfect world, we would remember everything and make no spelling errors. In real life, this happens all the time. Luckily for us, the CLI has something to help. Let’s try the clock command again:

The switch tells us that the command is incomplete. This is because I didn’t add a month or year, when this happens…use the question mark to figure out what the command requires.

What if I make a typing error?

The CLI complains but does show the ^ symbol to tell me where I made an error. When this happens, remove whatever you typed in above the ^ symbol and use the question mark:

This tells me that I should have typed November, not 11.

Keyboard Shortcuts

There are a couple of useful keyboard shortcuts that you can use for the CLI.

Cisco IOS keeps a history of previously entered commands. All you need to do is press the up and down arrow keys to browse through your previous commands.

With the left and right arrow keys, you can move the cursor one character in either direction. If you want to make some changes to a very long command that you are trying to enter, it might be a bit annoying to keep one of the arrow keys pressed. Instead, try the CTRL+A or CTRL+E combinations. This will make the cursor jump to the start or end of the line.

No idea how to spell a certain command? The TAB button will auto-complete commands for you. For example, try typing this:

And then hit the TAB button. The CLI will auto-complete it to:

This saves some typing and you don’t have to think about silly things like remembering if the command has a space or dash in between.

Do command

If you are in the configuration mode, you will face the following issue if you try a show command:

Why? The command is typed correctly but the problem here is that this is a command for the enable mode, not the configuration mode.

You could exit the configuration mode but instead, you can add do in front of the show command:

Output Modifiers

What if you want to get the output of a show command but you don’t have to see everything? For example, look at the following show command:

This produces quite some output. What if I only want to see the IOS version that this switch has? We can use some output modifiers:

At the end of your show command, add the | symbol. Let’s look at our options:

The two I personally use most often are begin and include. Let’s try both:

Include will only show me the line that have “IOS” in them.

Begin will start the output with the word you are looking for. For example, let’s say I am only interested in the interface configuration from the running configuration. Here’s how to do this:

Instead of seeing the entire running configuration, it will skip the first part of the output and starts with the interfaces instead.

Conclusion

You have now learned the basics of Cisco IOS and how to connect to the CLI. Here are some of the things we discussed:

I hope this lesson has been useful, the best thing to do now is to boot up a switch and try all of this by yourself.

Источник

Курс молодого бойца cisco: искусство владения консолью

Введение: многие начинающие настройщики сетевого железа боятся консоли (CLI, Command Line Interface) как огня. Ещё бы: ни тебе всплывающих подсказок по наведенному мышиному курсору, ни тебе красивых картинок, а лишь непонятные буквы на черном (зеленом, белом) фоне. Боязно…

Однако, консоль является мощнейшим инструментом, не овладев которым называть себя настройщком cisco нельзя.

При помощи консоли можно:
1. Задать начальную конфигурацию.
2. Восстановить потерянные пароли (для разных железок по-разному. Но поиском на сайте cisco.com легко найти процесс по ключевым словам “password-recovery (название железки)” )
3. Настроить нестандартные топологии
4. Включить скрытые возможности
5. Проверить правильность настроек командами show
6. Отладить процесс командами debug

Помните: при помощи консоли можно всё, при помощи GUI – не всё, а только то, что запрограммировали и разрешили.

Как же овладеть искусством быстрой настройки через консоль?

Безусловно, требуется много тренироваться 🙂 Однако, есть несколько хитростей, которые облегчат работу и могут пригодиться в реальной жизни для быстрой локализации и решения проблем или сдачи экзамена CCIE 🙂

Хитрость 1: Запомните горячие сочетания клавиш. Самые часто используемые ctrl+a (начало строки), ctrl+e (конец строки), ctrl+z (выход из режима настройки)

Хитрость 2: На маршрутизаторах и коммутаторах пользуйтесь командой do для вызова команд show из режима настройки.
Примеры: (config)# do show ip route
(config-if)# do show ip int f0/0
Это сильно экономит время, т.к. не приходится выходить из режима настройки и возвращаться обратно в него. Т.к. консольные команды древовидные, то беготня по режимам реально отнимает время и силы.

Важно: Есть тонкость: при использовании команды do не работает подсказка по вопросу, кнопка табуляции и проверка синтаксиса на ошибку. Поэтому, если Вы точно не знаете, какую команду show хотите ввести, всё-таки придётся выйти из режима настройки

Хитрость 3: Используйте выборку из конфига или вывода других команд просмотра. Для этого есть служебные команды после символа “|” (“grep”)
Примеры: sh run | include ip route
Sh ip route | include 192.168.0.0
Sh run | begin router ospf 1

Хитрость 4: Используйте блокнот или другой текстовый редактор, чтобы создавать шаблон конфига, а потом вливайте его копи-пастом в консоль. Перевод каретки циской распознаётся как ввод команды. Не забывайте после последней команды нажать кнопку ввод 🙂

Хитрость 5: Используйте стрелки «вверх» и «вниз» (или команды ctrl+p, ctrl+n) для вызова ранее введенных команд. Размер буфера команд настраивается.

Хитрость 6: Не забывайте, что разные команды возможно вводить из разных режимов: из режима непривилегированного пользователя можно мало и только посмотреть, из привилегированного – посмотреть, включить debug, из режима настройки – настроить параметры или перейти в подрежимы. Не забывайте, что знак «?» введенный без пробела, подскажет возможные продолжения команды, а знак «?», введенный через пробел – возможные дальнейшие ключевые слова

Хитрость 7: Учите команды и активно их сокращайте! Помните, что если сокращение однозначно, его циска распознает.
Пример (сравните):
Ip nat inside source list NAT interface GigabitEthernet0/0 overload
Ip nat in so l NAT int G0/0 o

Для ускорения обучению используйте кнопочку табуляции: если начало команды уже однозначно, циска продолжит команду автоматически.

Хитрость 8: Строчки из конфига (running или startup) являются командами. Можно подглядеть в конфиг и стереть неугодную команду, поставив перед ней ключевое слово no

В-общем, как и везде: упорство и труд всё перетрут!

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *