Linux command-line: Quick way to disable internet (keeping LAN)?
Split question: this other one here is for Windows.
Linux: Fastest way to disable internet (keeping LAN) from command line?
I think the easiest way to deactivate internet (not LAN) in Linux is to remove the default gateway, so, assuming LAN is 10.0.2.0/24 and gateway is 10.0.2.1 :
sudo /sbin/route del default gw 10.0.2.1
To reactivate internet:
sudo /sbin/route add default gw 10.0.2.1
But, even when this a simple line, it requires to discover the default gateway IP first:
sudo /sbin/route
I am going to build some general purpose shell scripts that need to enable/disable internet(but keep LAN working), so it seems I am going to need some (¿grep
, maybe?) operations to filter and detect the exact gateway IP number (it could be 10.0.2.1, 127.0.0.1, 127.0.50.1, 192.168.0.1 ... etc), unless I achieve to find a simpler command line.
Any ideas, please?
On *nix, to find the gateway:
GW="$(sudo /sbin/route -n | awk '$1=="0.0.0.0" {print $2; exit}')"
sudo /sbin/route del default gw "$GW"
echo "$GW" >~/my_tmp_file
The last line saves the value in a file for later use when you want to restart the network:
sudo /sbin/route add default gw "$(cat ~/my_tmp_file)"
Note: If there is more than one default gateway it will require this code to run again for each, or to be rewritten in order to support that.
How it works: The above awk
command is able to capture the gateway because route -n
output looks like:
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.2.1 0.0.0.0 UG 0 0 0 eth0
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
The internet gateway is the one that allows destination anywhere (0.0.0.0
). Thus, the awk
script goes through this output line by line looking at the first column (called $1
in awk
notation). When the first column is destination-anywhere, then it prints the second column which is the gateway. The output of the awk
command is then captured into the shell variable GW
. The shell can then be asked to substitute $GW
into any command that needs it.