Created
February 1, 2018 11:46
-
-
Save r4um/56c164d4bb1367a99fbeb25628f83eae to your computer and use it in GitHub Desktop.
Get the network interface names as seen outside the docker namespace
This file contains 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 python2 | |
# get the network interface names as seen outside the docker namespace | |
# TODO: add dumping stats | |
import os.path | |
import pyroute2 | |
import sys | |
import subprocess | |
def get_attr(link, name): | |
attr_val = "" | |
for attr in link['attrs']: | |
if attr[0] == name: | |
attr_val = attr[1] | |
return attr_val | |
def is_loopback(link): | |
return (link['flags'] & 0xffffffff & pyroute2.netlink.rtnl.ifinfmsg.IFF_LOOPBACK) == pyroute2.netlink.rtnl.ifinfmsg.IFF_LOOPBACK | |
def get_nons_links(): | |
links_no_ns = {} | |
ip = pyroute2.IPRoute() | |
for link in ip.get_links(): | |
if is_loopback(link): | |
continue | |
links_no_ns[link['index']] = get_attr(link, "IFLA_IFNAME") | |
return links_no_ns | |
def get_docker_container_ns(container_id): | |
namespace_id = subprocess.check_output(['docker', 'inspect', "--format={{.NetworkSettings.SandboxKey}}", container_id]).strip() | |
namespace_id = os.path.basename(namespace_id) | |
return namespace_id | |
def get_ns_links(ns_id): | |
links_ns = {} | |
pyroute2.netns.NETNS_RUN_DIR = '/var/run/docker/netns' | |
ns = pyroute2.NetNS(ns_id) | |
for link in ns.get_links(): | |
if is_loopback(link): | |
continue | |
links_ns[link['index']] = get_attr(link, "IFLA_IFNAME") | |
return links_ns | |
def docker_container_ids(): | |
x = subprocess.check_output(['docker', 'ps', "--format={{.ID}}"]).split("\n") | |
x = x[0:-2] | |
return x | |
if __name__ == "__main__": | |
cids = docker_container_ids() | |
if len(sys.argv) > 1: | |
cids = sys.argv[1:] | |
all_non_ns_links = get_nons_links() | |
for container_id in cids: | |
links_ns = get_ns_links(get_docker_container_ns(container_id)) | |
print container_id | |
for k,v in links_ns.iteritems(): | |
print "\t%d %s %s" % (k, v, all_non_ns_links[k+1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment