Меню Рубрики

Ssh windows 10 bash

Использование встроенного SSH клиента в Windows 10

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

Установка клиента 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 установлен (статус: State: Installed).

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

  • С помощью команды PowerShell: Add-WindowsCapability -Online -Name OpenSSH.Client*
  • С помощью DISM: dism /Online /Add-Capability /CapabilityName:OpenSSH.Server

0.0.1.0

  • Через Параметры -> Приложения -> Дополнительные возможности -> Добавить компонент. Найдите в списке Клиент OpenSSH и нажмите кнопку Установить.
  • ]Бинарные файлы OpenSSH находятся в каталоге c:\windows\system32\OpenSSH\.

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

    Как использовать 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 используется команда:

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

    ssh username@host -p port

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

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

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

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

    ssh root@192.168.1.92 -i «C:\Users\username\.ssh\id_rsa»

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

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

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

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

    Еще несколько полезных аргументов 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» root@192.168.1.202:/home

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

    scp -r E:\ISO\ root@192.168.1.202:/home

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

    scp.exe root@192.168.1.202:/home/CentOS-8.1.1911-x86_64.iso e:\tmp

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

    Источник

    Keep SSH running on Windows 10 Bash

    I am having a problem keeping SSH running on the Windows Subsystem for Linux. It seems that if a shell is not open and running bash, all processes in the subsystem are killed. Is there a way to stop this?

    I have tried to create a service using nssm but have not be able to get it working. Now I am attempting to start a shell and then just send it to the background but I haven’t quite figured out how.

    3 Answers 3

    You have to keep at least one bash console open in order for background tasks to keep running: As soon as you close your last open bash console, WSL tears-down all running processes.

    And, yes, we’re working on improving this scenario in the future 😉

    Update 2018-02-06

    In recent Windows 10 Insider builds, we added the ability to keep daemons and services running in the background, even if you close all your Linux consoles!

    One remaining limitation with this scenario is that you do have to manually start your services (e.g. $ sudo service ssh start in Ubuntu), though we are investigating how we might be able to allow you to configure which daemons/services auto-start when you login to your machine. Updates to follow.

    To maintain WSL processes, I place this file in C:\Users\USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\wsl.vbs

    In /etc/rc.local I kick off some services and finally «sleep» to keep the whole thing running:

    In /etc/sudoers.d I added a ‘rc-local’ file to allow the above commands without a sudo password prompt:

    This worked well on 1607 but after the update to 1704 I can no longer connect to wsl via ssh.

    Once you have cron running you can use ‘sudo crontab -e -u username’ to define cron jobs with @reboot to launch at login.

    Just read through this thread earlier today and used it to get sshd running without having a wsl console open. I am on Windows 10 Version 1803 and using Ubuntu 16.04.5 LTS in WSL. I needed to make a few changes to get it working. Many thanks to google search and communities like this.

    I modified /etc/rc.local as such:

    I needed to add the directory for sshd or I would get an error «Missing privilege separation directory /var/run/sshd I commented out cron because I was getting similar errors and haven’t had the time or need yet to fix it.

    I also changed the sudoers entries a little bit in order to get them to work:

    Hope this is useful to someone. John Butler

    Источник

    ssh remote access on bash Windows 10

    I’d like to connect remotely to the Ubuntu bash on my Windows 10.

    I’ve got an answer on port 22 but when it asks for username and password, it says access denied.

    I’ve already created a user «root» and i’ve done a «sudo passwd root»

    Windows firewall is deactivated (service stopped).

    5 Answers 5

    Stop ssh server and ssh broker services on Windows to avoid SSH port conflict

    Makes below changes in /etc/ssh/sshd_config :

    Then restart ssh server by sudo service ssh restart . If you see could not load host key error then create host key as below and restart ssh service:

    First, You need to Stop/Disable Windows 10 SSH Server Broker Services or Change OpenSSH Port.

    After that, modify the /etc/ssh/sshd_config:

    I started having issues after installing VirtualBox with my Bash on Ubuntu on Windows SSH connection. I stopped the VM, uninstalled, and still couldn’t authenticate. The user ‘Nobody’ is correct, the best solution would either to disable the SSH Broker for Windows 10, or just change the port for SSH on the Linux subsystem, which I did, and works perfectly.

    You must also in most cases add a inbound firewall rule to allow traffic on port 22.. the default setup only allows for inbound traffic using the windows implementation of ssh, therefore not allowing any traffic for the openssh-server. Just follow the instructions above and then add a rule for port 22 inbound in Windows Firewall and you should be set.

    Since windows implementation doesn’t provide chroot you need to modify the /etc/ssh/sshd_config

    Also you will need to create a user using useradd command or so.

    Not the answer you’re looking for? Browse other questions tagged windows ssh or ask your own question.

    Related

    Hot Network Questions

    Subscribe to RSS

    To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

    site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.10.21.37848

    Источник

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

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

  • Ssh server для windows 7
  • Ssh powershell windows 10
  • Ssh port windows 7
  • Ssh no kex alg windows
  • Ssh keys windows github