Beispiel #1
0
def main(args):
    dir_path = args.directory
    file_name_regex = args.regex
    recurse_dirs = args.recurse

    if dir_path is None:
        dir_path = os.getcwd()

    if not os.path.exists(dir_path):
        print('Invalid directory "{}". Either the directory does not exist or read ' \
              'permissions are not available'.format(dir_path))
        sys.exit(1)

    for getmac_file_name in get_files(dir_path, file_name_regex, recurse_dirs):
        if os.path.exists(getmac_file_name):
            try:
                f = open(getmac_file_name, 'r')
                text = f.read()
            except UnicodeDecodeError:
                pass
            finally:
                f.close()

            macs = wired_mac_from_getmac(text)
            if len(macs) > 0:
                print("Sending WOL magic pack to {}, extracted from {}".format(
                    macs, getmac_file_name))
                for mac in macs:
                    wol.send_magic_packet(mac)
            else:
                print("No suitable MAC addresses where found in {}".format(
                    getmac_file_name))
def main(args):
    dir_path = args.directory
    file_name_regex = args.regex
    recurse_dirs = args.recurse

    if dir_path is None:
        dir_path = os.getcwd()

    if not os.path.exists(dir_path):
        print('Invalid directory "{}". Either the directory does not exist or read ' \
              'permissions are not available'.format(dir_path))
        sys.exit(1)

    for getmac_file_name in get_files(dir_path, file_name_regex, recurse_dirs):
        if os.path.exists(getmac_file_name):
            try:
                f = open(getmac_file_name, 'r')
                text = f.read()
            except UnicodeDecodeError:
                pass
            finally:
                f.close()

            macs = wired_mac_from_getmac(text)
            if len(macs) > 0:
                print("Sending WOL magic pack to {}, extracted from {}". format(macs, getmac_file_name))
                for mac in macs:
                    wol.send_magic_packet(mac)
            else:
                print("No suitable MAC addresses where found in {}". format(getmac_file_name))
Beispiel #3
0
    def process_command(self, command):
        cmd_list = command.split()
        if cmd_list[0] == "irsend":     # send IR signal
            self.send_IR(cmd_list[1], cmd_list[2])
        elif cmd_list[0] == "wol":      # wake on lan command
            wol.send_magic_packet(cmd_list[1])
        elif cmd_list[0] == "exec":     # execute an external command
            subprocess.call(cmd_list[1:])
        elif cmd_list[0] == "python":   # execute a python script
            python_cmd = cmd_list[1].split(".")
            the_method = python_cmd[-1]
            the_params = None
            if len(cmd_list) > 2:
                the_params = cmd_list[2:]   # retrieve the list of parameters

            the_module = ".".join(python_cmd[0:-1])
            method_attr = getattr(__import__(the_module), the_method)
            if the_params is None:
                method_attr(self)
            else:
                method_attr(self, *the_params)
        elif cmd_list[0] == "gpio":     # control rpi gpio
            self.do_gpio_command(cmd_list[1])
        elif cmd_list[0] == "say":
            cmdutils.say_something(" ".join(cmd_list[1:]))
    def run(self, context):
        """
        Run the test step
        """
        ComputerBase.run(self, context)

        self._logger.debug("Wake the computer with mac addr '%s'" % self._pars.mac_addr)
        wol.send_magic_packet(self._pars.mac_addr)

        self._logger.debug("Let the computer boot some time")
        time.sleep(self._pars.boot_expected_time)
        timeout = time.time() + self._pars.boot_timeout
        current = time.time()
        while True:
            try:
                computer_connection = self._computer.init()
                return True
            except SSHException as e:
                if current > timeout:
                    raise e
                else:
                    self._logger.info("Boot ongoing since %d on %d seconds" %
                                      (current, self._pars.boot_timeout))
                    time.sleep(5)
                    current = time.time()
Beispiel #5
0
def main():
    # Load the configuration
    with open(CONFIGFILE, 'r') as f:
        config = yaml.load(f.read())

    # Check if host is already online
    print("Checking if remote is already online...")
    if not check_host_online(config['remote_ip']):
        print("Remote is offline. Sending WOL packet to %s..." % config['remote_mac'])
        wol.send_magic_packet(config['remote_mac'])

        # Wait until host is reachable
        print("Waiting until remote is online...")
        while not check_host_online(config['remote_ip']):
            pass

    # Remote is online, prepare the backup process
    print("Starting backup.")
    print("Creating mountpoint %s..." % config['mountpoint'])
    try:
        os.mkdir(config['mountpoint'])
    except OSError as exc:
        print("FATAL: Failed to create mountpoint %s: %s" % (config['mountpoint'], str(exc)), file = sys.stderr)
        return

    # Do the backup
    for share in config['shares']:
        # Mount the share
        print("Mounting samba share //%s/%s on %s..." % (config['remote_ip'], share['name'], config['mountpoint']))
        fail = bool(os.system("mount -t cifs //%s/%s %s -o username=%s,password=%s,domain=%s" % (
            config['remote_ip'],
            share['name'],
            config['mountpoint'],
            share['username'],
            share['password'],
            share['domain'])))
        if fail:
            print("FATAL: Failed to mount //%s/%s on %s." % (config['remote_ip'], share['name'], config['mountpoint']), file = sys.stderr)
            return

        # Run rsync
        print("Backing up %s to //%s/%s..." % (share['source'], config['remote_ip'], share['name']))
        fail = bool(os.system("rsync -a -h --no-o --no-g --delete --progress %s %s" % (share['source'], config['mountpoint'])))
        if fail:
            print("WARNING: Backup of %s to //%s/%s failed or was incomplete." % (share['source'], config['remote_ip'], share['name']), file = sys.stderr)

        # Unmount the share
        print("Unmounting //%s/%s from %s..." % (config['remote_ip'], share['name'], config['mountpoint']))
        fail = bool(os.system("umount %s" % config['mountpoint']))
        if fail:
            print("FATAL: Failed to unmount //%s/%s from %s." % (config['remote_ip'], share['name'], config['mountpoint']), file = sys.stderr)
            return

    # Backup done, remove mountpoint
    print("Removing mountpoint %s..." % config['mountpoint'])
    try:
        os.rmdir(config['mountpoint'])
    except OSError as exc:
        print("FATAL: Failed to remove mountpoint %s: %s" % (config['mountpoint'], str(exc)), file = sys.stderr)
        return
Beispiel #6
0
def main(args):
    ping_response = os.system('ping -c 1 -w 5000 %s' % args.ipaddress[0])
    if ping_response == 0:
        print('%s is responding' % args.ipaddress[0])
    else:
        print('%s is not responding, ask for wake up' % args.ipaddress[0])
        wol.send_magic_packet(args.macaddress[0])
Beispiel #7
0
 def wakeup(self, host):
     success = True
     try:
         wol.send_magic_packet(host.mac, ip_address=host.ip)
     except:
         success = False
     return success
Beispiel #8
0
def start_stop_movie(cmdProcessor):
    ''' cmdProcessor is an instance of CommandProcessor '''
    # wakeonlan must be installed
    from wakeonlan import wol

    # get screen status
    screen_status = cmdProcessor.do_gpio_command("screen-read")
    if int(screen_status) == 1:         # screen is down, let's wrap up movie watching 
        # lights up the room
        cmdProcessor.do_gpio_command("light1-on")
        cmdProcessor.do_gpio_command("light2-on")

        # bring up the projector screen
        cmdProcessor.do_gpio_command("screen-off")

        # turn off the projector
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)

        # turn off the receiver
        cmdProcessor.send_IR("onkyo", "KEY_POWER")

        # turn off the media computer
        xbmc_send = cmdProcessor.config.get("misc", "xbmc_send")
        xbmc_host = cmdProcessor.config.get("misc", "xbmc_host")
        xbmc_port = cmdProcessor.config.get("misc", "xbmc_port")
        if xbmc_send and xbmc_host and xbmc_port:
            subprocess.call(
                [
                    xbmc_send,
                    "--host={0}".format(xbmc_host),
                    "--port={0}".format(xbmc_port),
                    "--action=XBMC.Powerdown"
                ]
            )
    else:
        # start movie watching
        xbmc_mac_address = cmdProcessor.config.get("misc", "xbmc_mac_address")

        # setup lights
        cmdProcessor.do_gpio_command("light2-on")
        cmdProcessor.do_gpio_command("light1-off")
        cmdProcessor.do_gpio_command("light3-off")

        # bring down projector screen
        cmdProcessor.do_gpio_command("screen-on")

        # turn on projector
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)

        # turn on receiver
        cmdProcessor.send_IR("onkyo", "KEY_POWER")    
        time.sleep(2)
        cmdProcessor.send_IR("onkyo", "KEY_DVD")
        
        # wake up media
        wol.send_magic_packet(xbmc_mac_address)
def callback_handler(bot, update):
    query = update.callback_query

    # Hue lights
    if query.data == 'lights_on':
        lights_response = hue_lights.lights_on()
        if lights_response:
            bot.answerCallbackQuery(query.id, text='Turning lights on...')
        else:
            bot.answerCallbackQuery(query.id, text='Lights are already on')
    elif query.data == 'lights_off':
        lights_response = hue_lights.lights_off()
        if lights_response:
            bot.answerCallbackQuery(query.id, text='Turning lights off...')
        else:
            bot.answerCallbackQuery(query.id, text='Lights are already off')

    # Piframe screen on/off
    elif query.data == 'screen_on':
        os.system('echo %s | sudo tee /sys/class/backlight/*/bl_power' % 0)
        bot.answerCallbackQuery(query.id, text='Turning screen on...')
    elif query.data == 'screen_off':
        os.system('echo %s | sudo tee /sys/class/backlight/*/bl_power' % 1)
        bot.answerCallbackQuery(query.id, text='Turning screen off...')

    # Wake on LAN
    elif query.data == 'computer':
        wol.send_magic_packet(config.get('computer', 'mac_address'))
        bot.answerCallbackQuery(query.id, text='Sending wake on LAN request')
Beispiel #10
0
def xon(void):
	if ticks==0:
		ticks==ticks+20
		print("XON event")
		val=True
		gpio.output(40,True)
		for i in conf["hosts"]:
			wol.send_magic_packet(i["mac"])
Beispiel #11
0
def xon(void):
    if ticks == 0:
        ticks == ticks + 20
        print("XON event")
        val = True
        gpio.output(40, True)
        for i in conf["hosts"]:
            wol.send_magic_packet(i["mac"])
Beispiel #12
0
 def act(self, client_address, state):
     print "State", state, "from client @", client_address
     if state == True:
         wol.send_magic_packet(tvMac)
         print "Magic packet sent to turn on TV!"
     if state == False:
         os.system("/usr/bin/node tv_shutdown.js")
         print "TV turned off!"
     return True
def action(objetxmpp, action, sessionid, data, message, dataerreur, result):
    print data
    try:
        wol.send_magic_packet(data['macaddress'])
        result['data']['start'] = "ok"
    except:
        dataerreur['data']['msg'] = "ERROR : plugin wakeonlan"
        dataerreur['ret'] = 255
        raise
Beispiel #14
0
def wake(mac_addr):
    try:
        from wakeonlan import wol
        wol.send_magic_packet(mac_addr)
    except ImportError as errno:
        print(bcolors.WARNING + "\nWake on lan tool not present on your system: {0}".format(errno) + bcolors.ENDC)
        # print ('Run: $ sudo pip install wakeonlan')
        try_install_wakeonlan()
        wake(mac_addr)
Beispiel #15
0
 def do(self, command):
     print "Will wake up a computer ", " ".join(command)
     ret = "no reconeguts"
     for wor in command:
         for pc in self.cfg["wol"]["pcs"]:
             if wor == pc["nom"]:
                 wol.send_magic_packet(pc["mac"])
                 ret = "OK"
     return ret
Beispiel #16
0
 def do(self, command):
     print "Will wake a computer ", " ".join(command)
     ret = "No conegut(s)"
     for arg in command:
         for pc in self.cfg["wol"]["pcs"]:
             if arg == pc["nom"]:
                 wol.send_magic_packet(pc["mac"])
                 ret = "OK"
     return ret
Beispiel #17
0
 def do(self, command):
     print "Will wake up a computer ", " ".join(command)
     ret = "no reconeguts"
     for wor in command:
         for pc in self.cfg["wol"]["pcs"]:
             if wor == pc["nom"]:
                 wol.send_magic_packet(pc["mac"])
                 ret = "OK"
     return ret
Beispiel #18
0
def start_stop_movie(cmdProcessor):
    ''' cmdProcessor is an instance of CommandProcessor '''
    # wakeonlan must be installed
    from wakeonlan import wol

    # get screen status
    screen_status = cmdProcessor.do_gpio_command("screen-read")
    if int(screen_status) == 1:  # screen is down, let's wrap up movie watching
        # lights up the room
        cmdProcessor.do_gpio_command("light1-on")
        cmdProcessor.do_gpio_command("light2-on")

        # bring up the projector screen
        cmdProcessor.do_gpio_command("screen-off")

        # turn off the projector
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)

        # turn off the receiver
        cmdProcessor.send_IR("onkyo", "KEY_POWER")

        # turn off the media computer
        xbmc_send = cmdProcessor.config.get("misc", "xbmc_send")
        xbmc_host = cmdProcessor.config.get("misc", "xbmc_host")
        xbmc_port = cmdProcessor.config.get("misc", "xbmc_port")
        if xbmc_send and xbmc_host and xbmc_port:
            subprocess.call([
                xbmc_send, "--host={0}".format(xbmc_host),
                "--port={0}".format(xbmc_port), "--action=XBMC.Powerdown"
            ])
    else:
        # start movie watching
        xbmc_mac_address = cmdProcessor.config.get("misc", "xbmc_mac_address")

        # setup lights
        cmdProcessor.do_gpio_command("light2-on")
        cmdProcessor.do_gpio_command("light1-off")
        cmdProcessor.do_gpio_command("light3-off")

        # bring down projector screen
        cmdProcessor.do_gpio_command("screen-on")

        # turn on projector
        cmdProcessor.send_IR("acer", "KEY_POWER")
        time.sleep(1)

        # turn on receiver
        cmdProcessor.send_IR("onkyo", "KEY_POWER")
        time.sleep(2)
        cmdProcessor.send_IR("onkyo", "KEY_DVD")

        # wake up media
        wol.send_magic_packet(xbmc_mac_address)
Beispiel #19
0
 def get(self):
     cmd = self.request.uri.replace('/RD/', '')
     if cmd == "ON" or cmd == "on":
         wol.send_magic_packet('e8:9d:87:12:34:56')
     if cmd == "OFF" or cmd == "off":
         subprocess.call(
             'curl --digest --user user:pass http://192.168.1.10/remote/remote.htm?key=12 &',
             shell=True)
     self.set_header('Content-type', 'text/plain; charset=ascii')
     self.write(cmd)
Beispiel #20
0
 def do(self, command):
     print "Will wake the computer", " ".join(command)
     ret = "Unknown PC SIR"
     for arg in command:
         for pc in self.cfg["wol"]["pcs"]:
             if arg == pc["nom"]:
                 print "Wake: ", pc["mac"]
                 wol.send_magic_packet(pc["mac"])
                 ret = "Wake Done SIR"
     return ret
Beispiel #21
0
def handle_wake_on_lan(req):
    machines = rospy.get_param('machines')
    if req.machine_name not in machines:
        rospy.logerror('No parameters found for machine "%s"', req.machine_name)
    else:
        rospy.logdebug('Waking up %s', req.machine_name)
        computer = NetworkComputer.FromParams(req.machine_name, machines[req.machine_name])
        if computer:
            wol.send_magic_packet(computer.mac_address)
    return WakeOnLanResponse()
Beispiel #22
0
def wake_up(nas_ip, nas_mac):
    wol.send_magic_packet(nas_mac)

    i = 0
    while i < 36 and not is_up(nas_ip):
        time.sleep(5)
        i += 1

    if i == 36:
        print "Timeout waking up" + nas_ip
        exit(1)
Beispiel #23
0
def power_handler(manager, event, state):
    if state.lower() == "on":
        wol.send_magic_packet(manager.args.mac_addr)

        yield from manager.send(event["channel"], "Powering on server.")

    elif state.lower() == "off":
        yield from manager.send(event["channel"], "Power off not implemented. Sorry! Coming soon!")

    else:
        yield from manager.send(event["channel"], "Unknown power state {}".format(state))
Beispiel #24
0
def handle(text, mic, profile):

    """
        Responds to user-input to control KODI.
        
        Current supports:
            -Pause / Play
            -Stop
            -Back
            -Up/Down/Left/Right
            -Info
            -Select

        Arguments:
        	text -- user-input, typically transcribed speech
       		mic -- used to interact with the user (for both input and output)
        	profile -- contains information related to the user (e.g., phone number)
    """
    if bool(re.search(r'\b{0}\b'.format("PAUSE"), text, re.IGNORECASE)) or bool(re.search(r'\b{0}\b'.format("PLAY"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Player.PlayPause','params':{'playerid':1},'id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("STOP"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Player.Stop','params':{'playerid':1},'id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("BACK"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Input.Back','id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("SELECT"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Input.Select','id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("Down"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Input.Down','id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("UP"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Input.Up','id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("INFO"), text, re.IGNORECASE)):
        data = {'jsonrpc':'2.0','method':'Input.Info','id':1}
        doJson(data, profile)
    elif bool(re.search(r'\b{0}\b'.format("START"), text, re.IGNORECASE)):
        try:
            wol.send_magic_packet(profile['kodi']['MAC'])
        except KeyError:
            print("Kodi mac adress was not defined")

        mic.say("The media center will be usable shortly")

    else:

        mic.say("Sorry I'm not aware of that KODI function yet")
Beispiel #25
0
def wake_hosts(hosts):
    print('Sending wake signal for hosts:')
    print(STRFORMAT.format('Hosts', '', 'SIGNAL'))
    wrong_hosts = []
    for host in hosts:
        if host in hosts_in_my_subnet:
            wol.send_magic_packet(hosts_in_my_subnet[host])
            print(STRFORMAT.format(host, '', 'sent'))
        else:
            wrong_hosts.append(host)
    if wrong_hosts:
        print('\nThe following hosts are not in the same subnet as this' +
              ' computer or do not exist:\n' + ' '.join(wrong_hosts) + '\n'
              'This program requires you to be logged in the same subnet\n' +
              'as the computer you want to send the wake signal.\n')
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the user's Gmail inbox, reporting on the number of unread emails
        in the inbox, as well as their senders.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., Gmail
                   address)
    """
    wol.send_magic_packet('00.24.1D.D1.2D.CA')

    mic.say('Turning on your desktop')
Beispiel #27
0
    def __init__(self, **kwargs):
        super(Wake_on_lan, self).__init__(**kwargs)

        self.mac_address = kwargs.get('mac_address', None)
        self.broadcast_address = kwargs.get('broadcast_address', '255.255.255.255')
        self.port = kwargs.get('port', 9)

        # check parameters
        if self._is_parameters_ok():
            # convert to unicode for testing
            broadcast_address_unicode = self.broadcast_address.decode('utf-8')
            # check the ip address is a valid one
            ipaddress.ip_address(broadcast_address_unicode)

            logger.debug("Call Wake_on_lan_neuron with parameters: mac_address: %s, broadcast_address: %s, port: %s"
                         % (self.mac_address, self.broadcast_address, self.port))

            # send the magic packet, the mac address format will be check by the lib
            wol.send_magic_packet(self.mac_address, ip_address=self.broadcast_address, port=self.port)
Beispiel #28
0
def application(request):
    print (request.args, request.base_url, request.data, request.files)
    try:
        if request.path == '/json':
            data = request.data.decode('utf-8') 
            print('json', data)
            
            js = json.loads(data)
            print (js['command'])
            command = js['command']
            if command == 'wol':
                wol.send_magic_packet('90-2B-34-D5-EC-0E')
                return Response('OK\n')
            
            return Response('Unknown command "' + command + '"\n' )
    except:
        return Response('Error\n')
    
    return Response('Unknown request\n')
Beispiel #29
0
def tv_power(state):
    if state:
        from wakeonlan import wol
        wol.send_magic_packet(sony_bravia_mac_address)
    else:
        import requests

        url = SONY_BRAVIA_URL

        payload = "<?xml version=\"1.0\"?>\n<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n    <s:Body>\n        <u:X_SendIRCC xmlns:u=\"urn:schemas-sony-com:service:IRCC:1\">\n            <IRCCCode>AAAAAQAAAAEAAAAvAw==</IRCCCode>\n        </u:X_SendIRCC>\n    </s:Body>\n</s:Envelope>"
        headers = {
            'content-type': "text/xml; charset=UTF-8",
            'x-auth-psk': "4169",
            'soapaction': "\"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC\"",
            'cache-control': "no-cache",
            'postman-token': "dda8bb69-1826-8e57-8091-5e777938557b"
        }

        response = requests.request("POST", url, data=payload, headers=headers)

        print(response.text)
def main():
    # Load the configuration
    with open(CONFIGFILE, 'r') as f:
        config = yaml.load(f.read())

    # Check if the target host is already running
    print("Checking if target is already online...")
    target_online = check_hosts([config['target_ip']])
    if target_online:
        print("Target is already online, exiting.")
        return

    # Check if any hosts are online
    print("Checking hosts...")
    online = check_hosts(config['ip_addresses'])
    if not online:
        print("No hosts online, exiting.")
        return

    # At least one host is online, send the WOL packet
    print("Sending WOL packet to %s..." % config['target_mac'])
    wol.send_magic_packet(config['target_mac'])
Beispiel #31
0
def command(device_ip, command_name):
    if (command_name == 'power on'):
        wol.send_magic_packet(mac)
        return True

    if "source" in command_name:
        command_name = "input"

    command_data = commands.get(command_name)
    if not command_data:
        return False

    body = """<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1"><IRCCCode>%s</IRCCCode></u:X_SendIRCC></s:Body></s:Envelope>""" % command_data[
        "value"]

    url = urlparse.urljoin('http://%s' % device_ip, 'sony/IRCC')
    resp = requests.post(url, data=body, headers={'Content-Type': 'text/xml'})

    if resp.status_code != 200:
        return False

    return True
Beispiel #32
0
def wol_menue():
    
    # read xml file and convert it do a dict.
    with open('hosts.xml') as fd:
        xml = xmltodict.parse(fd.read())

    # crate table with hosts
    table="""<table border="1">
    <tr>
    <td>Name</td><td>mac</td><td>IP</td><td>Info</td> <td>WakeUP</td>
    </tr>
    {0} </table>"""
    row=""
    for each in xml['hosts']['host']:
        row += """<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>
        <td>
        <form action="/apps/wol/wol.wsgi" method="get">
        <button name="mac" type="submit" value="{1}">Wake up</button>
        </form>
        </td></tr>""".format(each['name'], each['mac'], each['ip'], each['info'] )
    table= table.format(row)

    # crate final HTML page.
    html_out= html.format( xml['hosts']['title'], table)
    
    # POST methods
    try:
        wol_mac= request.query['mac']
        #print( wol_mac)
    except:
        wol_mac= None

    if wol_mac is not None:
        wol.send_magic_packet(wol_mac)

    return( html_out.encode('utf-8') )
Beispiel #33
0
def wakeup_pc():
    try:
        if NEEDS_WOL_PROXY == 'no':
            wol.send_magic_packet(PC_MAC_ADDRESS)
        else:
            wol.send_magic_packet(
                PC_MAC_ADDRESS, ip_address=WOL_PROXY_SERVER, port=9)
    except OSError:
        if NEEDS_WOL_PROXY == 'no':
            Clock.schedule_once(
                lambda dt: wol.send_magic_packet(PC_MAC_ADDRESS), 15)
        else:
            Clock.schedule_once(lambda dt: wol.send_magic_packet(
                PC_MAC_ADDRESS, ip_address=WOL_PROXY_SERVER, port=9), 15)

    except ValueError as e:
        print(e)
Beispiel #34
0
          <IRCCCode>"""+cmdcode+"""</IRCCCode>
        </u:X_SendIRCC>
      </s:Body>
    </s:Envelope>"""
    #print("Content : "+content)
    url = '/sony/IRCC'

    conn = http.client.HTTPConnection(sonyTv["ipaddress"])
    conn.request("POST",url, content, headers=headers)
    httpResponse = conn.getresponse()
    #print(httpResponse.status)
    return httpResponse.status


if result =="allume" :
    wol.send_magic_packet(sonyTv["mac"])
    print("Demande d'allumage envoyée.. patientez quelques secondes")
else :
    if testOn():
        print("La télé est bien allumée.")
        theCookie = majCookie()
        if theCookie != 0 :
            print("J'envoie la commande à la TV..")
            if handleCommand(result) != 200 :
                print("La commande n'a pas été reçue. J'efface le Cookie, et je relance la commande..")
                os.remove(os.path.dirname(os.path.abspath(__file__))+'\leCookie.txt')
                theCookie = majCookie()
                if theCookie != 0 :
                    print("J'envoie la commande à la TV..")
                    if handleCommand(result) != 200 :
                        print("La commande n'a pas été reçue. On dirait qu'il y a un problème..")
# This script has been tested with python 3.4.0
#
# CONFIGURATION:
# Edit all <fields> according to your data
#
######################################################################
# [email protected]
######################################################################

import json
import requests
import time
from wakeonlan import wol

# wake up on lan by sending a magic packet to the specified MAC address
wol.send_magic_packet('<00:..MACaddress>')

# lower this according to your boot time (seconds)
time.sleep(200)

# takes user input you can comment this out and hardcode the values with 'word'
rootpw = input("root pass: "******"passphrase to unlock volume: ")

# unlocks the drives
r = requests.post(
    'http://<yourNAS>/api/v1.0/storage/volume/<volumeName>/unlock/',
    auth=('root', rootpw),
    headers={'Content-Type': 'application/json'},
    verify=False,
    data=json.dumps({'passphrase': decryptkey}),
Beispiel #36
0
 def start_computer(self):
     """Start computer that it's turned off."""
     self.__puts('success', "Sends wakeon lan packet [%s]" % (self.macaddr))
     wol.send_magic_packet(self.macaddr)
Beispiel #37
0
def wake_command(chat, message, args):
    if controlInfopz(message) == True:
        wol.send_magic_packet('d8:cb:8a:9d:ec:50')
        chat.send('Pacchetto inviato')
    else:
        chat.send('Solo @infopz puo eseguire questo comando')
Beispiel #38
0
 def on(self):
     if not self.__macAddress:
         print "Client must have been powered on and paired before power on works"
     wol.send_magic_packet(self.__macAddress)
Beispiel #39
0
#!/usr/bin/python
from wakeonlan import wol
import time, argparse, paramiko


parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true', dest='wakeup')
parser.add_argument('-s', action='store_true', dest='shutdown')
args = parser.parse_args()


if args.wakeup:
    print 'Waking up ESXI Server'
    wol.send_magic_packet('f0.4d.a2.3c.f1.eb')

if args.shutdown:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.178.5', username='******', password='******')
    stdin, stdout, stderr = ssh.exec_command('powerOffVms && halt')
    print 'Shutting down ESXi Server'
    ssh.close()
def api_wake(mac):
    wol.send_magic_packet(mac)
    app.logger.debug('Sending Magic Packet to: %s' % mac)
    return ''
Beispiel #41
0
 def on(self):
     if not self.__macAddress:
         print "Client must have been powered on and paired before power on works"
     wol.send_magic_packet(self.__macAddress)
Beispiel #42
0
def api_wake(mac):
    wol.send_magic_packet(mac)
    app.logger.debug('Sending Magic Packet to: %s' % mac)
    return ''
Beispiel #43
0
 def wol(self,mac):
     wol.send_magic_packet(mac)
Beispiel #44
0
 def switch_on(self):
     wol.send_magic_packet(self.mac)
Beispiel #45
0
 def wake_host_up(mac):
   logger.info("Sending WOL to %s", mac)
   wol.send_magic_packet(mac)
# This script has been tested with python 3.4.0
#
# CONFIGURATION:
# Edit all <fields> according to your data
#
######################################################################
# [email protected]
######################################################################

import json
import requests
import time
from wakeonlan import wol

# wake up on lan by sending a magic packet to the specified MAC address
wol.send_magic_packet('<00:..MACaddress>')

# lower this according to your boot time (seconds)
time.sleep(200)

# takes user input you can comment this out and hardcode the values with 'word'
rootpw = input("root pass: "******"passphrase to unlock volume: ")

# unlocks the drives
r = requests.post(
        'http://<yourNAS>/api/v1.0/storage/volume/<volumeName>/unlock/',
        auth=('root', rootpw),
        headers={'Content-Type': 'application/json'},
        verify=False,
        data=json.dumps({'passphrase': decryptkey}),
Beispiel #47
0
def mac():
    mac = request.form["macaddr"]
    wol.send_magic_packet(mac)
    return "Your request has be sent to {}".format(mac)
def wakeserver():
    wol.send_magic_packet(MAC_ADDR, ip_address=IP_TARG)
    return 'Wake server successful'
Beispiel #49
0
def on():
    wol.send_magic_packet('3c:59:1e:cf:a0:f0', ip_address=TV)
    while (status()["power-mode"] != "PowerOn"):
        keypress("Power")
 def on(self):
     wol.send_magic_packet( self.TV_WiFi_MAC, self.TV_LAN_MAC )
     return 1==1
 def __wakeNode(remoteNode):
     try:
         wol.send_magic_packet(remoteNode.getMAC())
     except (AttributeError, TypeError):
         raise AssertionError('Input variables should be strings')
#!/usr/bin/python
# -*- coding: utf-8 -*-

from wakeonlan import wol

wol.send_magic_packet('**:**:**:**:**:**' ,ip_address='xxxxxxxxxxx', port=9)
Beispiel #53
0
 def wake(self, params):
     # wol.send_magic_packet('F8:0F:41:2B:84:94')
     wol.send_magic_packet(self._device.mac)
     return {"result": True}
Beispiel #54
0
 def wol(self):
     print("WOL Sent")
     wol.send_magic_packet('MAC ADDRESS')
Beispiel #55
0
def powerON():
 wol.send_magic_packet('mac address goes here')
Beispiel #56
0
def on_message(client, user_data, msg):
    data = json.loads(msg.payload)
    if 'mac' in data:
        wol.send_magic_packet(data['mac'])
"""
python wakeonlan实现电脑网络开机.py
http://bbs.bathome.net/thread-39732-1-1.html

2016年3月20日 13:03:16 codegay

https://pypi.python.org/pypi/wakeonlan/0.2.2
pip命令安装模块
pip install wakeonlan

把mac地址收集后,一行一个存在mac.txt中.
使用Wireshark抓了下包,发现多网卡的环境下是使用其中的一个网卡发送的.
广播包可能发不到指定的网段里,所以需要指定一下目标网段的IP.
"""
from wakeonlan import wol

with open("mac.txt") as f:
    for mac in f:
        wol.send_magic_packet(mac.strip(),ip_address="192.168.199.255")