Обновить playbooks/scan_inventory.yml

This commit is contained in:
2025-12-10 11:08:38 +00:00
parent f4141acaa4
commit fc94c9d6ed

View File

@@ -3,7 +3,7 @@
hosts: localhost hosts: localhost
connection: local connection: local
gather_facts: no gather_facts: no
become: yes # Нужно для сканирования UDP (SNMP) become: yes # Нужно для сканирования UDP (SNMP) и Nmap -O
vars: vars:
# --- SEMAPHORE API --- # --- SEMAPHORE API ---
semaphore_url: "http://192.168.0.198:9999" semaphore_url: "http://192.168.0.198:9999"
@@ -40,16 +40,20 @@
# ---------------------------------------------------------------- # ----------------------------------------------------------------
# ШАГ 1: Поиск живых хостов (Ping) # ШАГ 1: Поиск живых хостов (Ping)
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- name: Ping Sweep - name: Ping Sweep (быстрый поиск)
command: "nmap -sn -n --min-rate 1000 -T4 -oG - {{ subnets | join(' ') }}" command: "nmap -sn -n --min-rate 1000 -T4 -oG - {{ subnets | join(' ') }}"
register: ping_scan register: ping_scan
changed_when: false changed_when: false
- name: Список IP - name: Формирование списка активных IP
set_fact: set_fact:
active_ips: "{{ ping_scan.stdout | regex_findall('Host: ([0-9.]+)') | unique | list }}" active_ips: "{{ ping_scan.stdout | regex_findall('Host: ([0-9.]+)') | unique | list }}"
- fail: msg="Сеть пуста" when: active_ips|length == 0 # ИСПРАВЛЕННАЯ СТРОКА (Теперь это правильный многострочный блок)
- name: Проверка наличия хостов
fail:
msg: "Сеть пуста, активных хостов не найдено."
when: active_ips | length == 0
# ---------------------------------------------------------------- # ----------------------------------------------------------------
# ШАГ 2: Опрос через SNMP + Проверка портов # ШАГ 2: Опрос через SNMP + Проверка портов
@@ -67,7 +71,7 @@
# ---------------------------------------------------------------- # ----------------------------------------------------------------
# ШАГ 3: Классификация на основе ответа SNMP # ШАГ 3: Классификация на основе ответа SNMP
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- name: Анализ устройств - name: Анализ устройств и классификация
set_fact: set_fact:
classified_hosts: "{{ classified_hosts | default([]) + [ host_data ] }}" classified_hosts: "{{ classified_hosts | default([]) + [ host_data ] }}"
vars: vars:
@@ -77,7 +81,7 @@
# Пытаемся вытащить строку sysDescr # Пытаемся вытащить строку sysDescr
snmp_desc: "{{ out | regex_search('sysDescr\\.0: ([^\\n]+)', '\\1') | first | default('') }}" snmp_desc: "{{ out | regex_search('sysDescr\\.0: ([^\\n]+)', '\\1') | first | default('') }}"
# Определяем тип # Определяем тип (Логика распознавания)
detected_type: >- detected_type: >-
{% if 'Windows' in snmp_desc or '445/tcp open' in out %}windows {% if 'Windows' in snmp_desc or '445/tcp open' in out %}windows
{% elif 'RouterOS' in snmp_desc or 'MikroTik' in snmp_desc or '8291/tcp open' in out %}mikrotik {% elif 'RouterOS' in snmp_desc or 'MikroTik' in snmp_desc or '8291/tcp open' in out %}mikrotik
@@ -85,6 +89,7 @@
{% elif 'JetDirect' in snmp_desc or 'LaserJet' in snmp_desc or 'Samsung' in snmp_desc or 'Kyocera' in snmp_desc or '9100/tcp open' in out %}printer {% elif 'JetDirect' in snmp_desc or 'LaserJet' in snmp_desc or 'Samsung' in snmp_desc or 'Kyocera' in snmp_desc or '9100/tcp open' in out %}printer
{% else %}other{% endif %} {% else %}other{% endif %}
# Собираем данные об одном хосте
host_data: host_data:
ip: "{{ ip }}" ip: "{{ ip }}"
type: "{{ detected_type }}" type: "{{ detected_type }}"
@@ -96,7 +101,8 @@
# ---------------------------------------------------------------- # ----------------------------------------------------------------
# ШАГ 4: Разбиение на группы # ШАГ 4: Разбиение на группы
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- set_fact: - name: Группировка хостов
set_fact:
list_win: "{{ classified_hosts | selectattr('type', 'equalto', 'windows') | list }}" list_win: "{{ classified_hosts | selectattr('type', 'equalto', 'windows') | list }}"
list_lin: "{{ classified_hosts | selectattr('type', 'equalto', 'linux') | list }}" list_lin: "{{ classified_hosts | selectattr('type', 'equalto', 'linux') | list }}"
list_tik: "{{ classified_hosts | selectattr('type', 'equalto', 'mikrotik') | list }}" list_tik: "{{ classified_hosts | selectattr('type', 'equalto', 'mikrotik') | list }}"
@@ -106,7 +112,8 @@
# ШАГ 5: Отправка в Semaphore (Windows) # ШАГ 5: Отправка в Semaphore (Windows)
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- block: - block:
- set_fact: - name: Генерация текста инвентаря Windows
set_fact:
content_win: | content_win: |
[windows] [windows]
{% for h in list_win %} {% for h in list_win %}
@@ -117,7 +124,8 @@
ansible_shell_type=powershell ansible_shell_type=powershell
ansible_port=22 ansible_port=22
- copy: - name: Сохранение JSON для Windows
copy:
content: | content: |
{ {
"name": "SNMP Windows {{ 1000 | random }}", "name": "SNMP Windows {{ 1000 | random }}",
@@ -130,7 +138,8 @@
} }
dest: /tmp/p_win.json dest: /tmp/p_win.json
- command: > - name: Отправка Windows API
command: >
curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory" curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory"
-H "Authorization: Bearer {{ semaphore_api_token }}" -H "Authorization: Bearer {{ semaphore_api_token }}"
-H "Content-Type: application/json" -H "Content-Type: application/json"
@@ -142,7 +151,8 @@
# ШАГ 6: Отправка в Semaphore (MikroTik) # ШАГ 6: Отправка в Semaphore (MikroTik)
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- block: - block:
- set_fact: - name: Генерация текста инвентаря MikroTik
set_fact:
content_tik: | content_tik: |
[routers] [routers]
{% for h in list_tik %} {% for h in list_tik %}
@@ -152,7 +162,8 @@
ansible_connection=network_cli ansible_connection=network_cli
ansible_network_os=routeros ansible_network_os=routeros
- copy: - name: Сохранение JSON для MikroTik
copy:
content: | content: |
{ {
"name": "SNMP MikroTik {{ 1000 | random }}", "name": "SNMP MikroTik {{ 1000 | random }}",
@@ -165,7 +176,8 @@
} }
dest: /tmp/p_tik.json dest: /tmp/p_tik.json
- command: > - name: Отправка MikroTik API
command: >
curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory" curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory"
-H "Authorization: Bearer {{ semaphore_api_token }}" -H "Authorization: Bearer {{ semaphore_api_token }}"
-H "Content-Type: application/json" -H "Content-Type: application/json"
@@ -177,7 +189,8 @@
# ШАГ 7: Отправка в Semaphore (Принтеры) # ШАГ 7: Отправка в Semaphore (Принтеры)
# ---------------------------------------------------------------- # ----------------------------------------------------------------
- block: - block:
- set_fact: - name: Генерация текста инвентаря Принтеров
set_fact:
content_prn: | content_prn: |
[printers] [printers]
{% for h in list_prn %} {% for h in list_prn %}
@@ -186,7 +199,8 @@
[printers:vars] [printers:vars]
ansible_connection=local ansible_connection=local
- copy: - name: Сохранение JSON для Принтеров
copy:
content: | content: |
{ {
"name": "SNMP Printers {{ 1000 | random }}", "name": "SNMP Printers {{ 1000 | random }}",
@@ -199,7 +213,8 @@
} }
dest: /tmp/p_prn.json dest: /tmp/p_prn.json
- command: > - name: Отправка Принтеров API
command: >
curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory" curl -X POST "{{ semaphore_url }}/api/project/{{ semaphore_project_id }}/inventory"
-H "Authorization: Bearer {{ semaphore_api_token }}" -H "Authorization: Bearer {{ semaphore_api_token }}"
-H "Content-Type: application/json" -H "Content-Type: application/json"
@@ -207,5 +222,5 @@
ignore_errors: yes ignore_errors: yes
when: list_prn | length > 0 when: list_prn | length > 0
- name: Очистка - name: Очистка временных файлов
shell: rm -f /tmp/p_*.json shell: rm -f /tmp/p_*.json