-
Notifications
You must be signed in to change notification settings - Fork 2
/
inventory.py
59 lines (45 loc) · 1.19 KB
/
inventory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
import socket
import subprocess
def main():
print(json.dumps(inventory(), sort_keys=True, indent=2))
def inventory():
ip_address = find_pi()
return {
'all': {
'children': [
'ungrouped' ]
},
'ungrouped':{
'hosts':['local_mac']
},
'_meta': {
'hostvars': {
'local_mac': {
'ansible_host': ip_address,
}
},
},
}
def find_pi():
for ip in all_local_ips():
if port_22_is_open(ip):
return ip
def all_local_ips():
lines = subprocess.check_output(['arp', '-a']).split('\n')
for line in lines:
if '(' not in line:
continue
after_open_bracket = line.split('(')[1]
ip = after_open_bracket.split(')')[0]
yield ip
def port_22_is_open(ip):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, 22))
return result == 0
if __name__ == '__main__':
main()