Restart network with a command without need to provide password

Solution 1:

You can make a change to sudoers to allow your user account to execute the necessary commands without password.

Warning: Be sure to not delete anything from sudoers without exactly knowing what its for! You could potentially loose all admin privileges.

  1. Open sudo visudo
  2. In the section headed "Cmnd alias specification" add

    Cmnd_Alias NETWORK = /usr/sbin/service network-manager restart
    

    NETWORK is just an alias for a group of commands. Give it a different name if you prefer!

  3. At the end of the file, append the statement

    user_name ALL = (ALL) NOPASSWD: NETWORK
    

    where you substitute your user account for user_name. Also replace NETWORK with whatever name you've given the alias. One could also do without the alias and simply replace it by the command, but I prefer it this way. I find it keeps things more organized.

  4. Safe the file and exit the editor. Check with sudo -l that you are now indeed allowed to issue the command.

You still need to prepend the command with sudo, but you won't be prompted for a password anymore.

Solution 2:

Another possibility is to use the command line interface of Network Manager (it's not so "strong" as restarting the daemon, but it worked for me). In this case, the operation is exactly the same as if you interact with the applet, so you do not need any privilege.

To restart the wifi interface, use this code:

nmcli nm wifi off
sleep 5
nmcli nm wifi on

I had similar problems with the network dropping (it was a faulty router in my case), so I used this script added to the startup jobs:

#!/bin/bash
PINGTEST=192.168.1.1 # my router, change here. google.com should work anytime ;-)
while /bin/true; do
    if ! [ "$(ping -c 1 $PINGTEST)" ]; then
        echo "Warning: connection lost at $(date) -- restart" 1>&2  
        nmcli nm wifi off
        sleep 5
        nmcli nm wifi on
        sleep 60
        if ! [ "$(ping -c 1 $PINGTEST)" ]; then
             echo "Waiting for connection going up at $(date)" 1>&2
             sleep 60
        else 
             echo "Connection on at $(date)" 1>&2
        fi
#    else
#        echo "Connection OK on $(date)" 1>&2
    fi
sleep 60
done

it checks the connection every minute and if it does not work, it restarts the wifi.

If this is not sufficient, you probably have to use stronger weapons, like starting/stopping Network Manager. Even that sometime fails on me, and I have to resort to unload (sudo rmmod) and then reload (sudo modprobe) the wifi card driver module.