Как проверить ssh cisco
Настройка SSH
на Cisco
Router>enable — вход в режим Exec.
Router#configure terminal — вход в режим конфигурации.
Router(config)#hostname Branch — Настройка имени маршрутизатора.
Branch(config)#interface FastEthernet 0/0 — Вход в настройку физического интерфейса Fa 0/0.
Branch(config-if)#ip address 192.168.0.3 255.255.255.0 — Настройка IP адреса и маски сети на Fa0/0.
Branch(config-if)#no shutdown — Включение интерфейса.
Branch(config-if)#exit — Выход из режима настройки интерфейса.
Branch(config)#ip domain-name learnin.ru — Настройка имени домена (может быть любым, не привязано к AD)
Branch(config)#crypto key generate rsa — Генерация ключа для SSH. (Может потребоваться выбрать длину ключа)
Branch(config)#username learnin password cisco — Создание пользователя в локальной базе маршрутизатора
Branch(config)#interface line vty 0 15 — Вход в режим настройки терминальных линий.
Branch(config-line)#transport input ssh — Указание протокола SSH для подключения к линиям.
Branch(config-line)#login local — Указание использовать локальную базу (см. выше) для аутентификации пользователей по SSH.
Конфигурация Branch завершена. Теперь можно подключиться к маршрутизатору удаленно при помощи протокола SSH используя имя пользователя learnin и пароль cisco.
Если настройка произведена правильно, то вы можете подключиться к Branch протоколу SSH.
Это базовая настройка устройства, которая позволяет получить к нему доступ удаленно через сеть.
Протокол SSH является стандартным протоколом доступа к сетевым устройствам всевозможных производителей в бизнес среде ввиду своей защищенности.
Самый простой способ проверить работоспособность конфигурации, не используя дополнительное оборудование, — подключиться с устройства на свой IP адрес. Можно воспользоваться встроенным в Cisco IOS SSH клиентом:
Branch>enable
Branch#ssh -l learnin 192.168.0.3 — Запуск внутреннего клиента SSH, где learnin — имя пользователя заданное на этапе настройки, а 192.168.0.3 IP адрес устройства.
Также, можно проверить доступ по SSH к Branch с компьютера PC1, а также коммутатора SW1, для этого нужно настроить на этих устройствах IP адреса в той же сети, что и адрес маршрутизатора — попробуйте сами.
Configure SSH on Routers and Switches
The documentation set for this product strives to use bias-free language. For the purposes of this documentation set, bias-free is defined as language that does not imply discrimination based on age, disability, gender, racial identity, ethnic identity, sexual orientation, socioeconomic status, and intersectionality. Exceptions may be present in the documentation due to language that is hardcoded in the user interfaces of the product software, language used based on RFP documentation, or language that is used by a referenced third-party product. Learn more about how Cisco is using Inclusive Language.
Contents
Introduction
This document describes how to configure and debug Secure Shell (SSH) on Cisco routers or switches that run Cisco IOS ® Software.
Prerequisites
Requirements
The Cisco IOS image used must be a k9(crypto) image in order to support SSH. For example c3750e-universalk9-tar.122-35.SE5.tar is a k9 (crypto) image.
Components Used
The information in this document was created from the devices in a specific lab environment. All of the devices used in this document started with a cleared (default) configuration. If your network is live, ensure that you understand the potential impact of any command.
The information in this document is based on Cisco IOS 3600 Software (C3640-IK9S-M), Release 12.2(2)T1.
SSH was introduced into these Cisco IOS platforms and images:
-
SSH terminal-line access (also known as reverse-Telnet) was introduced in Cisco IOS platforms and images start in Cisco IOS Software Release 12.2.2.T.
SSH Version 2.0 (SSH v2) support was introduced in Cisco IOS platforms and images start in Cisco IOS Software Release 12.1(19)E.
Conventions
SSH v2 Network Diagram
Test Authentication
Authentication Test without SSH
First test the authentication without SSH to make sure that authentication works with the router Carter before you add SSH. Authentication can be with a local username and password or with an authentication, authorization, and accounting (AAA) server that runs TACACS+ or RADIUS. (Authentication through the line password is not possible with SSH.) This example shows local authentication, which lets you Telnet into the router with username «cisco» and password «cisco.»
Note: Throughout this document vty is used to indicate «Virtual Terminal Type».
Authentication Test with SSH
In order to test authentication with SSH, you have to add to the previous statements in order to enable SSH on Carter and test SSH from the PC and UNIX stations.
At this point, the show crypto key mypubkey rsa command must show the generated key. After you add the SSH configuration, test your ability to access the router from the PC and UNIX station.
Optional Configuration Sets
Prevent Non-SSH Connections
If you want to prevent non-SSH connections, add the transport input ssh command under the lines to limit the router to SSH connections only. Straight (non-ssh) Telnets are refused.
Test to ensure that non-SSH users cannot Telnet to the router «Carter».
Set Up an IOS Router or Switch as SSH Client
There are four steps required to enable SSH support on a Cisco IOS router:
1. Configure the hostname command.
2. Configure the DNS domain.
3. Generate the SSH key.
4. Enable SSH transport support for the vty.
If you want to have one device act as an SSH client to the other, you can add SSH to a second device called «Reed». This puts these devices in a client-server arrangement, where Carter acts as the server, and Reed acts as the client. The Cisco IOS SSH client configuration on Reed is the same as required for the SSH server configuration on Carter.
Issue this command to SSH from the Cisco IOS SSH client (Reed) to the Cisco IOS SSH server (Carter) to test this:
Setup an IOS Router as an SSH Server that Performs RSA-based User Authentication
Complete these steps to configure the SSH server to perform RSA-based authentication.
Specify the Host name.
2. Define a default domain name.
3. Generate RSA key pairs.
4. Configure SSH-RSA keys for user and server authentication.
5. Configure the SSH username.
6. Specify the RSA public key of the remote peer.
7. Specify the SSH key type and version. (This step is optional.)
8. Exit the current mode and return to privileged EXEC mode.
Add SSH Terminal-Line Access
If you need outbound SSH terminal-line authentication, you can configure and test SSH for outbound reverse Telnets through Carter, which acts as a comm server to Philly.
If Philly is attached to the Carter Port 2, then you can configure SSH to Philly through Carter from Reed with this command:
- You can use this command from Solaris:
Restrict SSH Access to a Subnet
You need to limit SSH connectivity to a specific subnetwork where all other SSH attempts from IPs outside the subnetwork are dropped.
You can use these steps to do the same:
Define an access-list that permits the traffic from that specific subnetwork.
Restrict access to the VTY line interface with an access-class.
This is an example configuration. In this example only SSH access to the 10.10.10.0 255.255.255.0 subnet is permitted, any other is denied access.
Note: The same procedure to lock down the SSH access is also used for switch platforms.
Configure the SSH Version 2
Variations on Banner Command Output
The banner command output varies between the Telnet and different versions of SSH connections. This table illustrates how different banner command options work with various types of connections.
Banner Command Options
Telnet
SSH v2
Displays before log into device.
Displays before log into device.
Displays before log into device.
Displays after log into device.
Displays after log into device.
Displays after log into device.
Note: SSH version 1 is no longer recommended.
Unable to Display the Login Banner
SSH version 2 supports the login banner. When it initiates the SSH session with the Cisco router, the login banner is displayed if the SSH client sends the username. For example, when the Secure Shell ssh client is used, the login banner is displayed. When the PuTTY ssh client is used, the login banner is not displayed. This is because SSH sends the username by default and PuTTY does not send the username by default.
The SSH client needs the username to initiate the connection to the SSH enabled device. The Connect button is not enabled if you do not enter the host name and username. This screenshot shows that the login banner is displayed when SSH connects to the router. The banner then prompts for a password.
Banner Prompts for a Password
The PuTTY client does not require the username to initiate the SSH connection to the router. This screenshot shows that the PuTTY client connects to the router and prompts for the username and password. It does not display the login banner.
SSH Connection to Router
This screen shot shows that the login banner is displayed when PuTTY is configured to send the username to the router.
Send Username to Router
Debug and Show Commands
Before you issue the debug commands described here, refer to Important Information on Debug Commands. Certain show commands are supported by the Output Interpreter Tool (registered to customers only), which allows you to view an analysis of show command output.
debug ip ssh Displays debug messages for SSH.
show ssh Displays the status of SSH server connections.
show ip ssh Displays the version and configuration data for SSH.
Sample Debug Output
Router Debug
Server Debug
Note: This is Solaris machine output.
Incorrect Configurations
These sections have sample debug output from several incorrect configurations.
SSH from an SSH Client Not Compiled with Data Encryption Standard (DES)
Bad Password
Router Debug
SSH Client Sends Unsupported (Blowfish) Cipher
Router Debug
Get «%SSH-3-PRIVATEKEY: Unable to retrieve RSA private key for» Error
A change in the domain name or host name can trigger this error message. Use these workarounds:
Zeroize the RSA keys and re-generate the keys.
If the previous workaround does not work, try these steps:
Zeroize all RSA keys.
Reload the device.
Create new labeled keys for SSH.
If your SSH configuration commands are rejected as illegal commands, you have not successfully generated a RSA key pair for your router. Ensure you have specified a host name and domain. Then use the crypto key generate rsa command to generate a RSA key pairs and enable the SSH server.
When you configure RSA key pairs, you can get these error messages:
No hostname specified
You must use the hostname global configuration command to configure a host name for the router.
No domain specified
You must use the ip domain-name global configuration command to configure a host domain for the router.
The number of allowable SSH connections is limited to the maximum number of vty configured for the router. Each SSH connection uses a vty resource.
SSH uses either local security or the security protocol configured through AAA on your router for user authentication. When you configure AAA, you must ensure that the console is not run under AAA. Apply a keyword in the global configuration mode to disable AAA on the console.
No SSH server connections running:
This output suggests that the SSH server is disabled or not enabled properly. If you have already configured SSH, it is recommended that you reconfigure the SSH server in the device. Complete these steps in order to reconfigure the SSH server on the device.
- Delete the RSA key pairs. After the RSA key pairs are deleted, the SSH server is automatically disabled.
Note: It is important to generate key pairs with at least 768 as bit size when you enable SSH v2.
Caution: This command cannot be undone after you save your configuration. Also, after RSA keys are deleted, you cannot use certificates or the CA or participate in certificate exchanges with other IP Security (IPSec) peers unless you regenerate the RSA keys to reconfigure CA interoperability, get the CA certificate, and request your own certificate again.
2. Reconfigure the hostname and domain name of the device.
3. Generate RSA key pairs for your router; this automatically enables SSH.
Note: Refer to crypto key generate rsa — Cisco IOS Security Command Reference, Release 12.3 for more information on the usage of this command.
Note: You can receive the SSH2 0: Unexpected mesg type received error message due to a packet received that is not understandable by the router. Increase the key length while you generate rsa keys for ssh in order to resolve this issue.
4. Configure the SSH server.
5. To enable and configure a Cisco router/switch for the SSH server, you must configure SSH parameters. If you do not configure SSH parameters, the default values are used.
ip ssh
Check SSH connection in Cisco Packet Tracer
TLDR; In this post we will discuss how we can setup and check SSH connection on a Cisco packet tracer environment.
Posted by Mohamed Irfan on 2019-Dec-17
Scenarios, where its required to have an SSH Service in packet tracer simulation
As we all know, Cisco Packet Tracer is a network simulation tool that will assist you visualize your network configuration for innovative designs built by you. It has several almost all the devices that can be in a network stack, for example
- Network Devices like L2 , L3 swicthes
- Routers
- End devices like PCs
- Web servers
- Firewalls and etc.
Hence if we want to have a web server, we just need to drag and drop the web server from the devices section and configure it with the necessary parameters.
But we do not have an SSH server separately. That brought me to write this post, to share my thoughts on testing an SSH connection. As of my personal experience I’ve been developing a network security modal for a university network as an assignment. So there it had some Access control lists ( ACLs) where it says allow only SSH traffic to a certain IP address. So when it was required to test the behavior of the firewall on SSH traffic, there was no option to test it.
How can we Do it then ??
Our aim is to test an SSH connection ( SSH service ) running on a particular host which has the given IP address. So, we can make use of the SSH services in the network devices such as L2,L3 switches or routers in the Cisco Packet tracer. Normally these devices have SSH services running on them for secure remote configuration.We can make use of it since its just an SSH service running on the device which has an IP address ( Just like an SSH server ) .
Let’s Try it with a router in Cisco Packet Tracer
In this demo, we ll be connecting the PC to the router directly ,and have them in the same sub net so that it can be simple to implement and test.
If you do not have prior knowledge on how to use the packet tracer, i would recommend you to follow the official course which is free, hence you can get an idea about whats going on.
Network configuration details
Let’s have static IP configuration ( so no need to worry about a DHCP server)
Router ( Modal — ISR4321)
Note that we have to turn the status of the interface to Up ( on ) in the router.
For all these configuration we can use the GUI provided in the Cisco packet tracer. But its better if we can try it with the CLI of the device.
Let’s Enable SSH on the router.
Before doing anything let’s first change the router’s name from the default name, if not its going to a throw errors when we try to generate the crypto key.
Now Add a IP domain name and Generate the Crypto key
Create the Cryto key using RSA ( SSH is a secure connetion not just like telnet )
Note that , it will prompt to enter the bits in module, we will stick to 1024 which is the standard practice
Now configure the line Virtual teletype (VTY) which is used to facilitate a connection to the daemon via Telnet.
- Add the transport mode input as SSH
- Make login method as local
- Name the SSH version to be used
Note that the ? will be really useful in the configuration, it will list all the possible command inputs when you have partially typed something.
Setup a username and a password. give the privilege level as 15 so that the user can directly go to the Privileged mode in the router.
The configuration on the router is almost over. But do not forget to save the running configuration to startup configuration , if not when the router is rebooted all the configurations is going to be lost.so do write this to startup configuration , switch back to privileged mode
We are good to go now,
Let’s Test the SSH connection from PC, by running the following command in the PC’s command prompt
give the password as cisco123 for the username john that is already created in the router.
Final Remarks
From the above configuration we have set up a SSH server on the IP address 192.168.1.100 , its time to use it wherever we need. For example, as it’s explained at the beginning, we can connect this router to the firewall and then check the behavior of the firewall from an outside PC for the SSH traffic. Here we are not using this router to route the traffic, it just acts as a SSH server. Obviously we can make use of this router ‘s other functionalities as we want meanwhile using it for testing SSH connection.
Доступ по SSH на Cisco IOS
Read the article CONFIGURING SSH ON CISCO IOS in
English
Вопрос «как настроить подключение к Cisco по протоколу SSH?» возникает у каждого, кто сталкивается с этим оборудованием. Ответ — «Просто!»
Для примера возьмем модель маршрутизатора Cisco 881. Команды для настройки других маршрутизаторов (1841, 2800, 3825…) или коммутаторов (2900, 3500, 4800…) будут аналогичными. Различие может быть лишь в настройке интерфейсов. (Настройка доступ по протоколу SSH на межсетевые экраны Cisco ASA описана в статье «Cisco ASA. Основы. Доступ в Интернет»
Итак, в нашем распоряжении:
- маршрутизатор Cisco 881
- рабочая станция администратора
- несколько компьютеров в локальной сети офиса
- коммутатор, который используется для организации локальной сети офиса
Задача: настроить защищенное подключение к маршрутизатору Cisco с помощью протокола SSH и обеспечить безопасное удаленное управление.

Шаг 0. Настройка интерфейса
На маршрутизаторе должен быть включен интерфейс, который будет использоваться для управления. В нашем случае это будет внутренний (LAN) интерфейс Fastethernet 0.
Для справки:
На Маршрутизаторе Cisco 881 имеется один интерфейс 3го уровня Fastethernet 4 (тот, на котором сразу можно задать IP адрес) и встроенный коммутатор с четырьмя интерфейсами 2го уровня (Fastethernet 0 – Fastethernet 3). На каждый из этих 4ех интерфейсов можно привязать по одному(!) виртуальному интерфейсу 3го уровня. (Vlan).
Для интерфейса управления маршрутизатора выбираем первый доступный адрес в сети офиса — 192.168.0.1. Далее заходим в настройки виртуального интерфейса Vlan 1 и присваиваем ему этот ip адрес. После этого привязываем его к одному из физических интерфейсов маршрутизатора (Fastethernet 0) и включаем его командой no shut.
Для наглядности:
ip address => interface Vlan X => interface Fastethernet Y
Задаем ip адрес на интерфейсе Vlan 1
R-DELTACONFIG (config)#
interface Vlan 1
ip address 192.168.0.1 255.255.255.0
no shutsown
Привязываем Vlan 1 к физическому интерфейсу FastEthernet 0
R-DELTACONFIG (config)#
interface Fa 0
switchport access vlan 1
no shutsown
Последнее действие выполняется для того, чтобы убедиться в корректности настройки. Vlan 1 привязан по умолчанию к каждому интерфейсу 2го уровня и строчка будет отображаться в конфигурации только, если номер Vlan будет отличаться от 1.
Далее необходимо проверить доступность созданного интерфейса с самого маршрутизатора, а затем с любой рабочей станции офиса, например с рабочей станции администратора. Подойдет простая проверка командой Ping. Естественно, что интерфейс маршрутизатора Fastethernet 0 должен быть соединен с коммутатором локальной сети (или напрямую с компьютером администратора) и адрес компьютера, с которого выполняется проверка, находится в той же сети, что и адрес интерфейса маршрутизатора (например 192.168.0.10).
Шаг 1 Создание учетной записи администратора
Для удаленного управления требуется создать учетную запись, если таковая еще отсутствует.
R-DELTACONFIG (config)#
username admin secret *****
Вместо звездочек ****** задаем пароль для учетной записи admin.
Важно!
По правилам хорошего тона пароль состоит из заглавных и прописных букв, цифр и спец. символов, при этом не короче 8 символов.
Шаг 2 задание пароля на режим конфигурирования
При открытии консоли управления маршрутизатором пользователь попадает в упрощенный режим, из которого возможно посмотреть лишь некоторые параметры устройства и техническую информацию о нем. При этом рядом с названием устройства присутствует знак стрелки «>»
R-DELTACONFIG>
Для просмотра конфигурации маршрутизатора и дальнейшей его настройки необходимо ввести команду enable
R-DELTACONFIG > enable
R-DELTACONFIG #
Изначально этот режим не защищен паролем и любой пользователь, который подключился консольным кабелем (про кабель и как подключиться описано в этой статье) сможет попасть в режим конфигурирования . С другой стороны, пользователь, который подключился удаленно (ssh/telnet),для которого не задан уровень привилегий (как раз наш случай), не сможет попасть в режим конфигурирования.
Задаем пароль на привилегированный режим (знак решетки # рядом с именем маршрутизатора), зайдя в режим конфигурирования (conf t).
R-DELTACONFIG (config)#
R-DELTACONFIG (config)# enable secret ******
Этот пароль будет единым для всех пользователей.
Подробнее про режимы конфигурирования можно прочитать здесь.

Шаг 3. Включение удаленного управления
Для удаленного управления необходимо указать способ аутентификации пользователя командой login local
R-DELTACONFIG (config)#
line vty 0 4
login local
После выполнения этого шага и при условии, что интерфейс управления маршрутизатора доступен пользователю, становится возможным подключение к маршрутизатору с помощью протокола telnet. Для этого необходимо из командной строки рабочей станции администратора выполнить команду
C:\Documents and Settings\***> telnet 192.168.0.1
Должен последовать запрос пользователя и пароля, которые были заданы в шаге 1. После успешной авторизации будет доступен упрощенный режим управления маршрутизатора (со стрелкой «>«). Для доступа к привилегированному режиму (#) необходимо ввести команду enable, а после пароль из шага 2.
Шаг 4 Настройка SSH
При использовании протокола Telnet (TCP порт 23) все команды и данные о конфигурировании устройства передаются в открытом виде, что потенциально небезопасно. Для защиты подключения используется протокол SSH (TCP порт 22).
Для настройки подключения через протокол SSH необходимо задать имя домена (любое), сгенерировать криптографический ключ доступа и включить сам протокол SSH версии 2.
R-DELTACONFIG (config)#
ip domain-name deltaconfig.ru
crypto key generate rsa
Choose the size of the key modulus in the range of 360 to 2048 for your
General Purpose Keys. Choosing a key modulus greater than 512 may take
a few minutes.
// после запроса необходимо указать 1024
How many bits in the modulus [512]: 1024
% Generating 1024 bit RSA keys, keys will be non-exportable. [OK]
ip ssh ver 2
После выполнения этого шага появляется возможность подключаться через SSH с помощью специальной программы, поддерживающей данную функцию, например putty. Скачать можно по этой ссылке.
Шаг 5. Ограничение подключения к маршрутизатору только через SSH
Для того, чтобы исключить возможность подключения к маршрутизатору по протоколу Telnet необходимо ввести следующие команды:
R-DELTACONFIG (config)#
line vty 0 4
transport input ssh
После этого удаленный доступ к консоли устройства будет невозможен кроме как по протоколу SSH.
Дополнительно можно ограничить доступ к управлению маршрутизатором или коммутатором Cisco только с определенных ip адресов. Как это сделать описано в этой статье.
Важно!
Будьте осторожны с доступом на устройства. Не пренебрегайте защитой подключения и ограничения круга лиц, допущенных к управлению.
Важно!
Не забудьте сохранить конфигурацию всех устройств командой write или copy run start. Иначе после перезагрузки все изменения будут потеряны.
R-DELTACONFIG# write
Building configuration.
[OK]