HOW-TO:Set up Wake-on-LAN for Ubuntu: Difference between revisions

From Official Kodi Wiki
Jump to navigation Jump to search
>MacUsers
No edit summary
 
(38 intermediate revisions by 8 users not shown)
Line 1: Line 1:
{{XBMC wiki toc Inline}}
{{mininav| [[Linux]] }}
__NOEDITSECTION__
If you are not one of the lucky ones with a built-in start-up controller (so that the remote can be used to start the computer) or if the computer is in the other room/floor, sometimes it's pretty annoying to go to the upstairs, for example, just to push a button. Wake-On-LAN (WOL) is a network standard, which provides the ability to switch on remote computers through special network packets, called [[w:Wake-on-LAN#Magic packet|Magic Packet]] from sleeping, hibernating, or powered-off state. It only works with Wake-On-LAN compliant BIOS and NIC.
If you are not one of the lucky ones with a built-in start-up controller (so that the remote can be used to start the computer) or if the computer is in the other room/floor, sometimes it's pretty annoying to go to the upstairs, for example, just to push a button. Wake-On-LAN is a network standard, which provides the ability to switch on remote computers through special network packets, called [http://en.wikipedia.org/wiki/Wake-on-LAN#Magic_packet MagicPacket] from sleeping, hibernating, or powered-off state. It only works with WOL compliant BIOS and NIC.
== Before we start ==
==Before we start==
First of all, the motherboard should support Wake-On-LAN and it should be enabled in the BIOS.  
First off, the motherboard should support the WOL (Wake On LAN) and it should be enabled in the BIOS. Different BIOS/motherboard do it differently; on ASUS (P5N7A-VM), it's under Power > APM Configuration and in there "Resume On PCIE Wake" and "Resume On LAN(MAC)" should be enabled.


==Enabling WOL in the OS==
Different BIOSs and motherboards do this differently; for example on the ASUS P5N7A-VM, it's under ''Power > APM Configuration'' and in there ''Resume On PCIE Wake'' and ''Resume On LAN(MAC)'' should be enabled.
Even though WOL works in network layer 2, OS support is still one of the important things to make it work. Even if you see the light on the Ethernet port is on after the halt/shutdown, the OS shuts off the Ethernet internally. One must tell Ethernet controller to WOL when boots up and tell "halt" script not to bring down controller during shut-down.  
 
===Install ethtool===
== Enabling WOL in the OS ==
I found "ethtool" is one of the easiest to use to enable WOL; install it first if it's not there yet.
Even though Wake-On-LAN works in network layer 2, OS support is still one of the important things to make it work. Even if you see the Ethernet port LED is on after the halt/shutdown, the OS shuts off the Ethernet internally. One must tell Ethernet controller to WOL when boots up and tell "halt" script not to bring down controller during shut-down.  
=== Install ethtool ===
One of the easiest applications to use to enable Wake-On-LAN is ''ethtool''. Install it with:
<source lang="bash">
<source lang="bash">
sudo apt-get install ethtool
sudo apt-get install ethtool
</source>
</source>
===Set Wake-on-LAN options===
=== Setup ethtool WOL options ===
Run the following command to enable it:
Run the following command to enable it on ethX (where X is the Ethernet device number).
<source lang="bash">sudo ethtool -s eth0 wol g</source>
<source lang="bash">sudo ethtool -s eth0 wol g</source>
*Note: Not all devices support this.
* ''Note: Not all devices support this.''
This can be verified running ethtool on ethX (where X is the name/number of the Ethernet device).
The settings can be verified by running:
<source lang="bash">sudo ethtool eth0</source>
<source lang="bash">sudo ethtool eth0</source>
You should see something like this ("g" indicates Wake on MagicPacket is enabled):
<source lang="bash">
  Settings for eth0:
  Settings for eth0:
  Supported ports: [ MII ]
  Supported ports: [ MII ]
  Supported link modes:  10baseT/Half 10baseT/Full  
  Supported link modes:  10baseT/Half 10baseT/Full  
                        100baseT/Half 100baseT/Full
  ...
                        1000baseT/Full
         ...
  .....
         .....
Auto-negotiation: on
  Supports Wake-on: g
  Supports Wake-on: g
  Wake-on: g
  Wake-on: g
  Link detected: yes
  Link detected: yes
</source>
* ''Note: "g" indicates wake on Magic Packet is enabled''
=== Enable ethtool on Start-up ===
To have an application or service is running on startup, Ubuntu uses Upstart scripts which replace the old init scripts.


==Get it enabled at system start-up==
The following commands; create ''wakeonlan.conf'' with the upstart code to run wakeonlan (as per example above), set the file to exectuable, and start the service<ref>http://askubuntu.com/questions/47918/how-can-i-enable-wake-on-lan-permanently</ref>:
Debian/Ubuntu uses Sys-V like init system for executing commands during the system bootup and shutdown time. If you wish to add a new service to start when the machine boots the script should be added to the directory /etc/init.d/ and then the "/etc/rc{runlevel}.d/" symlinks cause the script to be executed.
===The init.d script===
Create a file, say "wake-on-lan" in the "/etc/init.d/" (just copy & paste the entire code in the terminal)
<source lang="bash">
<source lang="bash">
sudo cat << EOF >> /etc/init.d/wake-on-lan
sudo bash -c "cat > /etc/init/wakeonlan.conf" <<'EOF'
#!/bin/bash
start on started network
#
### BEGIN INIT INFO
# Provides:            wake-on-lan
# Required-Start:      \$local_fs
# Required-Stop:        \$local_fs
# Default-Start:        2 3 4 5
# Default-Stop:        0 6
# Short-Description:    Enable Wake-On-Lan
### END INIT INFO
#
. /lib/lsb/init-functions


do_start() {
script
     ethtool -s eth0 wol g
    interface=eth0
    exit
    logger -t 'wakeonlan init script' enabling wake on lan for $interface
}
     ethtool -s $interface wol g
end script
EOF
</source><br />


do_stop() {
<source lang="bash">
    ethtool -s eth0 wol d
sudo chmod +x /etc/init/wakeonlan.conf
    exit
</source><br />
}


case "\$1" in
<source lang="bash">
  start )
sudo service wakeonlan start
        do_start
        ;;
  restart|reload|force-reload )
        echo "Error: argument '\$1' not supported" >&2
        exit 3
        ;;
  stop )
        do_stop
        ;;
  * )
        echo "Usage: \$0 start|stop" >&2
        exit 3
        ;;
esac
EOF
sudo chmod 755 /etc/init.d/wake-on-lan
</source>
</source>


===Automatic start-up at boot===
== Waking with Magic Packet ==
"sysv-rc-conf" is run-level configuration for Sys-V like init script links. From the man page: sysv-rc-conf gives an easy to use interface for managing "/etc/rc{runlevel}.d/" symlinks. sysv-rc-conf is not installed by default and needs to be installed first.
Wake-on-LAN is platform-independent; any application that sends "magic packets" can wake up computers from shutdown state (as long mains power is not off) regardless of the OS it boots into afterwards.
<source lang="bash">sudo apt-get install sysv-rc-conf</source>
and when done, we enable the wake-on-lan service for runlevel 2,3,4 & 5, using --level option
<source lang="bash">sudo sysv-rc-conf --level 2345 wake-on-lan on</source>
If everything goes well, you should see the WOL is enabled for the above run-levels.
xbmc@htpc:~$ sysv-rc-conf --list | grep wake
wake-on-lan  2:on 3:on 4:on 5:on
That's all, the machine is now ready to be waken-up by WOL [http://en.wikipedia.org/wiki/Wake-on-LAN#Magic_packet magic packet].


== Extra info ==
The following steps are for setting up a Wake-on-LAN application on Ubuntu but there are many applications available, including for Windows and Mac OS X, that accomplish the same task.
Wake-on-LAN is platform-independent; any application that sends "magic packets" can wake up computers from shutdown state (as long mains power is not off) regardless of OS it boots into afterward. There are a number of tools available for Windows in the net. I use this script to create a magic-packet from Linux. The "node_lst" section (at the top of the script) should be modified to reflect actual MAC address of the machine in question. Put the script in the "/usr/local/bin" and change the permission to 775, so that it can be called from any where without specifying the actual path.
=== The script: wake-on-lan ===
<source lang="bash">sudo vi /usr/local/bin/wake-on-lan</source>
Use any editor you are comfortable with to use and then copy & paste the script below.
<source lang="python">
exec /usr/bin/python -x "$0" "$@"
# -*- coding: ISO-8859-15 -*-
#
# wake-on-lan
# $Id: wake-on-lan.cin,v 1.0 2010/02/20 15:05:42 das Exp $
# S. Das, London


## --- Local nodes -------------------------- ##
Install our Wake-on-LAN application, in this case ''powerwake'', as it has IP and hostname options.
## Modify this to put your own hostname/MAC
<source lang="bash">
## address pair here. The format is:
sudo apt-get install powerwake
## "abc xx:xx:xx:xx:xx:xx", where "abc" could
</source>
## be any name you like and the "xx:xx..." is
## the MAC address of the machine the magic
## packet is going to be sent.
 
node_lst = [
'pcbk 00:18:8b:c9:29:73',
'htpc 00:24:7c:a2:e4:d0'
]


## --- don't change anything below --------- ##
The simplest usage of powerwake is to just supply the IP address or hostname of the machine you want to wake:
<source lang="bash">
powerwake 192.168.1.1
</source><br />


import os,sys,string,commands
<source lang="bash">
import struct, socket
powerwake xbmc-hostname.local
import re,random
</source>
* ''Note: To enable powerwake to cache the remote machine MAC address you may need to run it once with the remote machine awake.''
If everything goes well, as described above, you should now be seeing the machine in the other room booting up.


retval = 0
== Finishing Touches ==
<div id="Finishing Touches"></div>


X = '([a-zA-Z0-9]{2}[:|\-|.]?){5}[a-zA-Z0-9]{2}'
=== Aliases ===
S = re.compile(r'\s+')
You can make it even easier to run the above application from the command line or other scripts. One way is to include aliases to it in your .bashrc file, found in your user's home directory. Open the file in your preferred text editor and scroll to the bottom of the file, then add one or more of the lines below, depending on what you need to do.
<source lang="bash">nano ~/.bashrc</source><br />


mmap = {}
<source lang="bash">
# User Defined Aliases
alias htpcwol="powerwake xbmc-hostname.local"
alias htpcssh="powerwake xbmc-hostname.local; ssh [email protected]"
</source>
Save and exit, then run the following to reload it (normally loaded automatically at startup):
<source lang="bash">source ~/.bashrc</source>


## First argument 'None' in str.translate is new in 2.6.
You will now have two new commands (aliases) available for use from the command line; the first alias ''htpcwol'' simple wakes the host up remotely and the second one ''htpcssh'' also wakes it up but then creates an SSH session to the remote machine.
## Previously, it was a string of 256 characters.
if sys.version_info < (2, 6):
    f1_arg = ''.join(chr(i) for i in xrange(256))
else:
    f1_arg = None


def WakeOnLan(mac_address):
Aliases are a huge time saver if you use the command line for remote access often and there are many examples on the internet.<ref>http://www.howtogeek.com/73768/how-to-use-aliases-to-customize-ubuntu-commands/</ref>
   
    ## Building the Wake-On-LAN "Magic Packet"...
    ## Pad the synchronization stream.
    data = ''.join(['FFFFFFFFFFFF', mac_address * 20])
    msg = ''


    ## Split up the hex values and pack.
=== Suspend or Hibernate from command line ===
    for i in range(0, len(data), 2):
To suspend the remote machine from within an SSH session set the suspend command to run several minutes in the future:<ref>http://askubuntu.com/questions/35719/how-do-i-suspend-over-ssh</ref>
        msg = ''.join([msg, struct.pack('B', int(data[i: i + 2], 16))])
<source lang="bash">
echo 'pm-suspend' | sudo at now + 3 minutes
</source>


    ## ...and send it to the broadcast address using UDP
You can then disconnect safely from the SSH session and the remote machine will suspend at the set time.
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.sendto(msg, ('10.0.11.127', 9))
    s.close()


def sys_exit():
=== Using the Kodi remote control iOS app ===
    sys.stdout.flush()
Commands to ''shutdown'' systems often work best when issuing them against MAC addresses. If you are using the Kodi Remote Control app on the iPad or iPhone, you must supply the MAC address (or: HWaddr) of your NIC in the setup. I can now shutdown and startup Kodi from the app.
    sys.exit(1)


## check if hostname is provided
To find out the HWaddr on Ubuntu use this command:
if len(sys.argv) != 2:
<source lang="bash">
    print "Usage: %s <hostname>" % sys.argv[0]
ifconfig | grep HWaddr
    sys_exit()
</source>


for i in node_lst:
== References ==
    # strip off everything from first "#" found
<references/>
    i = i.split('#',1)[0]
    if not re.search(X, i):
continue


    h = S.split(i,1)[0]            ## host name
[[Category:How-to|Wake]]
    m = S.split(i,1)[-1]            ## MAC address
[[Category:Linux]]
    mmap[h] = m.strip('\t|" "')
 
 
for j, k in mmap.iteritems():
    if sys.argv[1] == j:
if not re.search(X.replace('zA-Z','fA-F'), k):
    print "Invalid MAC address [",k,"]; nothing to do!!"
    sys_exit()
else:
    WakeOnLan(k.translate(f1_arg,':.-'))
    print "WOL request has been sent to %s [%s]" % (j,k)
    break
else:
    print "Host [%s] doesn't exist!!" % sys.argv[1]
    sys_exit()
</source>
Replace the sample MAC address[es] with the original ones. The "hostname" part doesn't have to be the actual host-name though and could be any thing - it's just to substitute the hard-to-remember MAC address with something easier to write whilst running the script. Don't forget to change the file-mode to 755
<source lang="bash">sudo chmod 755 /usr/local/bin/wake-on-lan</source>
Run the script like this: ''wake-on-lan <hostname>''; and the output should be something like this:
[admin@b_server WOL]$ wake-on-lan htpc
WOL request has been sent to htpc [00:24:7c:a2:e4:d0]
If everything goes well as describe above, you should be seeing the machine in the other room is booting up.
[[category:How To|Linux]]
[[category:Inner Workings]]
[[category:Development]]
[[category:Linux]]
[[category:XBMC Live]]
[[category:To-Do]]

Latest revision as of 23:12, 20 June 2017

Home icon grey.png   ▶ Linux ▶ HOW-TO:Set up Wake-on-LAN for Ubuntu

If you are not one of the lucky ones with a built-in start-up controller (so that the remote can be used to start the computer) or if the computer is in the other room/floor, sometimes it's pretty annoying to go to the upstairs, for example, just to push a button. Wake-On-LAN (WOL) is a network standard, which provides the ability to switch on remote computers through special network packets, called Magic Packet from sleeping, hibernating, or powered-off state. It only works with Wake-On-LAN compliant BIOS and NIC.

Before we start

First of all, the motherboard should support Wake-On-LAN and it should be enabled in the BIOS.

Different BIOSs and motherboards do this differently; for example on the ASUS P5N7A-VM, it's under Power > APM Configuration and in there Resume On PCIE Wake and Resume On LAN(MAC) should be enabled.

Enabling WOL in the OS

Even though Wake-On-LAN works in network layer 2, OS support is still one of the important things to make it work. Even if you see the Ethernet port LED is on after the halt/shutdown, the OS shuts off the Ethernet internally. One must tell Ethernet controller to WOL when boots up and tell "halt" script not to bring down controller during shut-down.

Install ethtool

One of the easiest applications to use to enable Wake-On-LAN is ethtool. Install it with:

sudo apt-get install ethtool

Setup ethtool WOL options

Run the following command to enable it on ethX (where X is the Ethernet device number).

sudo ethtool -s eth0 wol g
  • Note: Not all devices support this.

The settings can be verified by running:

sudo ethtool eth0
 Settings for eth0:
 	Supported ports: [ MII ]
 	Supported link modes:   10baseT/Half 10baseT/Full 
 	...
         ...
 	Supports Wake-on: g
 	Wake-on: g
 	Link detected: yes
  • Note: "g" indicates wake on Magic Packet is enabled

Enable ethtool on Start-up

To have an application or service is running on startup, Ubuntu uses Upstart scripts which replace the old init scripts.

The following commands; create wakeonlan.conf with the upstart code to run wakeonlan (as per example above), set the file to exectuable, and start the service[1]:

sudo bash -c "cat > /etc/init/wakeonlan.conf" <<'EOF'
start on started network

script
    interface=eth0
    logger -t 'wakeonlan init script' enabling wake on lan for $interface
    ethtool -s $interface wol g
end script
EOF


sudo chmod +x /etc/init/wakeonlan.conf


sudo service wakeonlan start

Waking with Magic Packet

Wake-on-LAN is platform-independent; any application that sends "magic packets" can wake up computers from shutdown state (as long mains power is not off) regardless of the OS it boots into afterwards.

The following steps are for setting up a Wake-on-LAN application on Ubuntu but there are many applications available, including for Windows and Mac OS X, that accomplish the same task.

Install our Wake-on-LAN application, in this case powerwake, as it has IP and hostname options.

sudo apt-get install powerwake

The simplest usage of powerwake is to just supply the IP address or hostname of the machine you want to wake:

powerwake 192.168.1.1


powerwake xbmc-hostname.local
  • Note: To enable powerwake to cache the remote machine MAC address you may need to run it once with the remote machine awake.

If everything goes well, as described above, you should now be seeing the machine in the other room booting up.

Finishing Touches

Aliases

You can make it even easier to run the above application from the command line or other scripts. One way is to include aliases to it in your .bashrc file, found in your user's home directory. Open the file in your preferred text editor and scroll to the bottom of the file, then add one or more of the lines below, depending on what you need to do.

nano ~/.bashrc


# User Defined Aliases
alias htpcwol="powerwake xbmc-hostname.local"
alias htpcssh="powerwake xbmc-hostname.local; ssh [email protected]"

Save and exit, then run the following to reload it (normally loaded automatically at startup):

source ~/.bashrc

You will now have two new commands (aliases) available for use from the command line; the first alias htpcwol simple wakes the host up remotely and the second one htpcssh also wakes it up but then creates an SSH session to the remote machine.

Aliases are a huge time saver if you use the command line for remote access often and there are many examples on the internet.[2]

Suspend or Hibernate from command line

To suspend the remote machine from within an SSH session set the suspend command to run several minutes in the future:[3]

echo 'pm-suspend' | sudo at now + 3 minutes

You can then disconnect safely from the SSH session and the remote machine will suspend at the set time.

Using the Kodi remote control iOS app

Commands to shutdown systems often work best when issuing them against MAC addresses. If you are using the Kodi Remote Control app on the iPad or iPhone, you must supply the MAC address (or: HWaddr) of your NIC in the setup. I can now shutdown and startup Kodi from the app.

To find out the HWaddr on Ubuntu use this command:

ifconfig | grep HWaddr

References