Linux – Adding a static route to a virtual interface using configuration files rather than ip command

iplinuxstatic-routes

We statically assign our routes using the /etc/sysconfig/network-scripts/route-ethx files. This makes managing them fairly easy since we add the routes during the kickstart process (by way of post-script). They rarely change and if they need to be updated we simply push out a change and update the build scripts to include the new route.

Recently, we had a customer ask for a virtual interface (eth0:0) with a unique IP. It needs to connect exclusively to one network. The first assigned IP on eth0 will handle all other traffic.

Everything I've seen states how to add a route using ip route add, however I can't sort out how to specify that anything going to a particular IP or network can have the source IP set. If I use the ip command will it update the route files or is it stored elsewhere for persistence across reboots? If I have to add the entry to the route file for eth0:0 what should the line look like?

So basically:

If it goes to 10.0.0.2 use IP 10.0.1.3 as the source.
If it goes anywhere else use IP 10.0.1.2 as the source.

Is this possible? How do I accomplish it?

Best Answer

If I understand clearly your question, you could try something like the following

# ip route add 10.0.0.2 via xxx.xxx.xxx.xxx src 10.0.1.3
# ip route add default via yyy.yyy.yyy.yyy src 10.0.2.2

Is there another method I need to look into?

You could try to use iptables

# iptables -t nat -I PREROUTING -d 10.0.0.2 -j SNAT --to-source 10.0.1.3