Skip to content

Instantly share code, notes, and snippets.

@switefaster
Last active April 10, 2024 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save switefaster/f769129d536f87e597e2080922a8d0d9 to your computer and use it in GitHub Desktop.
Save switefaster/f769129d536f87e597e2080922a8d0d9 to your computer and use it in GitHub Desktop.
namespace setup for linuxqq
#!/bin/bash
NS="linuxqq"
VETH="veth0"
ip li delete ${VETH} 2>/dev/null
[Unit]
Description=LinuxQQ Namespace Setup
ConditionFileIsExecutable=/path/to/linuxqq-netns.sh
[Service]
Type=oneshot
ExecStart=/path/to/linuxqq-netns.sh
ExecStop=/path/to/linuxqq-netns-exit.sh
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
#!/bin/bash
available_interfaces()
{
local ret=()
local ifaces=$(ip li sh | cut -d " " -f 2 | tr "\n" " ")
read -a arr <<< "$ifaces"
for each in "${arr[@]}"; do
each=${each::-1}
if [[ ${each} != "lo" && ${each} != veth* ]]; then
ret+=( "$each" )
fi
done
echo ${ret[@]}
}
IFACE="$1"
if [[ -z "$IFACE" ]]; then
ifaces=($(available_interfaces))
if [[ ${#ifaces[@]} -gt 0 ]]; then
IFACE=${ifaces[0]}
echo "Using interface $IFACE"
else
echo "Usage: ./ns-inet <IFACE>"
exit 1
fi
fi
NS="linuxqq"
VETH="veth0"
VPEER="veth1"
VETH_ADDR="10.200.1.1"
VPEER_ADDR="10.200.1.2"
FIXED_MAC="ff:ff:ff:ff:ff:ff"
# Remove namespace if it exists.
ip netns del $NS &>/dev/null
# Create namespace
ip netns add $NS
# Create veth link.
ip link add ${VETH} type veth peer name ${VPEER}
# Add peer-1 to NS.
ip link set ${VPEER} netns $NS
# Setup IP address of ${VETH}.
ip addr add ${VETH_ADDR}/24 dev ${VETH}
ip link set ${VETH} up
# Setup IP ${VPEER}.
ip netns exec $NS ip addr add ${VPEER_ADDR}/24 dev ${VPEER}
ip netns exec $NS ip link set ${VPEER} address 52:f1:32:a8:33:d2
ip netns exec $NS ip link set ${VPEER} up
ip netns exec $NS ip link set lo up
ip netns exec $NS ip route add default via ${VETH_ADDR}
# Enable IP-forwarding.
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush forward rules.
iptables -P FORWARD DROP
iptables -F FORWARD
# Flush nat rules.
iptables -t nat -F
# Enable masquerading of 10.200.1.0.
iptables -t nat -A POSTROUTING -s ${VPEER_ADDR}/24 -o ${IFACE} -j MASQUERADE
iptables -A FORWARD -i ${IFACE} -o ${VETH} -j ACCEPT
iptables -A FORWARD -o ${IFACE} -i ${VETH} -j ACCEPT
# modified from https://gist.githubusercontent.com/dpino/6c0dca1742093346461e11aa8f608a99/raw/27df052e57009d9ffc1a0ce9d6a8047dc711ad46/ns-inet.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment