Last active
May 2, 2018 16:11
-
-
Save SharkyRawr/c8b83f12dba9c75a6b4b9f454adb57a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python3 | |
| """ | |
| Print IP's of LXC containers in a hostfile compatible way. | |
| by Hendrik 'Sharky' Schumann - https://schumann.pw/ | |
| """ | |
| import os, sys | |
| LXC_PATH = r'/var/lib/lxc/' | |
| def fetch_ips(container): | |
| container_dir = os.path.join(LXC_PATH, container) | |
| ips = [] | |
| with open(os.path.join(container_dir, 'config'), 'r') as f: | |
| lines = f.readlines() | |
| for line in lines: | |
| if 'lxc.network.ipv' in line and not 'gateway' in line: | |
| ipnet = line.split(' = ')[1] | |
| ip = ipnet[:ipnet.index('/')] | |
| #netmask = ipnet[ipnet.index('/'):] | |
| ips.append(ip) | |
| return ips | |
| def find_containers(): | |
| alldirs = os.listdir(LXC_PATH) | |
| allcontainers = [] | |
| for d in alldirs: | |
| if os.path.isdir(os.path.join(LXC_PATH, d)): | |
| allcontainers.append(d) | |
| return allcontainers | |
| def main(argv): | |
| ipcon = [] | |
| for container in find_containers(): | |
| ips = fetch_ips(container) | |
| ipcon.append(dict(container=container, ips=ips)) | |
| for container in ipcon: | |
| for ip in container['ips']: | |
| print(("%s\t%s" % (ip, container['container'])).expandtabs(30)) | |
| if __name__ == '__main__': | |
| main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment