1

My router is quite a distance from my work space, but I have an ethernet cable running that distance. When I plug it into my laptop, is there a way to automatically turn on the laptop's hotspot so that my phone can connect to a stronger WiFi signal?

Also, it would need to turn off the hotspot when the ethernet connection is removed.

2 Answers2

2

Use nmcli d|grep -E "^eth0"|grep connected to judge if cable is connected.

Write a script like

AP=0
while :; do
    if nmcli d|grep -E "^eth0"|grep connected ; then
        if [[ AP -eq 0 ]]; then
            # bring hotspot up
            AP=1
        fi
    else
        if [[ AP -eq 1 ]]; then
            # turn hotspot off
            AP=0
        fi
    fi
    sleep 2
done
1

Based on Bob Johnson's answer, I would suggest to use nmcli device show [ethernetdevice] | grep IP4.ADDRESS, it's agnostic to language and prevents to keep WiFi as AP when a cable is connected but is not giving IP address:

#!/bin/bash

AP=0
while :;
do
 if nmcli device show eth0 | grep IP4.ADDRESS ; then
    if [[ AP -eq 0 ]]; then
     nmcli device disconnect wlan0
     nmcli connection up 'Shared WiFi connection name'
     AP=1
    fi
 else
    if [[ AP -eq 1 ]]; then
     nmcli connection down 'Shared WiFi connection name'
     nmcli device connect wlan0
     AP=0
    fi
 fi
 sleep 5
done

Where:

  • eth0 is the ethernet device identified by ifname, eth0 in most cases, (not mine) you can get the correct name for your device by typing nmcli device in a terminal.
  • wlan0 is the WiFi device identified by ifname.
  • Shared WiFi connection name is the name of the CONNECTION to share WiFi as AP (not always equivalent to SSID, it depends on how it is configured).

Add the script to autostart apps in your shell. It's working like a charm for me.

leoperbo
  • 763