Как запустить ssh agent на windows

I'm following #335 Deploying to a VPS , and near the end of the episode, we need to run ssh-add to give server access to github repo. The problem is how do I run it in windows? What need to instal...

Original answer using git’s start-ssh-agent

Make sure you have Git installed and have git’s cmd folder in your PATH. For example, on my computer the path to git’s cmd folder is C:Program FilesGitcmd

Make sure your id_rsa file is in the folder c:usersyourusername.ssh

Restart your command prompt if you haven’t already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 — A better solution if you’re using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn’t rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:WindowsSystem32OpenSSHssh.exe. If it’s not in the list you may need to close and reopen cmd.

Once you’ve followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:WindowsSystem32OpenSSHssh.exe). This is to stop inconsistencies between the version of ssh you’re using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won’t need to start the ssh-agent every time you restart your computer
  • Identities that you’ve added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:UsersUser.ssh folder)
  • You don’t need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

SSH-Agent and OpenSSH are tools in Windows that can be used to authenticate to remote Git repositories, such as GitLab, GitHub, Azure DevOps, etc. Once set up as a service that stores your various SSH keys, this can facilitate authentication without entering a password each time, removing the irritation of entering a password every time you wish to push/pull/etc. from a Git repository.

Prerequisites

  • The OpenSSH Client optional service must be enabled on your machine, and OpenSSH must be added to your PATH environment variable. You can read how to do that here.
  • A remote Git repository that you wish to access. We will use a GitLab repository for this article; however, the process will be similar for other Git management providers.
  • Git must be installed on your machine.

How to Install the SSH-Agent Service in Windows

Using an elevated PowerShell window (run as admin), execute the following command to install the SSH-Agent service and configure it to start automatically when you log into your machine:

Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service

To avoid needing to restart your system to get the service running for the first time, execute this command:

start-ssh-agent.cmd

Setting up an SSH Key Pair to Access a Git Remote Provider

Using a command line tool such as Bash or PowerShell, you should be able to follow these steps to create a local SSH key pair. For our example, we will create an ED25519 key, but you can create other keys such as an RSA.

Create a new SSH ED25519 key, giving it a useful comment:

ssh-keygen -t ed25519 -C "Git-Demo"

By default, the file will be stored in your local user’s SSH repository in Windows. You can choose another storage location if you wish or rename the file by entering a new file path to save the key. Leave it blank to stick with the default.

In our example, we rename the file from the default id_ed25519 to id_ed25519_git_demo:

You can also add a password if you like or leave this blank:

You will then be shown the key’s randomart image to confirm creation:

Copy the contents of the public key to your clipboard. You can read this key with the following command:

cat pathtosshkey.pub

For example, our code is likely:

cat C:Userschastie/.sshid_ed25519_git_demo.pub

Note: We access the public key with the .pub suffix.

A sample is shown here. You can then select this and copy it with a right-click of your mouse:

In GitLab (or the appropriate location of your Git remote repository), you can now add this public key to your user profile. In GitLab, you can do this by adding it under the SSH Keys section of your user settings:

Test that you can connect to the repository when using the SSH private key directly with this command:

ssh -i path/to/ssh/private/key -T git@host

For example, our command could be:

ssh -i C:Userschastie/.sshid_ed25519_git_demo -T git@gitlab.mycompany.com

or

ssh -i C:Userschastie/.sshid_ed25519_git_demo -T git@github.com

We have now established an SSH key pair that can authenticate to our Git remote provider. It remains to set this up in the SSH-Agent service to automatically provide access. We can demonstrate the issue by attempting the same connection, but without specifically naming the SSH key, with the command below:

ssh -T git@host

As we can see, if we execute this command without specifying an SSH key, we are prompted for a password:

Adding the SSH Key to the SSH-Agent Service

Our goal is to be able to connect to a Git repository without entering a password. At this stage, we have a working SSH key pair and the SSH-Agent service installed and running.

Execute the following command to add your SSH key to your SSH-Agent service:

ssh-add path/to/ssh/private/key

For our example, our command could be:

ssh-add C:Userschastie/.sshid_ed25519_git_demo

We can now test our connection to our Git remote provider without specifying a key and connect successfully:

ssh -T git@host

Configuring Git to Leverage the Windows SSH-Agent

In an elevated console (run as admin), execute the following command to modify your existing Git configuration to leverage the windows OpenSSH service as the core SSH command:

git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe

Congratulations! You have now set up your environment to automatically authenticate to your Git remote provider through an SSH key pair, without using passwords. If you wish to facilitate access to any other Git remote providers, simply follow the same steps to generate a key pair ( as outlined above) and add it to your existing SSH-Agent service.

В 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:windowssystem32OpenSSH.

  • 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 [[email protected]]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 [email protected]

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

ssh [email protected] -p port

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

ssh [email protected]

При первом подключении появится запрос на добавление ключа хоста в доверенные, наберите yes -> Enter (при этом отпечаток ключа хоста добавляется в файл C:Usersusername.sshknown_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:Usersusername.sshid_rsa"

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

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

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

ssh-add "C:Usersusername.sshid_rsa"

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

ssh [email protected]

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

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

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

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

scp.exe "E:ISOCentOS-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 без установки сторонних приложений и утилит.

Cover image for Setting up SSH and Git on Windows 10

Dominik Biedebach

Welcome to my first official guide on Dev.to. Today I want to explain how you can setup SSH and Git on your Windows 10 computer.

Note: This is not about 100% securing your keys but about how to generate keys for use with GitHub.

Thanks to garethdd for his constructive feedback.

What is SSH?

SSH stands for Secure Shell and is an awesome way to authenticate yourself on remote servers (for example the Github server) without typing in a password everytime.

SSH works via two keys, the Private Key and the Public Key. While the private key should always stay private and safe, the public key can be shared around the internet without any problems.

The private key allows you to get access to servers that have your public key registered, so your access can only be stolen if the attacker somehow gets your Secret Key so keep it safe!

SSH should be preinstalled on new Windows 10 machines.

What is Git?

Git is a free version management tool that helps you to versionize your code and potentially save it on a remote server (for example Github, Gitlab or Bitbucket).

You can install Git from here:
https://git-scm.com/download/win

You can also install Git via chocolatey:

Create a SSH Key

The first step is to generate a new SSH key. Use cmd or Powershell and run the following command:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

You can but don’t need to give it a passphrase since you should never share your secret key around but using one will secure your keys. Keep in mind that everybody can have as many private keys as they want.

This generates a new private SSH key with rsa encryption and 4096 bits. It also generates a public key from the secret key which you can share around.

There will be a new folder and files in your Windows user folder.

In general you can create as many keys as you want. The id_rsa key is the default key generated by ssh and will be automatically be used by your ssh-agent if you don’t tell it to use another key.

What is an ssh-agent?

An ssh-agent is the agent process used to actually authenticate yourself with ssh. There are a few out there (PuTTY with Pageant for example) but for this example we’ll use the ssh-agent provided by the native and default Windows 10 ssh-agent.

If you want to you can use PuTTY and Pageant to make your keys even more secure. Read this post on Digital Ocean for more information.

If you want to change the key used by your ssh-agent, you must first start the service. The service will be disabled on Windows 10 by default. Search for Services and open the Services settings and look for the «OpenSSH Authentication Agent» and Activate it:

Now you will be able to access the ssh-agent from your console via ssh-agent.

For this example we’re going to try to load another key called example into our agent and use it instead of the id_rsa key. To do this you can run the following command:

Now you will have both keys available for this session.

Register your SSH Key on Github

The next step is to register your generated SSH key on Github. For that, run the following command:

type C:Usersyour_user_name.sshid_rsa.pub

and copy the output string into your clipboard. Now go to your Github keys settings and add a new SSH key with your public key and save it.

Congratulations! You now are able to get and push code to Github without any password!

Note: There should also be a C:Usersyour_user_name.sshid_rsa file. This is your private key, don’t share this around!

Setup Github in your Shell

Now it’s time to setup Git on your machine. After installing it from the link above, open a new cmd or Powershell window. Now we need to set your public Git name and Git email address. This will always be public when pushing code.

Luckily Github gives you a privatized email address for use. Go to https://github.com/settings/emails and you will find a @users.noreply.github.com email address for your account. Copy this email address.

Next register your name and email in Git:

git config --global user.name "Your Name"
git config --global user.email your_email@users.noreply.github.com

Congratulations! Now all your Commits will be registered as being commited from your Github user.

Signing your GitHub commits (Optional Step)

To sign your commits you first must install the GPG command line tools. After you installed the GPG toolkit, you can run the following command to generate a new gpg key:

This will ask you what kind of key you want. Go for RSA and RSA.

Now you need to enter a bit length. The recommendation is 4096 bits.

After that you can specify a expiration length or if the key should never expire. Pick as you want. Expiring keys are more secure in general because you have to renew them every now and then.

Now enter your personal informations to verifying your identity with your gpg key.

When you’re done you will be asked for a passphrase. Give it a secure passphrase and you will be done with your gpg-key generation.

After that you will be able to find your key in your users .gnupg folder as specified in the success message.

If you want to list your gpg keys, simply run

// short version
gpg --list-secret-keys

// long version
gpg --list-secret-keys --keyid-format LONG

Your GPG key you can share with Github is the key coming after sec rsa4096/ so for example in

/Users/hubot/.gnupg/secring.gpg
------------------------------------
sec   4096R/3AA5C34371567BD2 2016-03-10 [expires: 2017-03-10]
uid                          Hubot 
ssb   4096R/42B317FD4BA89E7A 2016-03-10

the gpg key would be 3AA5C34371567BD2

To get your public key block, simply run

gpg --armor --export YOUR_GPG_KEY

which will output your public GPG Key Block. Copy it and paste it to your GitHub Account here.

From now on your commits will be signed when commited.

Use Git

Now you’re ready to actually use Git. From now you can clone repositories via git clone or push new code to Github. Here is a quick reference:

# Clone a repository to the current directory
git clone [REPOSITORY_CLONE_URL]

# Create a new commit with a message
git commit -m "Your commit message"

# Add files to the commit
git add .
git add ./filename.ext

# Push your commits to Github
git push origin master
git push origin [YOUR_BRANCH_NAME]

# Reset your repo to the last version
git reset --hard

# Create a new branch
git checkout -b [YOUR_BRANCH_NAME]

# Switch branches
git checkout [YOUR_BRANCH_NAME]
git checkout master

# Reset a single file
git checkout ./filename.ext

Conclusion

Thanks for reading this post. I hope it helped you with the setup. If you need help or have questions let me know!

Инструменты

Git SSH Windows — пошаговое руководство

Дата размещения статьи 08/12/2019 👁26098

Git SSH Windows — пошаговое руководство

Настроим пошагово Git SSH для Windows 10. Это позволит вам выполнять команды git без ввода пароля от своей учетной записи GitHub.

Порядок действий:

  1. Генерация ключа SSH.
  2. Добавление SSH-ключа в ssh-agent.
  3. Добавление ключа SSH в учетную запись GitHub.

Git SSH Windows

Генерация ключа SSH

Откройте bash/терминал. Добавьте следующий текст, подставив свой адрес электронной почты GitHub.

ssh-keygen -t rsa -b 4096 -C "ваша@почта.com"

Будет создан ключ ssh, используя e-mail в качестве метки.

Когда вам будет предложено «Введите файл, в котором вы хотите сохранить ключ», нажмите Enter. Это установит в местоположение по умолчанию.

Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]

Далее введите безопасную фразу-пароль дважды или просто нажмите Enter.

Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

Добавление SSH-ключа в ssh-agent

Чтобы запустить ssh-агент введите следующую команду.

На экране отобразится похожая строка.

Agent pid 31724

Добавим свой закрытый ключ SSH в ssh-agent. Если вы создали свой ключ с другим именем (или добавляете существующий ключ с другим именем), замените в команде id_rsa на имя вашего файла закрытого (приватного) ключа.

Ключ будет успешно добавлен в ssh-агент.

Добавление ключа SSH в учетную запись GitHub

Мы сгенерировали у себя на компьютере закрытый ключ SSH и добавили его в ssh-агент. Теперь нам необходимо добавить SSH ключ в учетную запись GitHub.

Сейчас нам необходимо скопировать SSH ключ в буфер обмена.

Способов есть несколько, но я же вам предлагаю следующее решения для Windows 10: введите команду ниже.

Прямо в терминале вы увидите содержимое необходимого файла с ключем. Скопируйте его в буфер.

Теперь зайдите на вашу страницу GitHub » Settings.

GitHub SSH Windows 10

Перейдите во вкладку SSH and GPG keys и нажмите на кнопку New SSH key для добавления SSH ключа в вашу учетную запись GitHub.

Добавление SSH ключа для GitHub

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

В поле Key добавьте свой ssh-ключ, который вы скопировали в буфер обмена на предыдущем шаге.

Нажмите Add SSH key.

Добавление SSH ключа для GitHub

Для подтверждения вам потребуется ввести свой пароль от учетной записи GitHub.

На этом настройка SSH для вашего устройства завершена, теперь вы можете работать с git без ввода пароля от своей учетной записи.

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

Дата обновления статьи 17/06/2022 06:41

JavaScript: Window Location Checkbox Checked — Проверка Состояния Чекбокса ✔️

Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.

  • Настройка Gulp Babel
  • Микроразметка сайта
  • Как перенести сайт WordPress на хостинг
  • Настройте показ всего текста во время загрузки веб-шрифтов
  • Сниппеты в VS Code
  • Не удается проверить так как не задан исполняемый PHP-файл

ansible

Previous Story

Ansible: ввод sudo-пароля при выполнении playbook

mikrotik

Next Story

MikroTik Mesh – единая WiFi сеть

Latest from Blog

asterisk

Как настроить FreePBX с помощью Docker (сборка Docker-контейнера FreePBX). В этом посте мы расскажем о FreePBX , его функциях

1c linux

Продолжаем изучать работу с единым дистрибутивом платформы 1С:Предприятие для Linux, который появился в версии 8.3.20. В

1c linux

Установка и обновление сервера 1С:Предприятие после перехода на единый дистрибутив стала еще проще. Но хорошо, если у вас

asterisk

Asterisk — это бесплатный инструмент с открытым исходным кодом для создания/разработки коммуникационных приложений. Он был разработан Марком Спенсером из Digium

modoboa

Связка из Postfix и Dovecot плюс стандартный обвес из антивируса, антиспама и прочих утилит. Доменные имена

Listen to this article

С каждым новым выпуском Windows 10 все больше и больше полезных инструментов переносится из Linux. Во-первых, в Windows появилась подсистема для Linux, а теперь еще добавили встроенный клиент и сервер OpenSSH, который использует версию 7.5 OpenSSH. Хотя программное обеспечение Windows 10 OpenSSH в настоящее время находится в бета-версии, оно уже достаточно хорошо работает. Со встроенным в Windows 10 и включенным OpenSSH клиентом для подключения к серверу по SSH вам больше не потребуется использовать сторонний SSH-клиент (например, Putty).

В 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:windowssystem32OpenSSH.

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

Вы можете установить 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 [[email protected]]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 [email protected]

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

ssh [email protected] -p port

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

ssh [email protected]

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

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

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

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

ssh [email protected] -i "C:Usersusername.sshid_rsa"

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

set-service ssh-agent StartupType ‘Automatic’

Start-Service ssh-agent

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

ssh-add "C:Usersusername.sshid_rsa"

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

ssh [email protected]

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

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

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

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

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

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

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 без установки сторонних приложений и утилит.

Ну, и еще раз отметим, что по состоянию на сейчас OpenSSH еще не является полноценной функцией ОС Windows 10. PuTTy работает стабильнее и кроме того имеет более простой и понятный интерфейс. Но, как вы понимаете, как только нативный SSH в Microsoft доведут до ума, использование сторонних клиентов ограничат. Потому привыкать к OpenSSH так или иначе придется.

Источник: http://www.spy-soft.net/ и https://winitpro.ru/


Если Вам понравилась статья — поделитесь с друзьями

948 просмотров

Отказ от ответственности: Автор или издатель не публиковали эту статью для вредоносных целей. Вся размещенная информация была взята из открытых источников и представлена исключительно в ознакомительных целях а также не несет призыва к действию. Создано лишь в образовательных и развлекательных целях. Вся информация направлена на то, чтобы уберечь читателей от противозаконных действий. Все причиненные возможные убытки посетитель берет на себя. Автор проделывает все действия лишь на собственном оборудовании и в собственной сети. Не повторяйте ничего из прочитанного в реальной жизни. | Так же, если вы являетесь правообладателем размещенного на страницах портала материала, просьба написать нам через контактную форму жалобу на удаление определенной страницы, а также ознакомиться с инструкцией для правообладателей материалов. Спасибо за понимание.

Если вам понравились материалы сайта, вы можете поддержать проект финансово, переведя некоторую сумму с банковской карты, счёта мобильного телефона или из кошелька ЮMoney.

Понравилась статья? Поделить с друзьями:
  • Как запустить windows explorer через task manager
  • Как запустить sqlite в консоли windows
  • Как запустить unreal tournament 1999 на windows 10
  • Как запустить windows defender через cmd
  • Как запустить space siege на windows 10