"""
Finds all Snom brand phones in a /24 and tells them to key in 6405 turn on
the hands free speaker.  (6405 is an extension that plays the stock monkies
sound from Asterisk)
"""

import urllib2
import socket
import sys

def enumerate_snom_ips(base):
    original_timeout = socket.getdefaulttimeout()
    socket.setdefaulttimeout(0.2)

    ips_to_check = [base + '.' + str(i) for i in range(2, 255)]
    snom_ips = []

    for ip in ips_to_check:
        try:
            data = urllib2.urlopen('http://' + ip + '/index.htm').read()
            if '<TITLE>snom 300</TITLE>' in data:
                snom_ips.append(ip)
        except KeyboardInterrupt:
            sys.exit()
        except:
            pass

    socket.setdefaulttimeout(original_timeout)

    return snom_ips


def send_command(ip, key):
    urllib2.urlopen('http://' + ip + '/command.htm?key=' + key).read()

def monkies(ip):
    for key in ['6', '4', '0', '5', 'SPEAKER']:
        send_command(ip, key)

print 'monkies.py - Finding all Snom phones...'
for ip in enumerate_snom_ips('10.10.12'):
    print ip
    monkies(ip)