Skip to content

Instantly share code, notes, and snippets.

@double-z
Forked from zqu4rtz/TtapNetQemu
Created February 12, 2019 02:15
Show Gist options
  • Save double-z/7e65c51a4c960cc65952ecb961bb9867 to your computer and use it in GitHub Desktop.
Save double-z/7e65c51a4c960cc65952ecb961bb9867 to your computer and use it in GitHub Desktop.
#!/sbin/openrc-run
#
# OpenRc Script to create a service that can configure a Internal or Host-Only Network
# it create tun/tap and bridge interfaces, you'll able to use them how do you like
#
# INSTRUCTIIONS:
# 1- create file /etc/ttapnetqemu/network.conf put follow lines
#
# mode=hostonly|inet #hostonly -> Host Only Network or inet -> Internal Network
# host_numbers=2 #Number of hosts to configure. it create same number of tun/tap and bro interface depending to mode
# kvm_group=kvm #Specify kvm user group, it necessary to grant permissions on tap interfaces
#
# 2- then rc-service start you can run
# qemu-system-x86_64 -netdev tap,id=YOUR_IDNET,ifname=TAP_INTERFACE,script=no
# -device e1000,netdev=net1,mac=XX:XX:XX:XX:XX:XX -enable-kvm -daemonize
#
CONF_FOLDER="/etc/ttapnetqemu/network.conf";
DE_KEYVALUE_CONF="="
depend(){
need net
}
start(){
ebegin "Configuring Qemu Network"
if [[ -f $CONF_FOLDER ]]; then
MODE=$(grep "mode" $CONF_FOLDER | awk -F $DE_KEYVALUE_CONF '{print $2}');
NUMBER_TAPIFACES=$(grep "host_numbers" $CONF_FOLDER | awk -F $DE_KEYVALUE_CONF '{print $2}');
KVM_GROUP=$(grep "kvm_group" $CONF_FOLDER | awk -F $DE_KEYVALUE_CONF '{print $2}');
#Adding all tun/tap interfaces
case $MODE in
"hostonly" )
einfo "Creating topology Host-Only Network";
for iface in $(seq 1 1 $NUMBER_TAPIFACES) ;
do
ip tuntap add dev "tap$iface" mode tap group $KVM_GROUP;
ip link set dev "tap$iface" up promisc on;
ip addr add 0.0.0.0 dev "tap$iface";
ip link add "br$iface" type bridge;
ip link set "br$iface" up;
ip link set "tap$iface" master "br$iface";
echo 0 > "/sys/class/net/br$iface/bridge/stp_state";
ip addr add "192.168.$iface.1/24" dev "br$iface";
done;
;;
"inet" )
einfo "Creating topology Internal Network";
ip link add br0 type bridge;
ip link set br0 up;
echo 0 > "/sys/class/net/br0/bridge/stp_state";
ip addr add 10.0.0.1/24 dev br0;
for iface in $(seq 1 1 $NUMBER_TAPIFACES) ;
do
ip tuntap add dev "tap$iface" mode tap group $KVM_GROUP;
ip link set dev "tap$iface" up promisc on;
ip addr add 0.0.0.0 dev "tap$iface";
ip link set "tap$iface" master br0;
done;
;;
esac
else
return 1;
fi
eend $?
}
stop(){
ebegin "Removing all Tun/Tap and bridge interfaces"
#Check if qemu is running
pgrep "qemu-system" &>/dev/null;
if [[ $? -ne 0 ]]; then
#Get all tuntap and bridge interfaces
for iface in $({(ip -br tuntap); (ip -br link show type bridge);} | awk -F '[: ]' '{print $1}') ; do
ip link set $iface down;
ip link del $iface;
done;
else
return 1;
fi
eend $?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment