Last active
January 22, 2024 07:43
-
-
Save aojea/e45a33f53246c5e124aa7c7adc7ce75d to your computer and use it in GitHub Desktop.
Create a veth pair
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 bash | |
while getopts ":n:m:i:g:" opt; do | |
case $opt in | |
n) | |
NAMESPACE=$OPTARG | |
;; | |
m) | |
MAC=$OPTARG | |
;; | |
i) | |
IP=$OPTARG | |
;; | |
g) | |
GW=$OPTARG | |
;; | |
esac | |
done | |
if [ -z "$NAMESPACE" ]; then | |
echo "Usage: create_veth_pair -n NAMESPACE [-i IP] [-m MAC] [-g GW]" | |
exit 1 | |
fi | |
set -xe | |
DP_INTERFACE=${NAMESPACE}dp | |
NS_INTERFACE=${NAMESPACE}ns | |
ip netns add $NAMESPACE | |
ip link add name $DP_INTERFACE type veth peer name $NS_INTERFACE | |
ip link set netns $NAMESPACE dev $NS_INTERFACE | |
ip link set up $DP_INTERFACE | |
ip netns exec $NAMESPACE ip link set up dev lo | |
ip netns exec $NAMESPACE ip link set up dev $NS_INTERFACE | |
if [ -n "$IP" ]; then | |
if [ $IP="dhcp" ] | |
then | |
ip netns exec $NAMESPACE dhclient -nw -v \ | |
-pf /tmp/dhclient$NAMESPACE.pid \ | |
-lf /tmp/dhclient$NAMESPACE.lease $NS_INTERFACE | |
else | |
ip netns exec $NAMESPACE ip address add $IP dev $NS_INTERFACE | |
fi | |
fi | |
if [ -n "$MAC" ]; then | |
ip netns exec $NAMESPACE ip link set address $MAC dev $NS_INTERFACE | |
fi | |
if [ -n "$GW" ]; then | |
ip netns exec $NAMESPACE ip route add default via $GW | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment