直接上代码:
#!/usr/bin/python3
# coding:utf-8
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
import subprocess
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources="/etc/ansible/hosts")
hosts = []
hosts += inventory.list_hosts()
# list all groups
groups = inventory.list_groups()
for host in hosts:
cmd = "ssh %s hostname" % host
#s = os.popen(cmd, 'r')
#hostname = s.read().strip()
#s.close()
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
p.wait()
hostname = p.stdout.read().decode().strip()
print("%s\t%s\t%s" % (host, host.get_groups(), hostname))