Skip to content

Instantly share code, notes, and snippets.

@benfasoli
Last active May 22, 2017 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfasoli/72f27cbcaeca4c3402ad5c8034d0afce to your computer and use it in GitHub Desktop.
Save benfasoli/72f27cbcaeca4c3402ad5c8034d0afce to your computer and use it in GitHub Desktop.
Force change linux network interface status if unable to make an outgoing connection
#!/usr/bin/python
# Ben Fasoli
# Maintain an internet connection by monitoring outgoing requests to google's
# dns server (8.8.8.8)
import os
from time import sleep
def ping(host = '8.8.8.8'):
print('Attempting outgoing connection')
response = not bool(os.system('ping -c 1 -W 5 ' + host + ' > /dev/null 2>&1'))
if not response:
print('Failed to make outgoing connection')
return(response)
def restart_interface(interface = 'eth5'):
print('Restarting ' + interface + '...')
os.system('/sbin/ifdown ' + interface)
sleep(3)
os.system('/sbin/ifup --force ' + interface)
sleep(10)
print('Interface ' + interface + ' forced up')
return(True)
if __name__ == '__main__':
online = ping('8.8.8.8')
n_ping = 1
while not online and n_ping < 10:
restart_interface('eth5')
online = ping('8.8.8.8')
n_ping = n_ping + 1
if online:
print('Network connection currently active')
else:
print('Unable to establish network connection')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment