Хочу адаптировать заметку по управлению через Ansible на Ubuntu 22.04 Server доменной инфраструктурой на базе Windows Server 2012 R2 Std (srv-dc01). Цель получить еще один инструмент взаимодействия. Просто я на одной из работ делал такое взаимодействие, но тогда использовал Ubuntu 18.04 Desktop/Server и все было хорошо.

Текущий стенд на базе виртуализации Debian 10 + Proxmox 6.4

Srv-us2204a.polygon.local

  • OS: Ubuntu 22.04 Server
  • Roles: Сервис Ansible

Srv-dc01.polygon.local

  • OS: Windows Server 2012 R2
  • Roles: Active Directory, DNS, DHCP

Шаг №1: На систему с осью Ubuntu 22.04 Server устанавливаю пакет Ansible:

ekzorchik@srv-us2204a:~$ sudo apt-add-repository ppa:ansible/ansible -y
ekzorchik@srv-us2204a:~$ apt-cache show ansible | grep Version
Version: 6.3.0-1ppa~jammy
Version: 2.10.7+merged+base+2.10.8+dfsg-1
ekzorchik@srv-us2204a:~$
ekzorchik@srv-us2204a:~$ sudo apt-get install -y ansible

Шаг №2: Устанавливаю пакет для использования модуля winrm:

ekzorchik@srv-us2204a:~$ sudo pip install http://github.com/diyan/pywinrm/archive/master.zip#egg=pywinrm
ekzorchik@srv-us2204a:~$ sudo find / -name "winrm"
/usr/lib/python3/dist-packages/winrm
/usr/local/lib/python3.10/dist-packages/winrm
ekzorchik@srv-us2204a:~$

Шаг №3: Теперь чтобы подключить к Server 2012 R2 Standard (Role: DC) нужно на srv-dc01 авторизоваться с правами Domain Admins, запустить консоль командной строки с правами Администратора и:

Win + X -> Command Prompt (Admin)

C:\Windows\system32>powershell -command "set-executionpolicy remotesigned"

Шаг №4: После запускаю скрипт, который и создает правила в Firewall: Allow 5986/TCP, либо я в Windows системах отключаю брандмауэр:

Win + X -> Command Prompt (Admin)

C:\Windows\system32>

C:\Windows\system32>netsh advfirewall set allprofiles state off
Ok.
C:\Windows\system32>cd /d c:\Soft

c:\Soft>powershell -file .\ConfigureRemotingForAnsible\ConfigureRemotingForAnsible.ps1
File C:\Soft\ConfigureRemotingForAnsible\ConfigureRemotingForAnsible.ps1 cannot
 be loaded. The file C:\Soft\ConfigureRemotingForAnsible\ConfigureRemotingForAn
sible.ps1 is not digitally signed. You cannot run this script on the current sy
stem. For more information about running scripts and setting execution policy,
see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
    + CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecord
   Exception
    + FullyQualifiedErrorId : UnauthorizedAccess

c:\Soft>

хм странно, но ведь команда выше set-executionpolicy отработала, а если

PS C:\Windows\System32> set-executionpolicy unrestricted

Существует четыре уровня безопасности:

  • Restricted (Запрещено, по умолчанию) Сценарии не запускаются.
  • Allsigned (Все подписанные) Запускаются только подписанные сценарии.
  • RemoteSigned (Удаленные подписанные) Разрешен запуск локальных сценариев, прочие сценарии должны быть подписаны.
  • Unrestricted (Без ограничений) Запускаются все сценарии.

Повторяю, выполнение скрипта:

PS C:\Soft> .\ConfigureRemotingForAnsible\ConfigureRemotingForAnsible.ps1
Security warning
Run only scripts that you trust. While scripts from the internet can be useful,
 this script can potentially harm your computer. If you trust this script, use
the Unblock-File cmdlet to allow the script to run without this warning
message. Do you want to run
C:\Soft\ConfigureRemotingForAnsible\ConfigureRemotingForAnsible.ps1?
[D] Do not run  [R] Run once  [S] Suspend  [?] Help (default is "D"): R
Self-signed SSL certificate generated; thumbprint: D8CE58F78A4DEB119D76DAF6C80A
A818FDF2BE53
wxf                 : http://schemas.xmlsoap.org/ws/2004/09/transfer
a                   : http://schemas.xmlsoap.org/ws/2004/08/addressing
w                   : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
lang                : en-US
Address             : http://schemas.xmlsoap.org/ws/2004/08/addressing/role/ano
                      nymous
ReferenceParameters : ReferenceParameters

Ok.

Шаг №5: После чего пробую подключиться с Ubuntu 22.04 к доменной системе:

ekzorchik@srv-us2204a:~$ sudo mkdir -p /etc/ansible/windows/group_vars
ekzorchik@srv-us2204a:~$ sudo nano /etc/ansible/windows/hosts
[windows]
10.90.90.3
ekzorchik@srv-us2204a:~$ sudo nano /etc/ansible/windows/group_vars/windows.yml
file: group_vars/windows.yml
ansible_user: ekzorchik@POLYGON.LOCAL
ansible_password: 712mbddr@
ansible_winrm_transport: basic
#Если получила эта системе kerberos билет
#ansible_winrm_transport: kerberos
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_ping
10.90.90.3 | UNREACHABLE! => {
    "changed": false,
    "msg": "basic: HTTPSConnectionPool(host='10.90.90.3', port=5986): Max retries exceeded with url: /wsman (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f7be9139f00>: Failed to establish a new connection: [Errno 111] Connection refused'))",
    "unreachable": true
}
ekzorchik@srv-us2204a:~$

А теперь с учетом что на srv-dc01 я выше выполнил скрипт: ConfigureRemotingForAnsible.ps1

ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_ping
10.90.90.3 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Отлично но – это Basic аутентификация. Я успешно подключился с Ubuntu 22.04 Server к SRV-DC01.polygon.local

Шаг №6: Теперь для себя я хочу разобрать чтобы при подключении с Ubuntu системы на Windows систему происходила аутентификация на основе kerberos:

ekzorchik@srv-us2204a:~$ sudo apt-get install python3-dev libkrb5-dev krb5-user -y
Default Kerberos version 5 realm: ничего не указываю и нажимаю OK
ekzorchik@srv-us2204a:~$ sudo pip install http://github.com/diyan/pywinrm/archive/master.zip#egg=pywinrm
ekzorchik@srv-us2204a:~$ sudo pip install pyOpenSSL --upgrade
ekzorchik@srv-us2204a:~$ sudo pip install kerberos
ekzorchik@srv-us2204a:~$ sudo pip install "pywinrm[kerberos]"
ekzorchik@srv-us2204a:~$ sudo pip install "pywinrm[credssp]"
ekzorchik@srv-us2204a:~$ sudo pip install "requests-credssp" "requests-kerberos"
ekzorchik@srv-us2204a:~$ sudo cp /etc/krb5.conf /etc/krb5.conf.backup
ekzorchik@srv-us2204a:~$ sudo rm /etc/krb5.conf
ekzorchik@srv-us2204a:~$ sudo nano /etc/krb5.conf
[libdefaults]
default_realm = POLYGON.LOCAL
[realms]
POLYGON.LOCAL = {
kdc = srv-dc01.polygon.local
admin_server = srv-dc01.polygon.local
}
[domain_realm]
.polygon.local = POLYGON.LOCAL
polygon.local = POLYGON.LOCAL

Шаг №7: Проверяю, могу ли я получить kerberos билет:

ekzorchik@srv-us2204a:~$ kinit ekzorchik@POLYGON.LOCAL
Password for ekzorchik@POLYGON.LOCAL: указываю пароль 712mbbdr@ и нажимаю клавишу Enter
ekzorchik@srv-us2204a:~$ klist
Ticket cache: FILE:/tmp/krb5cc_1000
Default principal: ekzorchik@POLYGON.LOCAL

Valid starting       Expires              Service principal
09/08/2022 11:25:50  09/08/2022 21:25:50  krbtgt/POLYGON.LOCAL@POLYGON.LOCAL
        renew until 09/09/2022 11:25:46

из вывода выше видно, что билет получен

Удаляю полученный билет через утилиту ниже:

ekzorchik@srv-us2204a:~$ kdestroy
ekzorchik@srv-us2204a:~$ sudo apt-get install libxml2-utils -y
ekzorchik@srv-us2204a:~$ curl --header "Content-Type: application/soap+xml;charset=UTF-8" --header "WSMANIDENTIFY: unauthenticated" http://10.90.90.3:5985/wsman --data '&lt;s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsmid="http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd"&gt;&lt;s:Header/&gt;&lt;s:Body&gt;&lt;wsmid:Identify/&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt;' | xmllint --format -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   694  100   460  100   234   165k  86092 --:--:-- --:--:-- --:--:--  338k
<?xml version="1.0"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
  <s:Header/>
  <s:Body>
    <wsmid:IdentifyResponse xmlns:wsmid="http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd">
      <wsmid:ProtocolVersion>http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd</wsmid:ProtocolVersion>
      <wsmid:ProductVendor>Microsoft Corporation</wsmid:ProductVendor>
      <wsmid:ProductVersion>OS: 0.0.0 SP: 0.0 Stack: 3.0</wsmid:ProductVersion>
    </wsmid:IdentifyResponse>
  </s:Body>
</s:Envelope>
ekzorchik@srv-us2204a:~$

Шаг №8: Формирую обращение через Ansible посредством Kerberos билета:

ekzorchik@srv-us2204a:~$ sudo mkdir /etc/ansible/windows
ekzorchik@srv-us2204a:~$ sudo nano /etc/ansible/windows/hosts
[windows]
10.90.90.3
ekzorchik@srv-us2204a:~$ sudo mkdir /etc/ansible/windows/group_vars
ekzorchik@srv-us2204a:~$ sudo nano /etc/ansible/windows/group_vars/windows.yml
file: group_vars/windows.yml
ansible_user: ekzorchik@POLYGON.LOCAL
ansible_password: 712mbddr@
ansible_winrm_transport: kerberos
ansible_port: 5985
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
validate_certs: false
ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_ping
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
10.90.90.3 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
ekzorchik@srv-us2204a:~$

Отлично, работает.

Шаг №9: Пример, создаем вложенные каталоги:

ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_command -a "cmd.exe /c mkdir c:\a\b\c\d\e\f"
ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_command -a "cmd.exe /c tree c:\a"
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
10.90.90.3 | CHANGED | rc=0 >>
Folder PATH listing for volume Windows
Volume serial number is 000000A3 5C0F:7A54
C:\A
����b
    ����c
        ����d
            ����e
                ����f

ekzorchik@srv-us2204a:~$

Шаг №10: Отключаем isatap,teredo,6to4:

ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_command -a "cmd.exe /c netsh interface teredo set state disabled"
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
10.90.90.3 | CHANGED | rc=0 >>
Ok.

Шаг №11: Отобразить настройки интерфейса:

ekzorchik@srv-us2204a:~$ sudo ansible windows -i /etc/ansible/windows/hosts -m win_command -a "cmd.exe /c ipconfig /all"
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
10.90.90.3 | CHANGED | rc=0 >>

Windows IP Configuration

   Host Name . . . . . . . . . . . . : srv-dc01
   Primary Dns Suffix  . . . . . . . : polygon.local
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : polygon.local

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Red Hat VirtIO Ethernet Adapter
   Physical Address. . . . . . . . . : 92-FA-E4-77-EC-8C
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.90.90.3(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.90.90.2
   DNS Servers . . . . . . . . . . . : 127.0.0.1
                                       10.90.90.3
   NetBIOS over Tcpip. . . . . . . . : Enabled
ekzorchik@srv-us2204a:~$

Что мне больше нравится из разобранного выше, так это что я используя Ubuntu 22.04 Server могу взаимодействовать через консоль с инфраструктурой Windows хоть и в таком виде, но все же лучше иметь любую возможность чем не иметь вообще ничего.

На этом у меня всё, с уважением автор блога Олло Александр aka ekzorchik.