Как подключиться по ssh из windows powershell

В классическом Windows PowerShell (до версии 5.1 включительно) для удаленного доступа через PSRemoting между компьютерами можно было использовать только протокол WinRM (WSMan, порт 5985/5986). В новых кроссплатформенных версиях PowerShell Core 7.x и 6.x вы можете использовать SSH в качестве транспорта для удаленного взаимодействия PowerShell между компьютерами. В этой статье мы рассмотрим, как настроить PSRemoting over SSH для подключения к Windows, Linux и macOS хостам.

Содержание:

  • Настройка SSH PowerShell Remoting в Windows
  • Настройка SSH Remoting для PowerShell в Linux
  • Примеры удаленного взаимодействия PowerShell через SSH

Настройка SSH PowerShell Remoting в Windows

Рассмотрим, как настроить SSH сервер на стороне клиента Windows для удаленного взаимодействия через PowerShell Remoting.

В Windows 10 (начиная с версии 1809) и Windows Server 2019+ доступен для установки встроенный OpenSSH сервер. Его можно установить с помощью следующей команды (для Windows 10 и 11):

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Также установите на компьютер последнюю версию PowerShell Core:

iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

Затем нужно включить автоматический запуск службы sshd:

Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd

Убедитесь, что Windows теперь слушает порт TCP/22 (SSH))

Get-NetTCPConnection -State Listen|where {$_.localport -eq '22'}

openssh сервер в windows слушает 22 порт TCP

Разрешите входящие SSH подключения в Windows Defender Firewall:

Enable-NetFirewallRule -Name *OpenSSH-Server*

Затем нужно открыть конфигурационный файл sshd_config (C:\ProgramData\ssh):

notepad $Env:ProgramData\ssh\sshd_config

Разрешите доступ по паролю, раскоментировав строку:

PasswordAuthentication yes

Также можно разрешить SSH доступ по ключам:

PubkeyAuthentication yes

Добавьте в файл следующую строку, которая будет обеспечивать запуск интерпретатора pwsh для удаленных SSH подключений:

Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo

Сохраните файл sshd_config, перезапустите службу sshd:

restart-service sshd

Настройка SSH Remoting для PowerShell в Linux

Теперь рассмотрим, как настроить хост с Linux для PowerShell Remoting over SSH.

Установите PowerShell Core в вашем дистрибутиве Linux согласно инструкции. В моем примере для Ubuntu 20.04 выполните команды:

sudo apt-get update -y
wget -q https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install powershell -y

Установите OpenSSH сервер (если не установлен):

sudo apt install openssh-server

Добавьте в файл /etc/ssh/sshd_config следующие строки:

PasswordAuthentication yes
Subsystem powershell /usr/bin/pwsh -sshs -NoLogo

Перезапустите службу ssh:

sudo systemctl restart sshd.service

Примеры удаленного взаимодействия PowerShell через SSH

Теперь вы можете подключиться к настроенному Windows или Linux хосту с помощью PowerShell over SSH. Для удаленного доступа к компьютерам через SSH используются те же командлеты PowerShell, что и для через WinRM,:

  • New-PSSession
  • Enter-PSSession – для запуска интерактивной PowerShell сессии с удаленных хостом;
  • Invoke-Command – для удалённого запуска отдельных команд или скриптов PS1.

По умолчанию все эти командлеты пытаются использовать Windows WinRM для подключения к удаленным компьютерам. Вам нужно использовать другие параметры подключения для использования SSH транспорта (доступны в PowerShell Core, поэтому нужно запускать из консоли
pwsh.exe
):

Параметры -HostName (вместо –ComputerName) и –UserName (вместо Credential) позволяют задать имя компьютера и пользователь для SSH подключения. С помощью параметра –KeyFilePath можно указать RSA ключи для SSH аутентификации (опционально). Также можно использовать параметр –SSHTransport для явного указания использования транспорта SSH для трафика PowerShell.

Попробуем интерактивно подключиться к удаленному компьютеру из Windows с помощью встроенного ssh клиента:

Enter-PSSession -HostName 192.168.13.202 -UserName kbuldogov

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

Enter-PSSession через SSH

Можно создать несколько постоянных PowerShell сессий к удаленным компьютерам и выполнять команды на них через SSH:

$session1 = New-PSSession -HostName 192.168.13.202 -UserName kbuldogov -SSHTransport
$session2 = New-PSSession -HostName 192.168.14.144 -UserName sysops -SSHTransport

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

Invoke-Command -Session $session1, $session2 -ScriptBlock { $PSVersionTable| select OS, PSVersion}| Select-Object PSComputerName, PSVersion, OS

Invoke-Command запуск удаленных команд в linux и windows через powershell remoting over ssh

В данном примере мы выполнили одновременно команду PowerShell на компьютере Windows и Linux и вывели результаты в консоль.

В PowerShell Core 7.1 и выше PSRemoting поддерживает второй прыжок (double hop) на другой удаленный компьютер из существующей сессии.

В переменной можно несколько SSH сессий и аутентифицироваться с помощью RSA ключей:

$sshConnections = @ HostName="winhost1"; UserName="winitpro\kbuldogov"; KeyFilePath="c:\users\kbuldogov\id_rsa" }, @{ HostName="sysops@ubuntu1"; KeyFilePath="c:\UserB\root\id_rsa" }
New-PSSession -SSHConnection $sshConnections

Основные ограничения PowerShell Remoting через SSH:

  • Не поддерживаются профили PowerShell;
  • В удаленных сессиях с Linux хостами не поддерживается sudo (при запуске появляется уведомление:
    sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
    );
  • Не поддерживается Just Enough Administration (JEA);

Как вы видите, настроить удаленно управление PowerShell Remoting через SSH намного проще, чем через WinRM HTTPS. Кроме того, такой способ подключения можно использовать для подключения через PowerShell к компьютерам в рабочей группе без добавления их в TrustedHost.

PowerShell Remoting over SSH это безопасная и простая замена WinRM. PSremoting over SSH поддерживается на всех платформах (как Windows и Linux), не требует открытия дополнительных портов (кроме TCP/22 SSH) и прост в настройке.

Table of Contents

PowerShell Remote Connection with SSH

The built-in SSH client appeared in Windows 10 and Windows Server 2019. It can be used to securely connect to Linux/UNIX servers, VMWare ESXi hosts and other devices instead of Putty. The native Windows SSH client is based on the OpenSSH port and is preinstalled in Windows starting from Windows 10 build 1809.

We can use SSH in PowerShell to establish a remote connection to another computer or server. This can be between Windows computers or Windows-Linux and vice versa.

The most common way to use SSH in PowerShell is as an SSH Client. Assuming that you keep your Windows up-to-date you should have SSH enabled by default. You can simply check it by opening PowerShell and type the following command:

# type ssh and press enter
ssh

# Result:
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-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]

You can check the OpenSSH client is installed or not:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
# Output
Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

If not (State: Not Present), you can install it using the following PowerShell command:

Add-WindowsCapability -Online -Name OpenSSH.Client*

Password-based authentication

With PowerShell open you can connect to a remote server or network device with a single command:

ssh <username>@<host_ip_address>

When you connect to a machine using SSH. For the first time you will need to accept the host’s key. Just type yes then hit Enter.

PS C:\> ssh [email protected]

The authenticity of host '10.10.6.22 (10.10.6.22)' can't be established.
ED25519 key fingerprint is SHA256:DFhYvYIS0O+SNI53un5Cbn4WB3YbxP6USGKbSp/XPEA.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.6.22' (ED25519) to the list of known hosts.

[email protected]'s password:
Welcome to Ubuntu 22.04.1 LTS (GNU/Linux 6.2.0-33-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

206 updates can be applied immediately.
1 of these updates is a standard security update.
To see these additional updates run: apt list --upgradable

Last login: Sun Oct  1 04:19:29 2023 from 10.10.5.52
leo@ub22:~$

If you have SSH running on a different port than the default port 22, then you can change the port number with the -p flag:

ssh <username>@<host_ip_address> -P <port_number>

#For example
ssh [email protected] -p 2222

Key-based authentication

Alternatively, we can authenticate using public-private keys. The advantage of this method :

  • More secure because using keys instead of clear text password.
  • Supports multiple encryption protocols.
  • Secure private keys using passphrase.
  • Automation authentication flow with ssh agent to manage all private keys.

Create a SSH Key Pair for SSH Authentication

1. First, launch a PowerShell window. 

2. Inside PowerShell, run the ssh-keygen command. The -t parameter tells OpenSSH what type of SSH key should be created. Here we go with the rsa type.

Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\admin/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\admin/.ssh/id_rsa
Your public key has been saved in C:\Users\admin/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:VW5ljf///nCFNw6ts450VISE/F+hx9dlgvtY9xZW1E0 admin@win11
The key's randomart image is:
+---[RSA 3072]----+
|          . +o+*E|
|           =.++.B|
|          . +.o==|
|         . ..o+**|
|        S    *=+O|
|            o =o*|
|           . +.oo|
|          . o oo.|
|           ..o .*|
+----[SHA256]-----+

3. A new folder named .ssh will be created within your user’s home folder (C:\Users<username>\.ssh). Two files have been created inside that folder. 

The difference between the two is the file extension (which is not shown by default in Windows Explorer).

  • The id_rsa file without extension is the private key – which you should guard like your own wallet. It can also be password-protected (as prompted in the ssh-keygen command above).
  • The id_rsa.pub file is the public counterpart of your private key. It needs to be installed on the target server(s) where you want to login using SSH.

Launch SSH agent (optional)

Note
Note: When creating a key pair, if you don’t use keyphrase to protect the private key. You can skip this section.

A SSH agent is a small program which runs in the background and loads your private key with the password into memory. This allows to use the ssh command without always having to enter the passphrase again.

You can check whether the service is already running or not:

PS C:\> Get-Service ssh-agent

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then enter the following commands in the administrator PowerShell window:

Get-Service ssh-agent | Set-Service -StartupType Manual
Start-Service ssh-agent
Get-Service ssh-agent
Status   Name               DisplayName
------   ----               -----------
Running  ssh-agent          OpenSSH Authentication Agent

The ssh-agent is now running. use ssh-add to load your own private key into the SSH agent:

ssh-add $env:USERPROFILE\.ssh\id_rsa
#Output
Identity added: C:\Users\admin\.ssh\id_rsa (admin@win11)

Install the public key on the remote server

1. Remember the mentioned public key? Now it is time to look at the contents. Using the Windows Explorer, navigate to your .ssh folder. Or you can use Get-Content cmdlet to get its content.

Get-Content $env:USERPROFILE\.ssh\id_rsa.pub

2. Open the id_rsa.pub file with a text editor. Notepad will do. This shows the content of the public key, which is a long line of a text:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5786CyQZizFqWs/YLCOFcougR1wZBG2yHFjswSACeJMO8DV3lGPjmOXMLf5z2QQy1mZHUW7t9J7EWzDj54lr7VNd+CwW2Jo0inRAP3+IzxcELwYBwJmfSj+KbWMsJF7Q8zden4t8G1jlFXE1Md8O3JUH4MyM4W7Ze9QmOy1fp8OftCyx4LPTWgbC1eqtwmck5AZgrfa8039E61LH+dKapcvgj5DgAE8Kco8zg/2RZBGrRWfa8FANr3fcfdaFN0mH3xQpcgO8/EfJhzTDmBVlFa2I5pkAFHHMvjcSWzK9fUzTIaPYWm+nNTQl/KSuW1kZi3sVfzcfCXEkUrCKAqc1OOQK8nvCm4578yCpb0gS6ge/VLGp5ZpUeOsvtN0JckGT6MBSr7VfheVABueflCm/hj9Nmouvf/oQfdjs4g+too99+ZJpIv6IWJHY4Kd2HettwnvwCam97KaEKEvIpyTQTjMhnQXPCKsPAk2sqH1VM9CwfyPfDoHZv4XqBLK3j+QM= admin@win11

3. SSH to the remote server. This time, you still need to use password authentication.

4. Create a new file named ~/.ssh/authorized_keys on the remote server using your favorite text editor.

mkdir ~/.ssh
nano ~/.ssh/authorized_keys

Note
Note: ~ stands for user’s home folder

5. Copy content of the public key from notepad to the newly created file.

6. Check then enable public key Authentication if it not enabled yet. The settings for OpenSSH server is located in /etc/ssh/sshd_config.

sudo nano /etc/ssh/sshd_config

7. Finally, restart the SSH service.

sudo systemctl resrart ssh

Connect to a remote SSH server

Now that we have created a key, enabled ssh agent and placed the public key on the target server, we can initiate a ssh connection.

With PowerShell SSH, you can access and manage remote systems from virtually anywhere. In addition, SSH offers detailed logging functions that allow activities on the server to be comprehensively monitored and tracked.

What are the requirements for PowerShell SSH?

Integrating SSH in Windows PowerShell gives you the ability to establish SSH connections to remote systems and execute SSH commands in a PowerShell script. This makes it a lot easier to manage and automate tasks in distributed IT infrastructures, especially in a heterogeneous environment where there are both Windows and non-Windows systems.

Here are the requirements to use SSH in PowerShell:

  • PowerShell installation: Make sure that PowerShell v6 or higher is installed on your local computer. PowerShell is usually pre-installed in Windows, but you need to check that you are using a version that supports SSH.
  • SSH client: You need an SSH client in your PowerShell environment to establish SSH connections. OpenSSH is available by default in Windows 10/11 and Windows Server 2019. If you are using an older version of Windows, you may need to install OpenSSH manually.
  • SSH server: The SSH server is the target server that you want to connect to. This can be a Linux server, a network device or another SSH-capable host.
  • Network access: Your local computer should have access to the network and be able to reach the remote SSH server. Port 22 must be open for SSH in the firewall rules.
  • PowerShell modules: There are PowerShell modules that have been specially developed for the use of SSH, such as the “PSSession” or “Posh-SSH” module. You should check that the corresponding module is installed on your system in order to be able to use SSH functionality in PowerShell.
  • Authorizations: You need administrator or elevated privileges and a password or SSH key to establish SSH connections from your local computer and access the remote server.

Step-by-step instructions on how to use PowerShell SSH

Before you can use Secure Shell (SSH) in PowerShell, you must set up the OpenSSH server. You can then start the PowerShell SSH session and execute commands on the remote system.

Step 1: Install OpenSSH

Click on the start menu or enter “PowerShell” in the search bar. Select Run as administrator. This opens the Windows PowerShell. You can use the following PowerShell command to install the OpenSSH feature on your Windows computer:

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

powershell

Step 2: Start OpenSSH service

Once the installation is complete, you can start the OpenSSH service:

Start-Service sshd

powershell

You can check whether the OpenSSH service is running:

Get-Service sshd

powershell

The Running status indicates that sshd is running properly.

PowerShell: SSH server service

Get-Service sshd checks the execution of the SSH service.

Step 3: Start SSH server service automatically

To activate the OpenSSH server service every time Windows is restarted, you can enter the following command:

Set-Service -Name sshd -StartupType 'Automatic'

powershell

Step 4: Customize firewall

If Windows firewall is active, you should add a rule to allow SSH traffic on Port 22 (the default SSH port).

New-NetFirewallRule -Name 'OpenSSH-Server' -DisplayName 'OpenSSH Server' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

powershell

Step 5: Establish an SSH connection

You can now log in with your SSH server from another device. To do this, open PowerShell on your client PC and enter the SSH command with the username and server address.

ssh username@servername

powershell

Replace “username” with your SSH username and “servername” with the IP address or hostname of the remote server. When you start the command, you will be prompted to enter your SSH password unless you are using the SSH key for authentication.

PowerShell: SSH login

Enter the SSH password

Step 6: Work in the SSH session

Once you have established an SSH connection, you can execute commands on the remote server as if you were physically logged on to the server. To end the SSH session and return to the local PowerShell, you can use the exit command.

There are a number of SSH commands in PowerShell. The command pwd stands for “print working directory” and shows you the current working directory, for example:

PowerShell SSH commands using PWD as an example

Example for SSH commands in PowerShell

Here is a list of commands that you can use in PowerShell SSH:

  • ls/dir: Displays the contents of a directory
  • cd: Changes the directory on the remote server
  • touch/New-Item: Creates a new file
  • rm/Remove-Item: Deletes files or directories
  • mv/Move-Item: Moves or renames files and directories
  • useradd: Adds a new user
  • scp: Transfers files between client and server

You can find more commands in our overview of PowerShell commands.

Was this article helpful?

Ten years ago, nobody would have thought that Secure Shell (SSH) connections would work from a Windows-native program. Yet – here we are.

SSH commands communication works just fine inside a Windows’ PowerShell window, as OpenSSH has been integrated into Windows 10 back in 2018.

Create a SSH key

First launch a PowerShell window. Inside PowerShell, run the ssh-keygen command. The -t parameter tells OpenSSH what type of SSH key should be created. Here we go with the rsa type.

PS C:\Users\ck> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\ck/.ssh/id_rsa): [enter]
Created directory 'C:\Users\ck/.ssh'.
Enter passphrase (empty for no passphrase): [enter personal password]
Enter same passphrase again: [enter personal password]
Your identification has been saved in C:\Users\ck/.ssh/id_rsa.
Your public key has been saved in C:\Users\ck/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:SvV[.......................] ck@DESKTOP-MGFCEDC
They key's randomart image is:
+--- [RSA 3072]----+
|      [...]       |
+----[SHA256]------+
PS C:\Users\ck>

This results in a new folder «.ssh» in your own user folder. Inside this .ssh folder, two files have been created:

OpenSSH keys created in Windows 10

OpenSSH keys created in Windows 10

The difference between the two is the file extension (which is not shown by default in Windows Explorer).

  • The «id_rsa» file without extension is the private key – which you should guard like your own wallet. It should also be password-protected (as prompted in the ssh-keygen command above).
  • The «id_rsa.pub» file is the public counterpart of your private key. It needs to be installed on the target server(s) where you want to login using SSH.

Launch SSH agent

A SSH agent is a small program which runs in the background and loads your private key with the password into memory. This allows to use the ssh command without always having to enter the passphrase again.

Note: Pageant is another widely used and well known ssh agent on Windows.

You can check whether the service is already running or not:

PS C:\Users\ck> Get-Service ssh-agent

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

To enable and start the ssh-agent service, open another PowerShell window (run as Administrator):

Start Windows PowerShell as administrator

Then enter the following commands in the Administrator PowerShell window:

PS C:\WINDOWS\system32> Get-Service ssh-agent | Set-Service -StartupType Manual
PS C:\WINDOWS\system32> Get-Service ssh-agent

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent


PS C:\WINDOWS\system32> Start-Service ssh-agent
PS C:\WINDOWS\system32> Get-Service ssh-agent

Status   Name               DisplayName
------   ----               -----------
Running  ssh-agent          OpenSSH Authentication Agent

The ssh-agent is now running.

Back in your first PowerShell window (as your own user), use ssh-add to load your own private key into the SSH agent:

PS C:\Users\ck> ssh-add .\.ssh\id_rsa
Enter passphrase for .\ssh\id_rsa: [enter personal password]
Identity added: .\ssh\id_rsa (ck@DESKTOP-MGFEDC)

Install the public key on the remote server

Remember the mentioned public key? Now it is time to look at the contents. Using the Windows Explorer, navigate to your .ssh folder.

SSH keys in Windows

Open the id_rsa.pub file with a text editor. Notepad will do. This shows the content of the public key, which is a long line of a text:

SSH public key in Notepad

SSH public key in Notepad

Send this key (or the content) to the server administrator – or if you have access to the server already, place the line into the file ~/.ssh/authorized_keys on the remote server.

Note: ~ stands for user’s home folder

Connect to a remote SSH server

Now that we have created a key, enabled ssh agent and placed the public key on the target server, we can initiate a ssh connection:

PS C:\Users\ck> ssh -l ck 192.168.15.20
The authenticity of host '192.168.15.20 (192.168.15.20)' can't be established.
ECDSA key fingerprint is SHA256:+F4MZdFhziAjwqwgM50G8186ef2qMbgEQS+Ri8ciWgo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.15.20' (ECDSA) to the list of known hosts.
Last login: Fri Mar 12 16:46:09 2021
ck@mintp ~ $ uname -a
Linux mintp 5.8.0-63-generic #71~20.04.1-Ubuntu SMP Thu Jul 15 17:46:08 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

The optional -l parameter defines the user on the remote server. This might not always be the same user as you are running on your Windows machine. By using the -l parameter you can define another user name. By default, ssh will assume the same user name as you are currently logged in.

Another often used optional parameter is -p. It defines a different SSH port (default is 22).

If this is the first time you are connecting to a remote server, ssh will prompt you to verify the remote host’s fingerprint. You can do so by entering yes at the prompt.

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

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

В прошлой статье я обещал рассмотреть механизм удаленного подключения с Windows на серверы под управлением *nix, и наоборот при помощи PowerShell. Обещанного обычно ждут три года, но я успел чуть раньше. Что ж, если хочется с верного макбука управлять гетерогенной инфраструктурой, или наоборот ― с Surface Pro рулить Linux-серверами без всяких putty, ― прошу под кат.

Microsoft Loves Linux

Еще в 2015 году Microsoft торжественно объявила о запуске программы «Microsoft Linux». Сюда вошла как банальная поддержка гостевых *nix-like OS на Hyper-V, так и встроенная в Windows 10 Ubuntu и возможность запуска в Docker продуктов Microsoft, таких как SQL Server.

Компания также опубликовала исходный код PowerShell, что позволило запускать «Ракушку Мощи» не только на Windows. Из-под одноименного аккаунта на Github, помимо исходного кода, выложены и бинарники под большинство современных систем (лицензия MIT).

Это позволяет настроить удаленное управление с помощью единого инструмента ― PowerShell. Помимо подключения к консоли компьютера, можно запускать отдельные команды, в том числе и на нескольких серверах одновременно. Довольно удобно для автоматизации задач администрирования, таких как массовое изменение настроек, инвентаризация, сбор логов.

Порой удобно совмещать традиционные консольные команды со вставками PowerShell:

cat /etc/passwd | ConvertFrom-Csv -Delimiter ':' -Header Name,Passwd,UID,GID,Description,Home,Shell | Sort-Object Name | Format-Table

Для подключения к Windows-машинам при помощи PowerShell используется протокол WS-Man. Для GNU\Linux привычен SSH. Так как сегодня становятся универсальными оба протокола, разберем их подробнее.

PowerShell 6.0 под Windows и *nix, пока еще находится в бете. Поэтому не рекомендую без хорошего тестирования применять на боевых серверах описанное ниже.

Магомед не идет к горе

Когда технология удаленного доступа при помощи PowerShell только набирала обороты, единственным универсальным способом подключения к разным системам был протокол WS-Man. Для тестового стенда я взял Windows Server 2016 и Centos 7, для которых и буду настраивать возможность удаленного подключения и выполнения команд при помощи этого протокола.

Для начала установим на Centos свежий PowerShell:

curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/microsoft.repo

yum install -y powershell

pwsh

После установки появилась возможность запускать привычные Windows-администратору командлеты. Например, посмотрим версию PS и получим список запущенных процессов командлетами $PSVersionTable и Get-Process:

Работаем в консоли PowerShell на CentOS.

Чтобы подключаться к Linux-машине с консоли Windows, нам понадобится установить и настроить:

  • OMI (Open Management Infrastructure) ― адаптация WMI, которую также можно использовать для управления компьютерами с ОС, отличными от Windows;
  • PSRP (PowerShell Remoting Protocol) ― библиотека, необходимая для удаленного подключения PowerShell.

Подробно с работой и эволюцией OMI и PSRP можно ознакомиться в отличном материале от Matt Wrock, я же просто установлю OMI командой:

yum install omi

Далее нужно настроить порты и аутентификацию в конфигурационном файле /etc/opt/omi/conf/omiserver.conf, после чего перезапустить сервер командой:

/opt/omi/bin/service_control restart

Для упрощения эксперимента я не буду настраивать ни NTLM-аутентификацию, ни Kerberos. Еще и шифрование отключу ― разумеется, в боевой среде делать этого не стоит. Для включения текстовой аутентификации и шифрования на стороне Windows в работе winrm достаточно выполнить следующие команды:

winrm set winrm/config/client/auth @{Basic="true"}
winrm set winrm/config/client @{AllowUnencrypted="true"}
winrm set winrm/config/service/auth @{Basic="true"}
winrm set winrm/config/service @{AllowUnencrypted="true"}

После настройки можно проверить работу OMI из консоли Windows:

winrm enumerate http://schemas.microsoft.com/wbem/wscim/1/cim-schema/2/OMI_Identify?__cimnamespace=root/omi -r:http://server:5985 -auth:Basic -u:root -p:"password" -skipcncheck -skipcacheck -encoding:utf-8 -unencrypted

Подключаемся к CentOS из cmd.

Теперь проверим работу обратным подключением ― из Linux к Windows:

/opt/omi/bin/omicli ei root/cimv2 Win32_Environment --auth Basic --hostname server -u username -p password --port 5985 

… а затем с CentOS подключаемся к Windows.

После того, как WMI\OMI заработал, нужно установить и настроить PSRP. К сожалению и вопреки инструкции, бинарник отсутствует. Библиотеку пришлось компилировать, долго и нудно исправляя возникающие ошибки зависимостей:

yum groupinstall 'Development Tools'
yum install openssl-devel pam-devel
git clone --recursive [https://github.com/PowerShell/psl-omi-provider.git](https://github.com/PowerShell/psl-omi-provider.git)

cd psl-omi-provider/
make release
rpm -ihv target/Linux_ULINUX_1.0_x64_64_Release/psrp-1.4.1-0.universal.x64.rpm

Теперь мы сможем подключаться с Windows на Linux и наоборот при помощи PowerShell. Начнем с Windows на Linux:

$cred = Get-Credential

#пропустим проверку сертификата для нашей тестовой лаборатории
$o = New-PSSessionOption -SkipCACheck -SkipRevocationCheck -SkipCNCheck

#выполнение команды:
Invoke-Command -ComputerName server -ScriptBlock { Get-Process } -Authentication Basic -SessionOption $o -Credential $cred -UseSSL | Select-Object -First 5

#подключение к консоли
Enter-PSSession -ComputerName 'server' -Credential $cred -Authentication basic -UseSSL -SessionOption $o

С Windows на Linux.

Аналогичным образом можно провести и обратное подключение.

Invoke-Command можно «натравить» на список компьютеров, и с рабочей станции Windows создать пользователя на всех серверах Linux командой вида:

 Invoke-Command -ComputerName server1,server2,server3  -ScriptBlock { adduser admin;echo admin:password | chpasswd
 }

Надо сказать, что способ не самый удобный и эффективный. Минусов добавляет компиляция библиотек, разнообразные баги ― например, на момент написания статьи PSRP не позволял нормально подключиться из Linux в Windows.

Да и сами разработчики рекомендуют не плясать вокруг WS-Man, а обратиться к проверенному способу ― SSH. Что ж, попробуем и его.

Гора идет к Магомету

На этот раз машина с Windows получит чуть больше специфической подготовки ― нужно установить свежий PowerShell и OpenSSH.

После можно проверить синтаксис командлета New-PSSession. Если все произошло как надо, то командлет, помимо привычного параметра ComputerName, будет поддерживать и HostName.

PowerShell 6.0.0-beta.9 и обновленный синтаксис командлета.

Установка OpenSSH описана в отдельной инструкции.

Но под спойлером вы найдете все основные моменты.

Качаем последний релиз или используем пакет из репозитория Chocolatey. Все это разархивируем в \Program Files\OpenSSH.

В консоли с правами администратора переходим в папку с разархивированным содержимым и запускаем установку командой:

powershell -ExecutionPolicy Bypass -File install-sshd.ps1

Теперь генерируем ключи:

.\ssh-keygen.exe -A
.\FixHostFilePermissions.ps1 -Confirm:$false

В тестовой среде мы будем использовать парольную аутентификацию, поэтому стоит убедиться что она включена в файле sshd_config:

```bash
PasswordAuthentication yes
```

Если вы также хотите автоматически запускать PowerShell при подключении по SSH, то в параметре subsystem нужно прописать путь к желаемой версии PS:

Subsystem   powershell C:/Program Files (x86)/PowerShell/6.0.0-beta.9/pwsh.exe -sshs -NoLogo -NoProfile

Для работы клиента SSH нужно добавить директорию в %PATH% любым удобным способом. Например, таким:

setx path "%path%;C:\Program Files\OpenSSH"

Остается только настроить и запустить службы:

Set-Service sshd -StartupType Automatic
Set-Service ssh-agent -StartupType Automatic
net start sshd

После установки уже можно наслаждаться подключением к серверу Windows по ssh.

C Windows через Putty на Linux, с Linux обратно на Windows по SSH.

На достигнутом останавливаться не будем и перейдем к настройке Linux. При настройке сервера SSH по умолчанию достаточно прописать PowerShell в Subsystem:

Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile

Теперь проверим подключение через командлет New-PSSession и Invoke-Command.

Сначала Windows:

Работаем из PowerShell с Linux-сервером.

Теперь подключимся из Linux к Windows:

Работаем из PowerShell с Windows-сервером.

В отличие от WS-Man, SSH настраивается намного проще и работает стабильнее. Да и беспарольное подключение по ключам настраивать привычнее.

В хозяйстве пригодится

С однозначным «советом потребителю» все опять сложно: SSH проще в настройке и стабильнее, но WS-Man использует API и позволяет применять инструменты вроде JEA. На боевых серверах использовать WS-Man я бы не стал однозначно, а вот реализация OpenSSH в Windows как сервера, так и клиента мне понравилась. Для самопальной автоматизации вполне подойдет даже без PowerShell.

В любом случае, границы между Linux и Windows хоть и медленно, но начинают стираться, что безусловно радует.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как установить сетевой принтер на windows 10 в локальной сети windows
  • Windows explorer 10 remove
  • Какие службы отключить в windows 10 для улучшения производительности ноутбука
  • Файловый менеджер для windows обзор
  • Spotify widget windows 11