Skip to content

Instantly share code, notes, and snippets.

@mattypiper
Created July 18, 2015 23:19
Show Gist options
  • Save mattypiper/150c2527654359f2ce46 to your computer and use it in GitHub Desktop.
Save mattypiper/150c2527654359f2ce46 to your computer and use it in GitHub Desktop.
Wifi Monitor Windows Service
"""
Windows service that monitors the currently connected network using netsh
Installation:
1) Edit the desired network name (replace "DesiredSsidName")
2) python WifiMonitor.py install
3) Open the Windows Service Control Manager and start the service
4) If there are problems, eg Python exceptions, use Event Viewer to see them
Description:
If the desired network isn't the current network, it disables the wireless network interface and then re-enables it
This is useful if your computer occasionally falls off of the network you want to be connected to, like mine
A log of WifiMonitor's actions can be found at C:\temp\wifi_monitor.log
Requires:
http://sourceforge.net/projects/pywin32/
"""
import os, subprocess, re, time
from subprocess import Popen, PIPE
from time import localtime, strftime
import win32serviceutil, win32service, win32event
import servicemanager
from socket import setdefaulttimeout
from threading import Event
def log(msg):
t = strftime("%Y-%m-%d %H:%M:%S", localtime())
with open('C:\\temp\\wifi_monitor.log', 'a') as f:
f.write('[{}] {}\n'.format(t, msg))
class AppServerSvc(win32serviceutil.ServiceFramework):
_svc_name_ = "WifiMonitor"
_svc_display_name_ = "WifiMonitor"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
self.keep_running = True
self.stop_event = Event()
setdefaulttimeout(60)
def SvcStop(self):
self.keep_running = False
self.stop_event.set()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def getCurrentSsid(self):
p = Popen(['netsh', 'wlan', 'show', 'interfaces'], stdout=PIPE)
(stdout, stderr) = p.communicate()
out = stdout.split('\n')
for line in out:
r = re.match('\s+SSID\s+:\s([\w\s]+)', line)
if r != None and len(r.groups()) > 0:
ssid = r.groups(1)[0].strip()
#log('Current SSID: {}'.format(ssid))
return ssid
log("Couldn't figure out current ssid")
def connect(self, ssid):
log('Connecting to {}.'.format(ssid))
p = Popen(['netsh', 'wlan', 'connect', 'name={}'.format(ssid)], stdout=PIPE)
(stdout, stderr) = p.communicate()
log(stdout)
if 'Connection request was completed successfully.' not in stdout:
return False
time.sleep(5)
cur = self.getCurrentSsid()
if cur != ssid:
log('Tried to connect to {}, but still connected to {}'.format(ssid, cur))
def disconnect(self, interface='WiFi'):
log('Disconnecting...')
p = Popen(['netsh', 'wlan', 'disconnect'], stdout=PIPE)
(stdout, stderr) = p.communicate()
def disable(self, interface='WiFi'):
log('Disabling interface {}...'.format(interface))
p = Popen(['netsh', 'interface', 'set', 'interface', interface, 'disabled'], stdout=PIPE)
(stdout, stderr) = p.communicate()
log('netsh disable complete'.format(interface))
#log(stdout)
def enable(self, interface='WiFi'):
log('Enabling interface {}...'.format(interface))
p = Popen(['netsh', 'interface', 'set', 'interface', interface, 'enabled'], stdout=PIPE)
(stdout, stderr) = p.communicate()
log('netsh enable complete'.format(interface))
#log(stdout)
def reset(self, desired):
log('Resetting adapter...')
self.disable()
time.sleep(5)
self.enable()
time.sleep(5)
self.connect(desired)
log('Reset complete')
def main(self):
desired = 'DesiredSsidName'
log('Starting WifiMonitor...')
while not self.stop_event.wait(timeout=30.0):
cur = self.getCurrentSsid()
if cur == None:
log('Couldn\'t determine ssid...')
self.reset(desired)
elif desired not in cur:
log('Currently connected to {}. Switching to {}.'.format(cur, desired))
self.reset(desired)
if __name__ == '__main__':
try:
win32serviceutil.HandleCommandLine(AppServerSvc)
except Exception as e:
log(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment