2

I’m currently routing some marked packets via eth0. However, I have to apply the routing rules every time the system reboots. The two commands I always have to re enter are

ip rule add fwmark 3 table 3
ip route add default via 192.168.0.1 table 3

The gateway for eth0 being 192.168.0.1 I’ve tried placing those commands in both /etc/rc.local and /etc/network/interfaces, and in both cases I have still had to run them manually. Does anyone have a suggestion as to where/how to run these commands on every startup?

Zaden
  • 23
  • 1
  • 1
  • 3

3 Answers3

6

Put your commands in a shell script e.g. /usr/local/sbin/myrouting and make it executable.

You could use cron and an @reboot target in /etc/crontab or the root crontab e.g. /etc/crontab

@reboot root /usr/local/sbin/myrouting

or root crontab

@reboot /usr/local/sbin/myrouting 

You could also do it using systemd.

Create a systemd unit file /etc/systemd/system/myrouting.service

[Unit]
after=network

[Service]
ExecStart=/usr/local/sbin/myrouting

[Install]
WantedBy=default.target

Then enable it

systemctl enable myrouying.service
Created symlink /etc/systemd/system/default.target.wants/myrouting.service → /etc/systemd/system/myrouting.service.
user9517
  • 115,471
  • 20
  • 215
  • 297
3

You can do this using /etc/network/interfaces file only.

You just have to put your add route command under the desired interface and put post-up or pre-down keywords before that command.

post-up keyword will add that route in the routing table after you will have brought up that interface and pre-down keyword will remove it before you will have brought down that interface.

For example:
To add static route on eth0 interface, /etc/network/interfaces file should be

auto eth0
iface eth0 inet static
    ...
    ...
    post-up ip route replace default via 192.168.0.1
    pre-down ip route delete default via 192.168.0.1 || true
Anton Danilov
  • 5,082
  • 2
  • 13
  • 23
Yugendra
  • 151
  • 1
  • 12
  • Turned out that OpenVPN was messing with commands I placed in there, so I kept the marking rule in the interfaces file, but moved the route adding to a file that runs on OpenVPN start up. Marking this as correct, since if it weren't for OpenVPN it would've worked. – Zaden Dec 26 '17 at 23:57
0

you could also add these command into /etc/rc.local and don't forget to make it executable:

touch stagingfile.txt

echo "ip rule add fwmark 3 table 3" >> stagingfile.txt
echo "ip route add default via 192.168.0.1 table 3" >> stagingfile.txt

sudo mv stagingfile.txt /etc/rc.local
chmod +x /etc/rc.local

should work

Owensteam
  • 120
  • 2
  • 10