Ssh из командной строки windows 10

В Windows 10 и Windows Server 2019 появился встроенный SSH клиент, который вы можете использовать для подключения к *Nix серверам, ESXi хостам и другим устройствам по защищенному протоколу, вместо Putty, MTPuTTY или других сторонних SSH клиентов. Встроенный SSH клиент Windows основан на порте OpenSSH и предустановлен в ОС, начиная с Windows 10 1809.

Содержание:

  • Установка клиента OpenSSH в Windows 10
  • Как использовать SSH клиенте в Windows 10?
  • SCP: копирование файлов из/в Windows через SSH

Установка клиента OpenSSH в Windows 10

Клиент OpenSSH входит в состав Features on Demand Windows 10 (как и RSAT). Клиент SSH установлен по умолчанию в Windows Server 2019 и Windows 10 1809 и более новых билдах.

Проверьте, что SSH клиент установлен:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'

'OpenSSH.Client установка в windows 10

В нашем примере клиент OpenSSH установлен (статус: State: Installed).

Если SSH клиент отсутствует (State: Not Present), его можно установить:

  • С помощью команды PowerShell:
    Add-WindowsCapability -Online -Name OpenSSH.Client*
  • С помощью DISM:
    dism /Online /Add-Capability /CapabilityName:OpenSSH.Client~~~~0.0.1.0
  • Через Параметры -> Приложения -> Дополнительные возможности -> Добавить компонент. Найдите в списке Клиент OpenSSH и нажмите кнопку Установить.

клиент openssh установить компонент

]Бинарные файлы OpenSSH находятся в каталоге c:\windows\system32\OpenSSH\.

  • ssh.exe – это исполняемый файл клиента SSH;
  • scp.exe – утилита для копирования файлов в SSH сессии;
  • ssh-keygen.exe – утилита для генерации ключей аутентификации;
  • ssh-agent.exe – используется для управления ключами;
  • ssh-add.exe – добавление ключа в базу ssh-агента.

исполняемые файлы OpenSSH

Вы можете установить OpenSSH и в предыдущих версиях Windows – просто скачайте и установите Win32-OpenSSH с GitHub (есть пример в статье “Настройка SSH FTP в Windows”).

Как использовать SSH клиенте в Windows 10?

Чтобы запустить SSH клиент, запустите командную строку
PowerShell
или
cmd.exe
. Выведите доступные параметры и синтаксис утилиты ssh.exe, набрав команду:

ssh

usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-E log_file] [-e escape_char]
[-F configfile] [-I pkcs11] [-i identity_file]
[-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
[-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
[-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
destination [command]

параметры ssh клиента в windows

Для подключения к удаленному серверу по SSH используется команда:

ssh username@host

Если SSH сервер запущен на нестандартном порту, отличном от TCP/22, можно указать номер порта:

ssh username@host -p port

Например, чтобы подключиться к Linux хосту с IP адресом 192.168.1.202 под root, выполните:

ssh [email protected]

При первом подключении появится запрос на добавление ключа хоста в доверенные, наберите yes -> Enter (при этом отпечаток ключа хоста добавляется в файл C:\Users\username\.ssh\known_hosts).

Затем появится запрос пароля указанной учетной записи, укажите пароль root, после чего должна открытся консоль удаленного Linux сервера (в моем примере на удаленном сервере установлен CentOS 8).

подключение из windows 10 в linux с помощью встроенного ssh клиента

С помощью SSH вы можете подключаться не только к *Nix подобным ОС, но и к Windows. В одной из предыдущих статей мы показали, как настроить OpenSSH сервер на Windows 10 и подключиться к нему с другого компьютера Windows с помощью SSH клиента.

Если вы используете SSH аутентификацию по RSA ключам (см. пример с настройкой SSH аутентификации по ключам в Windows), вы можете указать путь к файлу с закрытым ключом в клиенте SSH так:

ssh [email protected] -i "C:\Users\username\.ssh\id_rsa"

Также вы можете добавить ваш закрытый ключ в SSH-Agent. Сначала нужно включить службу ssh-agent и настроить ее автозапуск:

set-service ssh-agent StartupType ‘Automatic’
Start-Service ssh-agent

Добавим ваш закрытый ключ в базу ssh-agent:

ssh-add "C:\Users\username\.ssh\id_rsa"

Теперь вы можете подключиться к серверу по SSH без указания пути к RSA ключу, он будет использоваться автоматически. Пароль для подключения не запрашивается (если только вы не защитили ваш RSA ключ отдельным паролем):

ssh [email protected]

Еще несколько полезных аргументов SSH:

  • -C
    – сжимать трафик между клиентом и сервером (полезно на медленных и нестабильных подключениях);
  • -v
    – вывод подробной информации обо всех действия клиента ssh;
  • -R
    /
    -L
    – можно использовать для проброса портов через SSH туннель.

SCP: копирование файлов из/в Windows через SSH

С помощью утилиты scp.exe, которая входит в состав пакета клиента SSH, вы можете скопировать файл с вашего компьютера на SSH сервер:

scp.exe "E:\ISO\CentOS-8.1.1911-x86_64.iso" [email protected]:/home

scp.exe копирование файлов через ssh

Можно рекурсивно скопировать все содержимое каталога:

scp -r E:\ISO\ [email protected]:/home

И наоборот, вы можете скопировать файл с удаленного сервера на ваш компьютер:

scp.exe [email protected]:/home/CentOS-8.1.1911-x86_64.iso e:\tmp

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

Итак, теперь вы можете прямо из Windows 10 подключаться к SSH серверам, копировать файлы с помощью scp без установки сторонних приложений и утилит.

Уровень сложностиПростой

Время на прочтение5 мин

Количество просмотров307K

Программистов, сисадминов, devops’ов, тестировщиков часто объединяет использование некоторых общих технологий. Например, возможность иметь удалённый доступ к серверу пригодилось бы любому из указанной выше анекдотичной компании. Поэтому в этой статье мы рассмотрим основы работы с протоколом SSH на базовом уровня (без генерации ключей, подписей, мам, пап и кредитов). «Продвинутое» использование посмотрим уже отдельно, в следующий раз. Материал подготовил Макс, автор YouTube-канала PyLounge. Поехали!

Введение

SSH (Secure SHell — защищенная оболочка) — сетевой протокол прикладного уровня, предназначенный для безопасного удаленного доступа к различным системам (Linux, Windows, Mac).

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

Эта служба была создана в качестве замены не зашифрованному Telnet и использует криптографические техники, чтобы обеспечить, что всё сообщение между сервером и пользователем было зашифровано.

Чтобы установить SSH-соединение, необходимы два компонента: SSH-сервер и SSH-клиент. Сервер прослушивает определенный порт (по умолчанию это порт 22) и при успешной аутентификации дает доступ пользователю. Все команды, которые используются на SSH-клиенте, отправляются через защищенный канал связи на SSH-сервер, на котором они выполняются и откуда отправляют результат работы обратно клиенту.

SSH-сервер

Устанавливается на управляемой операционной системе и принимает входящие подключения от клиентских машин, проверяя соединение одним из способов:

  • по IP-адресу клиента, что не слишком безопасно из-за риска подмены;

  • по публичному ключу клиента и имени пользователя. Нужно создать приватный (закрытый) и публичный (открытый) ключ. Зашифровав информацию одним ключом, можно расшифровать ее только другим;

  • по паролю клиента, который передается в зашифрованном виде. Это один из наиболее распространенных вариантов. Вводить его нужно при каждом подключении.

Платные и бесплатные SSH-серверы есть для всех распространенных ОС:

  • BSD — OpenSSH;

  • Linux — dropbear, lsh-server, openssh-server;

  • Windows — freeSSHd, copssh, WinSSHD, OpenSSH и т. д.

SSH-клиент

Используется для входа на удаленный сервер и выполнения команд. Через клиент выполняется управление удаленным компьютером.

SSH-клиенты разработаны для всех ОС. Имеют платные и бесплатные версии:

  • Linux/BSD — openssh-client, putty, ssh, Vinagre;

  • Windows — PuTTY, SecureCRT, ShellGuard;

  • Android — connectBot.

Встроенный SSH-клиент Windows, основанный на OpenSSH, предустановлен в ОС, начиная с Windows 10 1809.

Установка OpenSSH на Ubuntu

Установка с помощью менеджера пакетов apt-get:

sudo apt-get install openssh-server

Проверка SELinux

Security Enhanced Linux, или SELinux – это усовершенствованный механизм контроля доступа, встроенный в большинство современных дистрибутивов Linux. Первоначально он был разработан Агентством национальной безопасности США для защиты компьютерных систем от вторжения злоумышленников и взлома. SELinux также может помешать работе с ssh. Поэтому необходимо убедиться, что он отключен, либо отключить его.

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

sudo apt-get install policycoreutils
sudo apt-get install net-tools

Проверяем статус SELinux. Состояние должно быть disable.

sestatus

Подключение к виртуальной машине с типом подключения NAT

Если виртуальная машина использует тип сетевого подключения NAT, то первоначально необходимо настроить проброс портов. Пробросим порт хоста 2222 (или любой свободный) на гостевой порт виртуальной машины номер 22 (порт ssh по умолчанию).

После этого мы можем подключиться из Windows к нашей виртуальной машине.

Подключение по ssh через PuTTY

Т.к. в качестве сетевого подключения у виртуальной машины используется NAT, при подключении мы будем указывать петлевой адрес localhost (127.0.0.1) c портом, на который был назначен проброс.

После этого вводим имя пользователя (пользователь должен существовать в linux!!!) и пароль от этого пользователя.

Подключение по ssh через Командную строку Windows (cmd)

Запускаем командную строку сочетанием клавиш Win + R . В открывшемся окне указываем cmd. Нажимаем OK.

В общем видео подключение по ssh имеет вид:

ssh имя_пользователя@ip_адрес_компьютера_к_которому_подключаемся -p порт

Если для подключения используется стандартный порт ssh — 22, то порт можно не указывать.

В открывшемся окне вводим команду:

ssh student@127.0.0.1 -p 2222

Вводим пароль пользователя. Всё. Вы великолепны!

Подключение к виртуальной машине с типом подключение Сетевой мост

С типом подключения Сетевой мост необходимо выдать статический ip для Linux системы. Дальнейшее подключение будет уже по этому, выданному ip, а не через localhost.

Установка статического ip

Начиная с выпуска Ubuntu 17.10 NetPlan теперь это инструмент настройки сети по умолчанию для управления настройками сети, заменяющий файл конфигурации /etc/network/interfaces, который использовался в предыдущих версиях.

Файлы конфигурации для Netplan находятся в каталоге /etc/netplan и написаны на языке YAML. В этом каталоге вы найдете файлы конфигурации YAML.

Откроем конфигурационный файл:

sudo nano /etc/netplan/*.yaml

Отредактируем конфигурационный файл:

network:  
  version: 2
  renderer: NetworkManager
  ethernets:
      enp0s3:
          dhcp4: false
          addresses: [10.40.0.224/24]
          gateway4: 10.40.0.1
          nameservers:
              addresses: [10.2.0.8, 10.2.0.3]

Здесь:

  • ethernets — указывает на проводное Ethernet подключение;

  • enp0s3 — имя сетевого интерфейса (можно узнать командой ifconfig);

  • dhcp4 — автоматическая выдача ipv4-адреса с помощью службы dhcp (для ipv6 указывать dhcp6);

  • addresses — ip-адрес и маска сети, которые назначаются компьютеру;

  • gateway4 — шлюз по умолчанию;

  • nameservers — список dns-серверов.

Посмотреть настройки можно с хостовой машины на Windows с помощью команды ipconfig /all.

Чтобы применить изменения и перезагрузить сеть, вводим команду:

sudo netplan apply

Подключение по ssh

Запускаем командную строку сочетанием клавиш Win + R . В открывшемся окне указываем cmd. Нажимаем OK.

В открывшемся окне вводим команду:

ssh student@10.40.0.224

Вводим пароль пользователя. Всё. Вы великолепны (2)!

Заключение

Несмотря на высокую защиту протокола, использование стандартного порта значительно повышает риск взлома сервера. Например, это можно сделать при помощи brute-force (атака полным перебором). Порт 22 — открытый, поэтому злоумышленнику нужно только подобрать логин и пароль к серверу. Это сложно, но возможно. Чтобы максимально ограничить доступ к серверу для злоумышленников (настроить брандмауэр, iptables), можно сменить SSH-порты.

Ресурсы, которые использовал

  1. Как включить SSH в Ubuntu 20.04 (Routerus):https://routerus.com/how-to-enable-ssh-on-ubuntu-20-04/

  2. Коротко об SSH / Хабр: https://habr.com/ru/sandbox/166705/

  3. Что такое SSH (блог REG.RU): https://help.reg.ru/support/hosting/dostupy-i-podklyucheniye-panel-upravleniya-ftp-ssh/chto-takoye-ssh

SSH (Secure Shell) in Windows CMD allows users to securely connect to remote servers using the following command syntax:

ssh username@hostname

Understanding SSH

What is SSH?

SSH, or Secure Shell, is a network protocol that allows secure access to remote machines over an unsecured network. It provides a text-based interface for performing administrative tasks, executing commands, and transferring files securely. Unlike other protocols such as Telnet or FTP, which send data in plain text, SSH encrypts the data being transmitted, making it a vital tool for maintaining confidentiality and integrity.

Benefits of Using SSH

Using SSH in the Windows command line provides several significant benefits:

  • Connection Security: SSH ensures that all data transmitted is encrypted, protecting it from eavesdroppers and unauthorized access.

  • Remote Administration: System administrators can manage servers remotely, which is particularly useful for maintaining systems without being physically present.

  • File Transfer Capabilities: SSH can also facilitate secure file transfers using protocols like SCP (Secure Copy Protocol) or SFTP (SSH File Transfer Protocol), making it a versatile tool for system management.

Mastering SCP in Windows Cmd: Quick Transfer Guide

Mastering SCP in Windows Cmd: Quick Transfer Guide

Preparing Your Windows CMD for SSH

Enabling SSH on Windows

Starting with Windows 10 and later versions, Microsoft has included a built-in SSH client. To check if it is enabled on your system:

  1. Open your Windows CMD.

  2. Run the following command to verify SSH’s availability:

ssh -V

If the SSH client is not available, you will need to enable it through the Windows Features. To do this, go to Settings > Apps > Optional Features and add OpenSSH Client.

Installing OpenSSH Client

If you find that OpenSSH is not installed on your version of Windows, follow these steps:

  1. Open the Settings application.
  2. Navigate to Apps > Optional Features.
  3. Click on Add a feature and search for OpenSSH Client.
  4. Select it and click Install.

Once installed, verify the installation again with:

where ssh

If the command returns a path, your installation was successful.

List in Windows Cmd: Quick and Easy Commands Explained

List in Windows Cmd: Quick and Easy Commands Explained

Basic SSH Commands

Opening an SSH Connection

To establish a connection to a remote server using SSH, use the command syntax:

ssh username@hostname

Here, username is your account name on the remote server, and hostname is the server’s IP address or domain name. For example:

ssh admin@192.168.1.10

Specifying Ports

By default, SSH connects through port 22. If your server uses a different port, you can specify it with the `-p` option:

ssh -p 2222 username@hostname

This command is essential when accessing servers with custom configurations for added security.

Mastering Pwd in Windows Cmd: Your Quick Reference Guide

Mastering Pwd in Windows Cmd: Your Quick Reference Guide

Advanced SSH Usage

SSH Keys: Understanding Authentication

One of the most secure methods for using SSH is through SSH keys. SSH keys consist of a public and a private part, where the public key is placed on the server you want to access, and the private key is kept secure on your local machine. This method eliminates the need for password-based logins, enhancing security significantly.

Generating SSH Keys on Windows

To generate a new SSH key pair, follow these steps:

  1. Open the CMD window.
  2. Use the following command:
ssh-keygen

You will be prompted to choose a location to save the key. By default, it saves to `C:\Users\your-username\.ssh\id_rsa`. You can simply press Enter to accept the default path. Follow the prompts to set a secure passphrase for added security.

Adding SSH Keys to the SSH Agent

An SSH agent manages your keys and simplifies the process of connecting to servers. To add your generated key to the agent, first start the agent:

eval $(ssh-agent)

Then, add your private key:

ssh-add path_to_private_key

For example:

ssh-add C:\Users\your-username\.ssh\id_rsa

Repair Windows Cmd: Quick Fixes and Tips

Repair Windows Cmd: Quick Fixes and Tips

Configuring SSH for Easier Use

Using SSH Config File

To streamline your SSH commands, you can create a configuration file that saves your connection settings. This file is located at `C:\Users\your-username\.ssh\config`.

Here’s an example of what the contents might look like:

Host myserver
    HostName hostname
    User username
    Port 2222

With this configuration, you can now connect simply by using:

ssh myserver

Executing Commands Remotely

SSH not only allows for interactive shell sessions but also enables you to run commands on the remote server. Use the following syntax:

ssh username@hostname 'command_here'

For instance, to list the files in a directory on the remote server:

ssh username@hostname 'ls -al'

This feature is especially useful for scripting and automation tasks.

Sleep Windows Cmd: Mastering Sleep Commands in Cmd

Sleep Windows Cmd: Mastering Sleep Commands in Cmd

Troubleshooting Common SSH Issues

Connection Refused or Timeout Errors

If you encounter connection issues, it might be due to several reasons. Common ones include:

  • The SSH server not running on the host.
  • Incorrect hostname or IP address.
  • Firewall or network settings blocking the connection.

To troubleshoot, ensure the SSH service is active on the server and that your network configuration permits SSH connections.

SSH Authentication Failures

Authentication failures often arise from incorrect credentials or issues with key-based authentication. Common approaches to resolving these issues involve:

  • Verifying the username and hostname for accuracy.
  • Checking the permissions of your SSH keys to ensure they are secure (they should be readable only by you).
  • On the server side, confirm that your public key is in the `~/.ssh/authorized_keys` file and properly formatted.

Use the following command to troubleshoot authentication problems:

ssh -v username@hostname

The `-v` flag enables verbose mode, providing detailed output that can help identify where the authentication process is failing.

Lock Windows Cmd: A Quick Guide to Securing Your Commands

Lock Windows Cmd: A Quick Guide to Securing Your Commands

Conclusion

SSH in Windows CMD opens a pathway to secure remote access and management of systems. By setting up an SSH client, generating keys, and leveraging advanced commands, users can efficiently perform tasks and maintain their servers with confidence. Explore these commands further, practice connecting to various servers, and experience the advantages of SSH firsthand.

Make File in Windows Cmd: A Quick Guide

Make File in Windows Cmd: A Quick Guide

Additional Resources

For those looking to deepen their understanding of SSH, consider exploring additional reading materials, online forums, and recommended tools to enhance your SSH experience. Experiment with different SSH configurations and commands to optimize your workflow!

In many cases, to manage your Linux servers, you can need to allow remote access and this can be done via the Secure Shell (SSH). Since many years ago, Linux systems can use the native terminal to use SSH but it was not the case for Windows systems which need some tools to be installed.

Windows systems have seen many improvements so that you don’t need to install a tool but you can use native tools which are available. In this tutorial, we will learn how to ssh a Linux machine from Windows with the native tools.

What to know about SSH

Secure Shell is a secure and encrypted connection protocol allowing remote and secure sign-ins over unsecured connections. The connection works in the client-server mode, so the connection is established by the SSH client connecting to the SSH server.

SSH offers several options for user authentication and the most common ones are passwords and public key authentication methods:

  • password: it works like the usual process for a local computer which means that you need to have the username and password of an existing account on the server.
  • public key: the principle is to have a cryptographic key pair public key and private key where the public key is configured on the server to authorize access and grant anyone who has a copy of the private key access to the server.

1) Install feature OpenSSH windows 10 client

Windows machines now allow you to use native tools to establish a SSH connection but you need first to make sure that the feature Openssh windows client is installed. Normally is not installed by default so you will need first to do it. Go to Windows -> Settings -> Apps -> Manage optional feature 

Click Add a feature 

Select OpenSSH Client and then install.

Now it’s installed

2) SSh connection with Windows Powershell and command prompt

Now you can decide to use the command prompt or Windows PowerShell to access your Linux server via ssh.

a) SSh with Windows Powershell

The Windows Powershell native tool allows you to remotely connect to a server via ssh. You just have to open it with Windows + r then hit the key A

Now enter the command the ssh command for the connection to your remote Linux server: ssh [email protected]

b) SSh with command prompt

To remotely access your server via the command, you just have to launch it with the key combination Windows + r and then enter cmd

Now in the command prompt, you can use the ssh command as with powershell

Now you know how you can connect to your remote Linux server with SSH with the native tools offered by Windows. You can choose to use putty tool as well but now it’s easiest and more comfortable to use the tools which are offered by default.

SSH (or Secure Shell) is a protocol for secure remote login to another machine. This provides a command prompt where you can issue commands to execute programs or perform tasks on the remote machine. You can connect using a program called PuTTY or using the command prompt.

Let’s take a look at a video demo using the windows command prompt.

Using PuTTY

First you need to download and install the program. You can download PuTTY here. Go to your downloads folder then double click putty-64bit-0.73-installer.msi

Start PuTTY. In the configuration window, enter the IP address or hostname of the machine you’re connecting to. Enter the port number – usually 22. Click ‘open’.

connect to SSH server using PuTTY

When a connection is established, enter your username and password for the machine you’re connecting to.

login to SSH server using PuTTY

Once authenticated you can issue various commands from the command prompt.

SSH server using PuTTY

Connect from the Command Prompt

First, open the command prompt. Type ‘cmd’ into the search field on the bottom left of your screen. Click ‘command prompt’.

open command prompt

To connect to the server type:

ssh username@hostname

So for example:

ssh pi@192.168.1.4

Enter the password for the username when prompted.

Connect to SSH server from Windows 10 Command Prompt

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как поменять шрифт windows forms
  • Как сделать стиль windows 7 на windows 10
  • Ssl library for windows
  • Как установить windows 10 через буткамп
  • Отключение драйвера мониторинга сетевой активности windows