README.md | ||
setup_interface.py |
setup_interface.py for VyOS
When using VyOS as a router in a home lab setup, the need frequently arises to add a new IP subnet.
This process involves adding a new physical network adapter to the router, then configuring an IP address for the interface, and finally configuring IP SNAT masquerading for the subnet.
This script automates that process. Once a network adapter has been added to the VyOS router host, run this script to configure the IP address of the new interface and to create the appropriate IP masquerade rule for the IP subnet.
This script checks all available physical network adapters to see if they are already configured with IP addresses. The script will not run for any adapters that already have IP addresses assigned to them.
Note that this script is intended to be used only with IPv4 addresses and it ignores IPv6 addresses.
This script uses the convenient ipaddress
Python built-in library, the subprocess
library's run()
command, and makes frequent use of f-strings for variable substitutions.
Because the shell commands invoked by subprocess.run()
use Linux pipes, they are invoked with the shell=True
option. Invoking them with shell=True
also makes it a lot simpler to run long shell commands without having to tokenize the commands into a list, which is normally preferred when invoking them with subprocess.run()
. Instead, the commands are just strings.
Also note that many commands are invoked with the /opt/vyatta/bin/vyatta-op-cmd-wrapper
wrapper script because they are not standard Linux shell commands but rather part of VyOS's rbash.
This script is a good example of leveraging the power of Python to work with the Linux command line for administrative tasks.
Running the script
# the description is required and will be applied to both the interface and
# it's associated NAT rule
./setup_interface.py <IP address/netmask #> '<interface/subnet description>'
Example usage
./setup_interface.py 192.168.0.3/24 'test-subnet'