Files
ansible-inventories/host_discovery.yml

42 lines
1.4 KiB
YAML

---
- name: Host Discovery with Nmap Probing Port 22
hosts: localhost
connection: local
vars:
networks:
- 192.168.1.0/24 # Add your networks here
output_file: discovered_hosts.json
tasks:
- name: Install nmap if not present
become: true
ansible.builtin.apt:
name: nmap
state: present
update_cache: true
- name: Perform Nmap scan on each network
ansible.builtin.shell:
cmd: nmap -sT -p 22 -Pn --open -R -oG - {{ item }}
register: scans
loop: "{{ networks }}"
changed_when: false
- name: Combine all scan outputs
ansible.builtin.set_fact:
all_output: "{{ scans.results | map(attribute='stdout') | join('\n') }}"
- name: Extract host lines
ansible.builtin.set_fact:
host_lines: "{{ all_output.splitlines() | select('search', '^Host:') | list }}"
- name: Parse hosts into list
ansible.builtin.set_fact:
hosts_list: "{{ hosts_list | default([]) + [{'ip': ip, 'hostname': hostname}] }}"
loop: "{{ host_lines }}"
vars:
line: "{{ item }}"
host_part: "{{ line.split('\t')[0] }}"
parts: "{{ host_part.split(' ') }}"
ip: "{{ parts[1] }}"
hostname: "{{ parts[2] | replace('(', '') | replace(')', '') }}"
- name: Save to JSON file
ansible.builtin.copy:
content: "{{ {'hosts': hosts_list} | to_nice_json }}"
dest: "{{ output_file }}"