Wake on lan linux отправить команду

Wake on lan linux отправить команду

опять перейдёт в состояние «d» и, если вам нужно, добавьте приведённую выше
команду куда-нибудь в /etc/rc.local.

Это может не работать (или не сработать второй раз), если выполнялся сброс (переинициализации) карты (в том числе — на ноутбуках после «сна»).

Лучше это делать из:
— Ubuntu/Ddebian: /etc/network/interfaces в post-up / pre-down
— AltLinux — в /etc/net/ifaces/ethX/ifup-post
— в других — в соотв. местах, выполняемых _каждый раз_ после инициализации устройства или перед его отключением.

1.4 , Р ( ? ), 12:58, 21/12/2010 [ответить] + / –
хочу через интернет. )))

1.6 , Alex ( ?? ), 01:17, 27/12/2010 [ответить] + / –
> девятый порт, помеченный в /etc/services как discard, что означает то, что
> пакет с этого порта отправить не получится

Бред, это просто название протокола, RFC863.

1.7 , sam ( ?? ), 17:23, 29/12/2010 [ответить] + / –
Прошу добавить в статью важный момент, я сам полчаса мучался пока не дошло до меня посмотреть куда уходят пакеты tcpdump-ом

Если на компьютере несколько сетевых карт обязательно нужно указать в параметр -i адрес

Например, если нужно разбудить комп с адресом 192.168.2.34 в сети 192.168.2.0/24 то можно так и указать например широковещательный адрес сети

Источник

Wake on lan linux отправить команду

Как настроить Wake On Lan в Linux-01

Всем привет сегодня расскажу как настроить Wake On Lan в Linux.

WakeOnLan (WOL) — это технология позволяющая включить компьютер, методом отправки на него специального пакета данных, называемыми Magic Packet. Принцип работы этой технологии таков, что при выключении компьютера он переходит в дежурный режим и переводит сетевую карту в режим пониженного потребления, просматривая все поступающие пакеты из сети. Если сетевой адаптер обнаружит Magic Packet, он выдаст сигнал на включение компьютера. Примечание: для использования данной технологии необходима поддержка данной функции (технологии) сетевым адаптером, почти все современные сетевые адаптеры поддерживают данную технологию.

В данном посте мы рассмотрим настройку данной функции на примере ОС Linux.

1. В первую очередь мы просмотрим список наших сетевых интерфейсов используя утилиту ethtool:
ifconfig

В ответ получим список наших используемых сетевых интерфейсов (в моём случае он 1):

eth0 Link encap:Ethernet HWaddr 6c:62:6d:f0:ce:b4
inet6 addr: fe80::6e62:6dff:fef0:ceb4/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4528 errors:0 dropped:0 overruns:0 frame:0
TX packets:491 errors:0 dropped:0 overruns:0 carrier:1
collisions:0 txqueuelen:1000
RX bytes:686281 (670.1 KiB) TX bytes:61590 (60.1 KiB)

Нам необходим интерфейс который имеет доступ к внешней сети (в моём случае eth0). Теперь проверим поддерживает ли сетевой адаптер данную технологию и настроим её используя утилиту ethtool. Устанавливаем её:
apt-get install ethtool — для Debian
yum install ethtool — для CentOS

и запустим её, для просмотра информации о сетевом интерфейсе:
ethtool eth0

В ответ мы получим всю информацию о нашем сетевом интерфейсе:

Settings for eth0:
Supported ports: [ TP ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Advertised link modes: Not reported
Advertised pause frame use: No
Advertised auto-negotiation: Yes
Speed: 100Mb/s
Duplex: Full
Port: Twisted Pair
PHYAD: 0
Transceiver: internal
Auto-negotiation: on
MDI-X: Unknown
Supports Wake-on: pg
Wake-on: d
Current message level: 0x0000003f (63)
drv probe link timer ifdown ifup
Link detected: yes

Где Supports Wake-on: pg — означает что наш сетевой интерфейс поддерживает технологию Wake On Lan, Wake-on: d — но она отключена.

Wake On Lan можно включить вручную 1 командой, но при каждой перезагрузке нашей машины он будет деактивироватся, для этого мы создадим и будем использовать специальный скрипт.
Для этого выполняем следующее:
cd /etc/init.d/
nano wakeonlanconfig

Добавляем в скрипт строки:
#!/bin/bash
ethtool -s eth0 wol g
exit

Даём права скрипту:
chmod a+x wakeonlanconfig

Создаём символическую ссылку и делаем наш скрипт исполняемым:
update-rc.d -f wakeonlanconfig defaults

Проверяем что всё нормально вводим команду:
/etc/init.d/wakeonlanconfig

Если ничего в ответ не получили, значит всё хорошо и можно проверить на практике.

Вот так вот просто настроить Wake On Lan в Linux

Источник

Ubuntu Documentation

This page explains how to enable use of Wake-on-LAN (WoL) in systems that have Ubuntu installed.

Wake-on-LAN enables users to turn on a computer across a network from another network device. It can be very useful in situations where computers are not all next to each other or there are a lot of machines. WoL works by sending a packet of data called a Magic Packet™ to the target machine. When the packet is received, the target machine’s network device (Network Interface Controller or NIC) wakes-up the rest of the machine.

In order to use WoL it must be supported and enabled as necessary in the BIOS, NIC and other network hardware (routers, switches etc). You may also need to configure some software if things don’t work out-of-the-box.

Enabling WoL in the BIOS

This section may differ depending on whether or not you have a NIC integrated into your motherboard.

Using an Integrated NIC

To enable WoL in the BIOS, enter the BIOS setup and look for something called «Wake up on PCI event», «Wake up on LAN» or similar. Change it so that it is enabled. Save your settings and reboot.

Using a Non-Integrated NIC

If your NIC is not integrated into your motherboard, you will still have to configure your BIOS to allow devices to wake up your computer. Boot your computer and enter the BIOS settings menu. In one of the sub-menus there will hopefully be the option to allow USB and/or PCI devices to wake-up the computer. Enable the setting that is appropriate for your NIC. Save your settings and reboot.

PCI NICs sometimes require a cable connection to the power supply in order to stay awake when the computer is off/asleep. Check your manual to see if yours does and install if necessary.

Enabling WoL in the NIC

Determining whether the NIC supports WoL

First, determine which NIC will be used, and then check whether it supports the Magic Packet™ using

where is the device name of your NIC, e.g. eth0. This command will output some information about your the capabilities of your NIC. If this output contains a line similar to the following:

where contains the letter g, the NIC should support the WoL Magic Packet™ method (for the other letters look at man ethtool).

Enabling WoL in the NIC

To check whether WoL is enabled in the NIC, one could use

If contains g and not d, then Magic Packet™ is enabled. However, if does contain d, WoL needs to be enabled by running the following command:

On most systems, issuing this command is required after each boot. If the system’s networking is configured via ifupdown, then it is easy to add the line up ethtool -s wol g below the interface’s configuration stanza in /etc/network/interfaces. For example:

This will ensure that WoL is enabled in the NIC on each boot. Fore more information see the interfaces manual.

Testing Wake-On-LAN

Test WoL by powering off the system and trying to send it the magic packet using:

Command-line tools

GTK+ tool

Configure other operating systems

If the system dual-boots with other operating systems, they should be configured to also enable or, at least, not disable WoL in the NIC. This is beyond the scope of this document but here’s a starting point for Microsoft’s OS’s.

Troubleshooting

If WoL is not working as expected, there are a number of lines of investigation to follow:

  • Check that the power management options for your BIOS and NIC support WoL and are enabled as described above.
  • Verify that the packets sent to wake the target computer are indeed reaching their intended desination.
    • You may be able to verify the presence of packets by watching the network activity indicator LED on your switch or router. This is easier to see if you send multiple packets as you can count them.

    Ensure that no other network configuration software is interfering with WoL activity. network-manager may interfere with WoL activity in certain situations; removing it and configuring your network manually may solve some issues.

    Magic Packet Technology — A white paper describing the specification and implemenation of Magic Packet™ technology from AMD, one of its two co-developers.

WakeOnLan (последним исправлял пользователь g1orgosp 2015-08-31 14:29:10)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник

WOL: Приключения «Волшебного Пакета» в Linux

Совсем недавно LeeMiller описал как воспользоваться посылкой «волшебного пакета» для удаленного включения компьютера под управлением Windows, большое ему спасибо.
Очень странно, что ни кто не спросил в комментариях, — А как же быть с Линуксом? Ничего не получается, у него нет, как минимум, Пуск — Панель Управления — Сетевые Подключения!

Либо все и так всё знают, либо это никому не надо, но я, всё же, рискну об этом написать.
Пост будет творческой переработкой моего стародавнего HowTo, опубликованного на forum.ubuntu.ru, написанного, в свою очередь, после чтения англоязычных мануалов.

UPD: перенёс в «Железо», поближе к топику-мотиватору. Смотрится странно, выслушаю пожелания на перенос в другое место.

Всю теорию и настройку BIOS’а я опускаю, её замечательно разобрал LeeMiller.
Нашей задачей будет заставить сетевую карту оставаться в ждущем режиме после выключения компьютера. Если в Windows для этого достаточно поставить одну галку, то в Linux настройки сетевой карты не запоминаются и надо их производить при каждом запуске системы. Для этого понадобится сделать скриптик и поставить его на загрузку ОС.
Опыты ставились над Ubuntu, но я думаю что с «другими линуксами» проблем возникнуть не должно.

Приступим

Наблюдаем результат наподобие
eth0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::215:f2ff:fe6f:3487/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:71495 errors:0 dropped:0 overruns:0 frame:0
TX packets:76190 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:23164212 (22.0 MiB) TX bytes:7625016 (7.2 MiB)
Interrupt:217 Base address:0xd400

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:1290 errors:0 dropped:0 overruns:0 frame:0
TX packets:1290 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:161182 (157.4 KiB) TX bytes:161182 (157.4 KiB)

В данном примере у нас одна сетевая карта, eth0. Если карт несколько, то их несколько 🙂

— Теперь создаем сам скрипт, для этого сначала необходимо получить права администратора:

Здесь я хочу обратить внимание на параметры: -s eth0 wol значит «заставить WOL карточки eth0» g — «ждать волшебного пакета». У WOL есть еще пяток вариантов чего ждать, но к данной теме это не относится.

Если никакого вывода не последовало и показалась следующая строка ввода — значит всё прошло гладко.

— Проверяем на практике.
Распечатываем данное руководство, выключаем первый компьютер и идём ко второму 🙂
Шлём пакет одним из предложенных LeeMiller’ом способов. Если способы не нравятся — рекомендую свой любимый, простенький веб-сервис, которым можно воспользоваться даже при помощи браузера в сотовом телефоне.

Хочу обратиться к тем, кто умнее меня, — если есть (наверняка есть) более красивый способ реализации — сообщайте, будем обновлять знания!

И благодарю LeeMiller’a за то что отсыпал кармы из волшебного пакета, без этого ничего бы не вышло.

Источник

Wake-on-LAN

Wake-on-LAN (WoL) is a feature to switch on a computer via the network.

Contents

Hardware settings

The target computer’s motherboard and Network Interface Controller have to support Wake-on-LAN. The target computer has to be physically connected (with a cable) to a router or to the source computer for WoL to work properly. Some wireless cards have support for Wake on Wireless (WoWLAN or WoW).

The Wake-on-LAN feature also has to be enabled in the computer’s BIOS. Different motherboard manufacturers use slightly different language for this feature. Look for terminology such as «PCI Power up», «Allow PCI wake up event» or «Boot from PCI/PCI-E».

Note that some motherboards are affected by a bug that can cause immediate or random #Wake-up after shutdown whenever the BIOS WoL feature is enabled.

Software configuration

Enable WoL on the network adapter

Depending on the hardware, the network driver may have WoL switched off by default.

To query this status or to change the settings, install ethtool , determine the name of the network interface, and query it using the command:

The Wake-on values define what activity triggers wake up: d (disabled), p (PHY activity), u (unicast activity), m (multicast activity), b (broadcast activity), a (ARP activity), and g (magic packet activity). The value g is required for WoL to work, if not, the following command enables the WoL feature in the driver:

This command might not last beyond the next reboot and in this case must be repeated via some mechanism. Common solutions are listed in the following subsections.

Make it persistent

Link-level configuration is possible through systemd-networkd#link files. The actual setup is performed by the net_setup_link udev builtin. Add the WakeOnLan option to the network link file:

Also see systemd.link(5) for more information.

systemd service

This is an equivalent of previous systemd.link option, but uses a standalone systemd service.

Alternatively install the wol-systemd AUR package, then activate this new service by starting wol@interface.service .

udev is capable of running any command as soon as a device is visible. The following rule will turn on WOL on all network interfaces whose name matches enp* . The file name is important and must start with a number between 81 and 99 so that it runs after 80-net-setup-link.rules , which renames interfaces with predicable names. Otherwise, NAME would be undefined and the rule would not run.

The $name placeholder will be replaced by the value of the NAME variable for the matched device.

A command can be run each time the computer is (re)booted using «@reboot» in a crontab. First, make sure cron is enabled, and then edit a crontab for the root user that contains the following line:

netctl

If using netctl, one can make this setting persistent by adding the following the netctl profile:

NetworkManager

NetworkManager provides Wake-on-LAN ethernet support. One way to enable Wake-on-LAN by magic packet is through nmcli.

First, search for the name of the wired connection:

By following, one can view current status of Wake-on-LAN settings:

Enable Wake-on-LAN by magic packet on that connection:

Then reboot, possibly two times. To disable Wake-on-Lan, substitute magic with ignore .

The Wake-on-LAN settings can also be changed from the GUI using nm-connection-editor .

You can disable Wake-on-Lan for all connections permanently by adding a dedicated configuration file :

Enable WoL in TLP

When using TLP for suspend/hibernate, the WOL_DISABLE setting should be set to N in /etc/tlp.conf to allow resuming the computer with WoL.

Trigger a wake up

To trigger WoL on a target machine, its MAC address must be known. To obtain it, execute the following command from the machine:

Here the MAC address is 48:05:ca:09:0e:6a .

In its simplest form, Wake-on-LAN broadcasts the magic packet as an ethernet frame, containing the MAC address within the current network subnet, below the IP protocol layer. The knowledge of an IP address for the target computer is not necessary, as it operates on layer 2 (Data Link).

If used to wake up a computer over the internet or in a different subnet, it typically relies on the router to relay the packet and broadcast it. In this scenario, the external IP address of the router must be known. Keep in mind that most routers by default will not relay subnet directed broadcasts as a safety precaution and need to be explicitly told to do so.

Applications that are able to send magic packets for Wake-on-LAN:

  • gWakeOnLAN — GTK utility to awake turned off computers through the Wake-on-LAN feature.

https://muflone.com/gwakeonlan/english/ || gwakeonlan

  • wol — Implements Wake-on-LAN functionality in a small program. It wakes up hardware that is Magic Packet compliant. Note: This application will need the port changed to 9 from the default(40000) using the -p argument/flag.

https://sourceforge.net/projects/wake-on-lan/ || wol

  • wol_qt — Qt utility with integrated ARP scan to find MAC addresses and batch sending of Wake-on-LAN packets.

https://github.com/stefmitropoulos/wol_qt || wol_qtAUR

On the same LAN

If you are connected directly to another computer through a network cable, or the traffic within a LAN is not firewalled, then using Wake-on-LAN should be straightforward since there is no need to worry about port redirects.

In the simplest case the default broadcast address 255.255.255.255 is used:

To broadcast the magic packet only to a specific subnet or host, use the -i switch:

Across the internet

When the source and target computers are separated by a NAT router, different solution can be envisaged:

  • If the router supports WoL, one can rely on it to properly broadcast the packet into the local network.

Otherwise Wake-on-Lan can be achieved via port forwarding. The router needs to be configured using one of these two options:

  • Forward a different port to each target machine. This requires any target machine to have a static IP address on its LAN.
  • Forward a single port to the broadcast address. Most routers do not allow to forward to broadcast, however if you can get shell access to your router, through telnet, ssh, serial cable or other mean, run the command: This example assumes the network is 192.168.1.0/24 and uses net0 as network interface. Now, forward UDP port 9 to 192.168.1.254. This solution was successfully tested on a Linksys WRT54G running Tomato, and on the Verizon FIOS ActionTec router. For notes on how to do it on a router with DD-WRT firmware, see this tutorial and for a router with OpenWrt firmware, see this tutorial.

In any case, run the following command from the source computer to trigger wake-up:

Miscellaneous

Check reception of the magic packets

In order to make sure the WoL packets reach the target computer, one can listen to the UDP port, usually port 9, for magic packets. The magic packet frame expected contains 6 bytes of FF followed by 16 repetitions of the target computer’s MAC (6 bytes each) for a total of 102 bytes.

Using netcat

This can be performed by installing gnu-netcat on the target computer and using the following command:

Then wait for the incoming traffic to appear in the nc terminal.

Using ngrep

Install ngrep on the target computer and type the following command:

Example of WoL script

Here is a script that illustrates the use of wol with different machines:

Troubleshooting

NetworkManager

Network adapter is still powered off on shutdown

Setting auto negotiation to yes may help if WOL is configured through nmcli and network adapter is still powered off on shutdown.

Wake-up after shutdown

It is known that some motherboards are affected by a bug that can cause immediate or random wake-up after a shutdown whenever the BIOS WoL feature is enabled (as discussed in this thread for example).

Fix using BIOS Settings

The following actions in the BIOS preferences can solve this issue with some motherboards:

  1. Disable all references to xHCI in the USB settings (note this will also disable USB 3.0 at boot time)
  2. Disable EuP 2013 if it is explicitly an option
  3. Optionally enable wake-up on keyboard actions

Fix by Kernel quirks

The issue can also be solved by adding the following kernel boot parameter: xhci_hcd.quirks=270336 This activates the following quirks:

Battery draining problem

Some laptops have a battery draining problem after shutdown [1]. This might be caused by enabled WOL. To solve this problem, disable it by using ethtool as mentioned above.

Realtek

Users with Realtek 8168 8169 8101 8111(C) based NICs (cards / and on-board) may notice a problem where the NIC seems to be disabled on boot and has no Link light. See Network configuration/Ethernet#Realtek no link / WOL problem.

If the link light on the network switch is enabled when the computer is turned off but wake on LAN is still not working, booting the system using the r8168 kernel module at least once and then switching back to the r8169 kernel module included with the kernel seems to fix it at least in the following configurations:

  • MSI B85M-E45 motherboard, BIOS version V10.9, onboard Realtek 8111G chipset

For the r8168 module you might need to set the s5wol=1 module option to enable the wake on LAN functionality.

alx driver support

For some newer Atheros-based NICs (such as Atheros AR8161 and Killer E2500), WOL support has been disabled in the mainline alx module due to a bug causing unintentional wake-up (see this patch discussion). A patch can be applied (or installed as a dkms module) which both restores WOL support and fixes the underlying bug, as outlined in this thread.

Источник

Читайте также:  Acer aspire one 8gb windows
Оцените статью