Skip to content

Instantly share code, notes, and snippets.

@stevenmirabito
Created August 4, 2016 18:48
Show Gist options
  • Save stevenmirabito/51d58cc72461515f0a26ca2d53193f33 to your computer and use it in GitHub Desktop.
Save stevenmirabito/51d58cc72461515f0a26ca2d53193f33 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Network Namespace Manager
# Author: Steven Mirabito ([email protected])
# Must run as root to manage namespaces
if [ $EUID != 0 ]; then
sudo "$0" "$@"
exit $?
fi
# Helper Functions
function show_help {
echo "Usage: ./netnsmgr <namespace> <interface> <command>"
}
# Move the arguments into variables
namespace="$1"
interface="$2"
shift
shift
command="$@"
# Make sure required arguments were passed
if [ -z "$namespace" ]; then
echo "Invalid namespace"
show_help
exit 1
fi
if [ -z "$interface" ]; then
echo "Invalid interface"
show_help
exit 1
fi
if [ -z "$command" ]; then
echo "Invalid command"
show_help
exit 1
fi
# Create the namespace if it doesn't exist
/sbin/ip netns list | grep $namespace &> /dev/null
if [ $? -ne 0 ]; then
# Make sure the interface exists
/sbin/ip link show | grep $interface &> /dev/null
if [ $? -ne 0 ]; then
# Invalid interface
echo "Invalid interface"
show_help
exit 1
fi
# Create the configuration folder
mkdir -p /etc/netns/$namespace
# Create namespace resolv.conf
echo "nameserver 8.8.8.8" > /etc/netns/$namespace/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/netns/$namespace/resolv.conf
# Create the namespace
ip netns add $namespace
# Bring up the loopback device
ip netns exec $namespace ip link set lo up
# Add the interface to the namespace
ip link set $interface netns $namespace
# Bring up the interface
ip netns exec $namespace ip link set $interface up
# Run DHCP on the interface
ip netns exec $namespace dhclient $interface 2>&1
fi
# Run the command in the namespace
ip netns exec $namespace $command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment