Ubuntu – How to restart the Wi-Fi connection from the command-line

command linewireless

Occasionally, my Wi-Fi connection does no longer work for various reasons. Disabling and re-enabling Wi-Fi through the graphical interface of the network indicator does not resolve the problems in these cases.

How can I completely restart my Wi-Fi connection from the command-line without having to restart my machine (which fixes these problems)?

Best Answer

nmcli is very useful command-line utility for interacting with Network Manager. Use this command in Ubuntu 16.04 LTS

nmcli radio wifi off && sleep 5 && nmcli radio wifi on

For versions prior to 15.10 ( i.e. before transition to systemd ) the command would be slightly different:

nmcli nm wifi off && sleep 5 && nmcli nm wifi on

Good thing about it - this doesn't require root powers.

Restarting network manager itself is a good idea as well.

For 16.04 LTS:

sudo systemctl restart NetworkManager

and for 14.04 LTS:

sudo service network-manager restart

And if we really wanted to, we could even automate it with a script that will restart your wifi.

#!/bin/bash
# replace wlan0 with your device name
# as given by ip addr or ifconfig
while true 
do
    # keep checking if we have ip address    
    wifi_info=$(ip -4 -o addr  show wlan0 )
    while [ -n "$wifi_info" ];
    do
       wifi_info=$(ip -4 -o addr  show wlan0 )
       sleep 0.25
    done

    # We get here only if IP address is lost
    # which means we're off-line
    # restart wifi 
    nmcli radio wifi off && sleep 5 && nmcli radio wifi on
done