benfasoli
5/18/2017 - 10:40 PM

Force change linux network interface status if unable to make an outgoing connection

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')