Ssh with windows powershell

Using SSH with PowerShell

Microsoft announced that they will support SSH using PowerShell in Windows 10. Until now Microsoft has a good solution for this, there is a third party solutions called Posh-SSH. To use SSH in PowerShell you first have to install the Posh-SSH PowerShell Module from the PowerShell Gallery. Make sure you are running Windows 10 or you have the Windows Management Framework 5 installed.

If you want to use SSH with PowerShell 6, you read my blog here: Using SSH with PowerShell 6

You can now find the Posh-SSH Module and install it:

You now have several PowerShell SSH cmdlets available:

Now you can create a new SSH Session using the following cmdlet (Password based authentication)

You can now simply run commands against this session or use SCP to copy files.

I hope this helps you using SSH with PowerShell. If you have any questions, please write it in the comments. Also check out my other blogs and see how SSH is integrated in Windows 10.

About the Author / Thomas Maurer

Stop typing PowerShell credentials in demos using PowerShell SecretManagement

Azure Advisor: How to Improve performance, security, and reliability of your Azure VMs

Passed AZ-600 Azure Stack Hub Operator Associate Certification Exam

SC-900 Study Guide Microsoft Security, Compliance, and Identity Fundamentals

25 Replies to “Using SSH with PowerShell”

Nice, very helpful. Now the questions is how can I user to connect to a windows server using ssh?

The real question is when will this support Kerberos authentication?

Does this also works with com ports?
I know I can use putty.
But I want to use this.
Because PowerShell.

To be honest, I haven’t tried it with com ports 😉

Can connect using buty bash.exe but not the module

New-SSHSession : A non-recoverable error occurred during a database lookup
At line:12 char:1
+ New-SSHSession -ComputerName $ipaddress -Credential $psCred
+

+ CategoryInfo : InvalidOperation: (Renci.SshNet.SshClient:SshClient) [New-SSHSession], SocketException
+ FullyQualifiedErrorId : SSH.NewSshSession

what if my pc is only windows 7. who can i use SSH in powershell

You can use this same guide but you just need to make sure you have PowerShell v5 installed on your Windows 7 PC

great. really nice.
how to exec. .bash scripts

shahrzad, did you install bash in windows yet? After you do that, you have full access to running any linux command.
https://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/

question
exist a way to implement like
New-SSHSession -ComputerName “soaad1-q” -Credential ( user username password passwd )

Читайте также:  Intel linux graphics ubuntu

This so called powershell must be the biggest joke in computer history. It has no, nada,zip, nil resemblance with a real shell.

Powershell is Awesome, If you don’t know how to use it. get-help

Linux subsystem on Windows so that you can run Linux commands and programs on Windows. It’s like building a mansion on a cliff. Eventually it’s going to fall because the cliff is unstable.
It is also not every command from Linux. The implementation is still limited for both commands and apps. In fact most apps will not run in this as there is still a substantial difference for how a true Linux OS performs compared to what this truly offers. Lots of hype here.
Even Jack Hammons at MS has written that this subsystem was geared towards bash and cmd line tools and that it doesn’t even support any desktops or apps. In fact, if an app does run, it’s largely because their required libraries were ported to Windows as well. In many cases, this has not happened. In the end, you are still stuck with the inherent limitations of Windows for this lipstick on a pig.
IF MS wants to do something good, create a gui for Linux or pull an apple, dump your core and port your ui to Linux. Lindows/Winux may actually be something that I’d consider from MS.

Back to the original item here of the article. You fail to mention the need for installation of and access for additional tools like nuget which is required with these steps. Nuget if you(the reader) don’t know is the package manager for MS’s developer tools and do you really want that on a potentially production server?! That to me just screams one more way for a Windows server to be hacked.
Yes PowerShell in general is pretty good if you are running Windows. But given the choice, and considering the impending explosion of PowerShell based malware, I’ll still stick to *nix and native shells there.

Why is it not install on my Windows 10 PC? It is a Windows 10 home 64bit.

Can this be used to build a tunnel instead of using
plink -R :127.0.0.1:80 @subdomain.domain.com -i private_ssh.ppk

I haven’t tried it with the PowerShell Module. But with WSL (Windows Subsystem for Linux) it works:

For PowerShell version 2 compatibility, you can install the 1.9 or earlier versions of https://www.powershelladmin.com/wiki/SSH_from_PowerShell_using_the_SSH.NET_library “SSH-Sessions” or “SSHSessions” (someone stole the name on powershellgallery). It’s here in the PowerShell gallery: https://www.powershellgallery.com/packages/SSHSessions/2.1.3 – it is also quite a bit less “bloat” than Posh-SSH. Two weeks ago I was at spot two on google for “powershell ssh module” with the PS gallery link, but now I’m relegated to just about nowhere, so I’ll post here for self promotion (rarely hurts). https://www.powershellgallery.com/packages/SSHSessions/

Or you could always turn to the light-weight alternative: SSH-Sessions/SSHSessions, written by yours truly.
Link is here: https://www.powershelladmin.com/wiki/SSH_from_PowerShell_using_the_SSH.NET_library
And PowerShell Gallery link is here (the last PSv2-compatible version in old style is -RequiredVersion 1.9): https://www.powershellgallery.com/packages/SSHSessions/ – GitHub here: https://github.com/EliteLoser/SSHSessions – Thanks.

Читайте также:  Windows не видит новых флешек

Can I use keys instead of using credentials?

Windows 10 SSH vs PuTTY: что выбрать?

Одним из наиболее распространенных способов связи между компьютерами, в частности машинами Linux и веб-серверами, является SSH. Когда дело доходит до установления такого рода связи в Windows, по умолчанию выбирается установка PuTTY.

Однако благодаря Windows PowerShell вам может больше не понадобиться PuTTY. Давайте посмотрим, как настроить SSH-доступ в Windows 10 и могут ли новые инструменты вытеснить PuTTY.

Как установить SSH в Windows 10 (кратко)

Установка функциональности SSH в Windows 10 PowerShell достаточно проста, но пункты меню для нее несколько скрыты. Вот что вам нужно сделать:

  1. Откройте Настройки.
  2. Просмотр приложений.
  3. Перейти к управлению дополнительными функциями.
  4. Нажмите Добавить функцию.
  5. Выберите OpenSSH Client.
  6. Подождите, затем перезагрузите компьютер.

После этого вы можете установить SSH-соединение с другими совместимыми компьютерами. Если SSH-сервер был установлен и настроен на удаленном компьютере, можно установить соединение.

Подробная инструкция по установке

Реализация SSH в Windows 10 в PowerShell является версией проекта OpenSSH. Вы можете найти страницу проекта на GitHub.

Вы можете обнаружить, что SSH уже установлен на вашем компьютере с Windows 10 (он был включен в обновление за апрель 2018 года), но если нет, его можно легко добавить.

Чтобы проверить, откройте меню «Опытный пользователь» (щелкните правой кнопкой мыши Пуск или нажмите клавишу Windows + X ) и выберите Windows PowerShell. Здесь введите команду «ssh». Если SSH еще не установлен, вы увидите такой экран:

Исправить это достаточно просто. Нажмите клавишу Windows + I, чтобы открыть представление «Настройки», затем перейдите в «Приложения» и найдите «Управление дополнительными функциями . Нажмите здесь, затем найдите запись с пометкой «OpenSSH».

Если вы не видите его, нажмите Добавить функцию, а затем прокрутите вниз, пока не увидите OpenSSH Client. Нажмите, чтобы развернуть и просмотреть описание.

Когда вы будете готовы, нажмите Установить, чтобы добавить его на свой компьютер. Через несколько мгновений будет установлен новый SSH-клиент для Windows PowerShell. Стоит перезагрузить Windows, чтобы убедиться, что приложение установлено правильно.

Замечание о приложении SSH Server

Стоит подчеркнуть тот факт, что вы также можете установить SSH-сервер. Хотя маловероятно, что Microsoft разрешит любую форму универсального удаленного администрирования через SSH, использование его в качестве опции, тем не менее, полезно.

Чтобы установить это, повторите описанные выше шаги, выбрав OpenSSH Server .

Использование SSH в Windows PowerShell

После того, как SSH установлен и работает, вы можете использовать его для связи с другим компьютером. Например, вы можете использовать его для доступа к Raspberry Pi (один из нескольких вариантов об этом маленьком компьютере).

Использование простое. В PowerShell введите команду ssh, затем имя пользователя для учетной записи на удаленном устройстве и его IP-адрес.

Например, чтобы подключиться к моей коробке Raspberry Pi под управлением RetroPie, я использовал:

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

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

SSH-функции PowerShell и PuTTY

PuTTY долгое время был предпочтительным выбором для SSH на Windows. Будь то управление веб-серверами, доступ к Интернету вещей, устройства или удаленное администрирование ПК с Linux, это легкое и простое в использовании приложение.

Читайте также:  Очистка истории команд linux

Одной из причин стойкости PuTTY является широкий выбор функций. Итак, может ли SSH в Windows PowerShell конкурировать с PuTTY?

Ну, с точки зрения обеспечения функциональности SSH, да, это может. Вы можете узнать, как использовать некоторые расширенные функции SSH в Windows 10, введя команду ssh:

Результирующий список опций обрисовывает в общих чертах особенности. Например, вы можете указать порт:

Хотя вы можете связать адрес с OpenSSH в Windows, вы ограничены количеством адресов, которые можете сохранить.

Есть причина, почему PuTTY остается популярным. Приложение не только позволяет сохранять (и называть) ваши соединения, но и поддерживает соединения по Telnet, Serial и другим протоколам. Внешний вид PuTTY также настраивается, его можно быстро запустить с рабочего стола. В общем, PuTTY — это надежная утилита, которая обрабатывает практически все, что вы можете на нее бросить.

Почему SSH, когда вы можете использовать Linux?

Хотя удаленное управление Linux через SSH может быть жизненно важным, вам может даже не понадобиться SSH. В Windows 10 теперь есть подсистема Linux и командная строка в стиле Bash.

Это означает, что вы можете легко вводить команды Linux и получать реалистичные ответы. Хотя это может быть не идеально для всех сценариев, если вам нужен доступ к Linux для обучения в колледже или для обучения и у вас нет доступа по SSH (независимо от приложения) к устройству Linux, это может быть идеальным вариантом.

Конечно, это не единственный вариант. Если вам нужно практиковать команды Bash в Windows, вы всегда можете настроить виртуальную машину. Просто установите дистрибутив Linux в него и (если разрешить аппаратное обеспечение) у вас есть готовая к использованию ОС Linux.

Не пора ли отказаться от PuTTY в Windows 10?

SSH прост в использовании в Windows 10 PowerShell. Тем не менее, отсутствие функций, а также необходимость загрузки еще нескольких щелчков означает, что вы можете предпочесть использовать PuTTY. В любом случае, тот факт, что в Windows 10 есть два хороших варианта SSH, стоит отметить.

Setup PowerShell SSH Remoting in PowerShell 6

With PowerShell version 6, Microsoft introduced PowerShell Remoting over SSH, which allows true multiplatform PowerShell remoting between Linux, macOS and Windows. PowerShell SSH Remoting creates a PowerShell host process on the target machine as an SSH subsystem. Normally, PowerShell remoting uses WinRM for connection negotiation and data transport, however WinRM is only available on Windows based machines.

There are also some downsides to it. SSH-based remoting doesn’t currently support remote endpoint configuration and JEA (Just Enough Administration). It is also important to understand, that this is not just another PowerShell SSH client.

Use SSH Transport with PowerShell Remoting

To use PowerShell remoting with SSH you can use the same cmdlets, you know from PowerShell remoting with WinRM.

  • New-PSSession
  • Enter-PSSession
  • Invoke-Command

There are 3 new parameters for these cmdlets, if you are using PowerShell SSH remoting.

  • -HostName (Instead of -Computername, you define the SSH target)
  • -UserName (Instead of -Credentials you use the -UserName parameter)
  • -KeyFilePath (If you are using SSH key authentication you can use the -KeyFilePath parameter to point to the key file)
Оцените статью