TrashNotes

2025-03-27 08:20:10
напишем скрипт на питоне который забирает файлы с машин перечня "ansible inventory", и все содержимое /tmp/rm/* и копирует ко мне раскладывает по папкам согластно hostname

#######

from ansible.parsing.parser import AnsibleParser
from ansible.inventory.manager import InventoryManager
import os
import shutil

# Функция для получения файла из инвентаря и копирования содержимого
def get_and_copy_file(file_path):
    # Получаем файл в папке /tmp/с/последним_директорием/именем_файла
    tmp_dir = "/tmp/"
    last_directory = os.listdir(tmp_dir)[-1]  # Получаем последнюю директорию
    file_name = os.listdir(os.path.join(tmp_dir, last_directory))[0]  # Получаем имя файла

    file_path_to_copy = os.path.join(tmp_dir, last_directory, file_name)

    # Перемещение файла в папку с хостом и копирование его содержимого
    hostname = "your_host"  # Замените на ваш хост
    destination_path = f"/tmp/{hostname}/"
    
    if not os.path.exists(destination_path):
        os.makedirs(destination_path)

    shutil.copy2(file_path_to_copy, destination_path)
    print(f"Copied {file_name} to {destination_path}")

# Основная функция для работы с Ansible
def main():
    inventory_manager = InventoryManager.load_from_file("/path/to/your/inventory.ini")
    parser = AnsibleParser()
    
    # Получаем файлы из инвентаря, соответствующие фильтруемому перечню
    for group in inventory_manager.hosts.values():
        if "group_name" in group:  # Замените 'group_name' на имя группы
            files = [f for f in group.files if os.path.isfile(f)]
            for file_path in files:
                get_and_copy_file(file_path)

if __name__ == "__main__":
    main()
← Previous Next →
Back to list