Power windows with remote

Remote Power Button for Your PC

Wake on WAN

I love having all my computers off when I don’t need them. This saves plenty of power, makes me reboot regularly (good for Windows), and probably even prolongs my hardware lifetime. But you never know when you may need to connect to your home or office PC via RDP or TeamViewer to complete some urgent and critical task. If that PC is off, you can’t log into it, right? In fact, you can turn it on remotely from the Internet. If you haven’t heard about WoL or tried to make it work without luck, read on, let’s make it work together!

Meet Wake on LAN

Wake on LAN (WoL) is a protocol that allows you to turn a PC on by broadcasting a specially formed packet into your local network.

If your router’s configuration is flexible enough, you can even catch that packet from the Internet and broadcast it as required.

The protocol is radically simple. All you need to do is to send a so-called Magic Packet to your network’s broadcast IP (e.g., 192.168.1.255 or even 255.255.255.255) and port 9. The magic packet is a UDP datagram that should begin with six 0xFF bytes, then contain the MAC-address of your target PC repeated 16 times. That’s all. 144 bytes with magic power. If your LAN-card receives a magic packet with its MAC while waiting for it, the LAN-card tries to turn the computer on via ACPI. And yes, it waits for the magic packet when the entire system is completely turned off (just don’t remove the plug from the socket).

The WoL protocol is simple in theory, but in practice, it turns up to be a challenging thing to set up. Here are some possible issues when we are trying to deal with magic packets from the Internet (the most convenient case):

  1. You can be behind your provider’s NAT and unable to accept incoming connections.
  2. Your provider can block incoming connections on port 9 (or even all ports, for safety).
  3. Your router can be not capable of forwarding a port to a broadcast address.
  4. Your LAN-card can be off. It happens when something is not configured, or in case of a failure.
  5. Your ACPI can be configured to ignore the PCI wake requests.

The issues in first three items are not solved smoothly: you need to change either your provider or your router or both. So, there’s no way to turn on your PC from the Internet if your provider and/or router are junk, right? In fact, you can use an always-on single-board PC like Raspberry Pi which listens for a command sent from the Internet and broadcasts a magic packet. That’s what we are going to set up in this article! But first, I’ll try to summarize everything you should do with your Windows PC to make it accept WoL packets.

Configure Wake on LAN

There are several things you should do on Windows 10 to make your PC turn on when its LAN-card receives the magic packet:

1. Configure LAN-card

  • Right-click the Start button and open Network Connections.
  • Proceed to Change Adapter Options.
  • Right-click your primary Ethernet adapter and choose Properties.
  • Click Configure to open the device properties.
  • Proceed to the Advanced tab.

  • Set Wake Up Capabilities to Magic Packet or Magic Packet & Pattern Match.
  • Set Shutdown Wake Up to Enabled.

Uncheck everything on Power Management tab (you can try to check everything, but this configuration may not work for some reason):

The MAC-address of this adapter will also be required in the future, you can find it by double-clicking your primary Ethernet adapter and choosing Details. The Physical Address is what you need there, save this string on your smartphone (or paper, if you still use it).

2. Enable Shutdown

By default, when you shut down your PC, Windows 8+ performs a sort of hibernation. The disadvantages of this are more significant than a modest startup acceleration: your system drive remains in an unsafe state (you may notice this on Linux), and this mode somehow affects Wake on LAN. Let’s bring the real shutdown back.

  • Right-click the Start button and open Power Options.
  • Open the old interface using the Additional Power Options on the right side.
  • Click the Choose what the power buttons do link on the left side.
  • Unlock the checkboxes using the Change settings that are currently unavailable link.
  • Uncheck the Turn on fast startup option.
Читайте также:  Запуск утилиты восстановления windows

3. Configure ACPI

Unfortunately, I can’t give the precise instructions here. The SETUP interface is very different on different motherboards. You need to enter SETUP (also called BIOS) in the first few seconds after turning the PC on. Hold a button to do this: it can be Del, Esc, or one of the F-keys. Refer to your motherboard’s manual for detailed instructions.

In SETUP, enable everything related to Wake on LAN and also allow PCI devices to power the PC on.

These three steps should solve the issues 4 and 5 in the list of possible WoL problems. Try to wake your PC using your smartphone. I recommend this Android app, but you can use any WoL app, they are very simple. The Android app I use can detect the target MAC address automatically, try to search for your PC while the Windows is running.

If you were able to wake your PC using your smartphone connected to your Wi-Fi, it’s time to configure Wake on LAN over the Internet.

Wake on Cloud

The remaining part of the article is for those who can’t receive a packet from the Internet or can’t broadcast it after receiving. The additional hardware is a little bit overkill, but it’s good to have an always-on Linux in your network. You can use it for many different tasks apart from turning on your PC. The plan is simple:

  • Getting a single-board PC (Omega2, C.H.I.P., Raspberry Pi, etc.) or taking the one you already have.
  • Configuring a Cloud4RPi service, which allows you to send a Power On command from anywhere.

Single-board PC

I use Next Thing Co, C.H.I.P., because I have one. You can use any Linux-based device (from an OpenWRT-enabled router to a powerful server). There’s no C.H.I.P. specifics involved in this task, the instructions below should work anywhere.

  • Follow the Getting Started sections in the Cloud4RPi documentation to get the sample code working. If you face any problems, feel free to contact the developers, this team is very responsive.
  • Install the wakeonlan Python package using the pip install wakeonlan command
  • Implement the function that broadcasts a magic packet and the one that pings your PC (to ensure that the WoL request worked). I did it in a separate file wol.py.
  • Change the variables section in the control.py sample file and add two new variables.

The full code is presented in my cloud4rpi-wol repository, feel free to clone it and use my code.

Note that I use a NetBIOS name instead of an IP address to ping my PC. This will work if you install the libnss-winbind package and add the wins option to the hosts line in the /etc/nsswitch.conf file:

sudo apt install libnss-winbind
sed «s/^hosts:.*/& wins/» /etc/nsswitch.conf | sudo tee /etc/nsswitch.conf

Cloud4RPi

Create a Control Panel and bind a Switch widget to the PC WoL variable.

Unfortunately, Cloud4RPi has no Big Red Button widget, although the Switch widget does the great job in sending True into the wake_pc function. The function always makes it switch off right after switching on, but it doesn’t matter.

You can now turn on your PC from anywhere. Isn’t that great?

Service

If you have cloned a Cloud4RPi example, you should have a service_install.sh script. Use it to install your main script as a system service.

Now it starts with the system and sends logs to journald. You can control the service as follows:

Conclusion

Don’t waste electric power! Now, you don’t have to.

Управление виртуальными машинами Windows с помощью PowerShell Direct Manage Windows virtual machines with PowerShell Direct

Область применения: Windows 10, Windows Server 2016, Windows Server 2019 Applies To: Windows 10, Windows Server 2016, Windows Server 2019

PowerShell Direct можно использовать для удаленного управления виртуальной машиной Windows 10, Windows Server 2016 или Windows Server 2019 с узла Windows 10, Windows Server 2016 или Windows Server 2019 Hyper-V. You can use PowerShell Direct to remotely manage a Windows 10, Windows Server 2016, or Windows Server 2019 virtual machine from a Windows 10, Windows Server 2016, or Windows Server 2019 Hyper-V host. PowerShell Direct позволяет управлять Windows PowerShell внутри виртуальной машины независимо от конфигурации сети или параметров удаленного управления на узле Hyper-V или виртуальной машине. PowerShell Direct allows Windows PowerShell management inside a virtual machine regardless of the network configuration or remote management settings on either the Hyper-V host or the virtual machine. Это позволяет администраторам Hyper-V автоматизировать управление и настройку виртуальных машин с помощью сценариев. This makes it easier for Hyper-V Administrators to automate and script virtual machine management and configuration.

Запустить PowerShell Direct можно двумя способами: There are two ways to run PowerShell Direct:

Создание и выход из прямого сеанса PowerShell с помощью командлетов PSSession Create and exit a PowerShell Direct session using PSSession cmdlets

Запуск скрипта или команды с помощью командлета Invoke-Command Run script or command with the Invoke-Command cmdlet

Если вы управляете виртуальными машинами более ранних версий, используйте средство «Подключение к виртуальной машине» (VMConnect) или настройте для этой машины виртуальную сеть. If you’re managing older virtual machines, use Virtual Machine Connection (VMConnect) or configure a virtual network for the virtual machine.

Создание и выход из прямого сеанса PowerShell с помощью командлетов PSSession Create and exit a PowerShell Direct session using PSSession cmdlets

На узле Hyper-V откройте Windows PowerShell от имени администратора. On the Hyper-V host, open Windows PowerShell as Administrator.

Читайте также:  Региональные настройки windows 10 точка запятая

Используйте командлет Enter-PSSession для подключения к виртуальной машине. Use the Enter-PSSession cmdlet to connect to the virtual machine. Чтобы создать сеанс с помощью имени или GUID виртуальной машины, выполните одну из следующих команд: Run one of the following commands to create a session by using the virtual machine name or GUID:

Введите свои учетные данные для виртуальной машины. Type your credentials for the virtual machine.

Выполните все необходимые команды. Run whatever commands you need to. Эти команды выполняются на виртуальной машине, в которой был создан сеанс. These commands run on the virtual machine that you created the session with.

Когда все будет готово, завершите сеанс с помощью команды Exit-PSSession . When you’re done, use the Exit-PSSession to close the session.

Запуск скрипта или команды с помощью командлета Invoke-Command Run script or command with Invoke-Command cmdlet

Выполнить предварительно определенный набор команд на виртуальной машине можно с помощью командлета Invoke-Command. You can use the Invoke-Command cmdlet to run a pre-determined set of commands on the virtual machine. Ниже приведен пример использования командлета Invoke-Command, где PSTest — это имя виртуальной машины, а сценарий, который требуется запустить,(foo.ps1) находится в папке сценария (script) на диске C: Here is an example of how you can use the Invoke-Command cmdlet where PSTest is the virtual machine name and the script to run (foo.ps1) is in the script folder on the C:/ drive:

Чтобы выполнить одну команду, используйте параметр -ScriptBlock: To run a single command, use the -ScriptBlock parameter:

Что необходимо для использования PowerShell Direct? What’s required to use PowerShell Direct?

Чтобы создать сеанс PowerShell Direct на виртуальной машине: To create a PowerShell Direct session on a virtual machine,

Виртуальная машина должна работать на узле локально и быть загружена. The virtual machine must be running locally on the host and booted.

Необходимо войти в учетную запись администратора Hyper-V на хост-компьютере. You must be logged into the host computer as a Hyper-V administrator.

Необходимо указать действительные учетные данные пользователя для виртуальной машины. You must supply valid user credentials for the virtual machine.

Операционная система узла должна работать под управлением Windows 10 или Windows Server 2016 или более поздней версии. The host operating system must run at least Windows 10 or Windows Server 2016.

Виртуальная машина должна работать под управлением Windows 10 или Windows Server 2016 или более поздней. The virtual machine must run at least Windows 10 or Windows Server 2016.

С помощью командлета Get-VM можно проверить, что используемые учетные данные имеют роль администратора Hyper-V, и получить список виртуальных машин, запущенных локально на узле и загруженных. You can use the Get-VM cmdlet to check that the credentials you’re using have the Hyper-V administrator role and to get a list of the virtual machines running locally on the host and booted.

Enable-PSRemoting

Configures the computer to receive remote commands.

Syntax

Description

The Enable-PSRemoting cmdlet configures the computer to receive PowerShell remote commands that are sent by using the WS-Management technology. WS-Management based PowerShell remoting is currently supported only on Windows platform.

PowerShell remoting is enabled by default on Windows Server platforms. You can use Enable-PSRemoting to enable PowerShell remoting on other supported versions of Windows and to re-enable remoting if it becomes disabled.

You have to run this command only one time on each computer that will receive commands. You do not have to run it on computers that only send commands. Because the configuration starts listeners to accept remote connections, it is prudent to run it only where it is needed.

Enabling PowerShell remoting on client versions of Windows when the computer is on a public network is normally disallowed, but you can skip this restriction by using the SkipNetworkProfileCheck parameter. For more information, see the description of the SkipNetworkProfileCheck parameter.

Multiple PowerShell installations can exist side-by-side on a single computer. Running Enable-PSRemoting will configure a remoting endpoint for the specific installation version that you are running the cmdlet in. So if you run Enable-PSRemoting while running PowerShell 6.2, a remoting endpoint will be configured that runs PowerShell 6.2. If you run Enable-PSRemoting while running PowerShell 7-preview, a remoting endpoint will be configured that runs PowerShell 7-preview.

Enable-PSRemoting creates two remoting endpoint configurations as needed. If the endpoint configurations already exist, then they are simply ensured to be enabled. The created configurations are identical but have different names. One will have a simple name corresponding to the PowerShell version that hosts the session. The other configuration name contains more detailed information about the PowerShell version which hosts the session. For example, when running Enable-PSRemoting in PowerShell 6.2, you will get two configured endpoints named PowerShell.6, PowerShell.6.2.2. This allows you to create a connection to the latest PowerShell 6 host version by using the simple name PowerShell.6. Or you can connect to a specific PowerShell host version by using the longer name PowerShell.6.2.2.

To use the newly enabled remoting endpoints, you must specify them by name with the ConfigurationName parameter when creating a remote connection using the Invoke-Command , New-PSSession , Enter-PSSession cmdlets. For more information, see Example 4.

The Enable-PSRemoting cmdlet performs the following operations:

  • Runs the Set-WSManQuickConfig cmdlet, which performs the following tasks:
    • Starts the WinRM service.
    • Sets the startup type on the WinRM service to Automatic.
    • Creates a listener to accept requests on any IP address.
    • Enables a firewall exception for WS-Management communications.
    • Creates the simple and long name session endpoint configurations if needed.
    • Enables all session configurations.
    • Changes the security descriptor of all session configurations to allow remote access.
  • Restarts the WinRM service to make the preceding changes effective.
Читайте также:  Windows phone как почистить кэш

To run this cmdlet on the Windows platform, start PowerShell by using the Run as administrator option. This cmdlet is not available on Linux or MacOS versions of PowerShell.

This cmdlet does not affect remote endpoint configurations created by Windows PowerShell. It only affects endpoints created with PowerShell version 6 and greater. To enable and disable PowerShell remoting endpoints that are hosted by Windows PowerShell, run the Enable-PSRemoting cmdlet from within a Windows PowerShell session.

Examples

Example 1: Configure a computer to receive remote commands

This command configures the computer to receive remote commands.

Example 2: Configure a computer to receive remote commands without a confirmation prompt

This command configures the computer to receive remote commands. The Force parameter suppresses the user prompts.

Example 3: Allow remote access on clients

This example shows how to allow remote access from public networks on client versions of the Windows operating system. The name of the firewall rule can be different for different versions of Windows. Use Get-NetFirewallRule to see a list of rules. Before enabling the firewall rule, view the security settings in the rule to verify that the configuration is appropriate for your environment.

By default, Enable-PSRemoting creates network rules that allow remote access from private and domain networks. The command uses the SkipNetworkProfileCheck parameter to allow remote access from public networks in the same local subnet. The command specifies the Force parameter to suppress confirmation messages.

The SkipNetworkProfileCheck parameter does not affect server versions of the Windows operating system, which allow remote access from public networks in the same local subnet by default.

The Set-NetFirewallRule cmdlet in the NetSecurity module adds a firewall rule that allows remote access from public networks from any remote location. This includes locations in different subnets.

Example 4: Create a remote session to the newly enabled endpoint configuration

This example shows how to enable PowerShell remoting on a computer, find the configured endpoint names, and create a remote session to one of the endpoints.

The first command enables PowerShell remoting on the computer.

The second command lists the endpoint configurations.

The third command creates a remote PowerShell session to the same machine, specifying the PowerShell.6 endpoint by name. The remote session will be hosted with the latest PowerShell 6 version (6.2.2).

The last command accesses the $PSVersionTable variable in the remote session to display the PowerShell version that is hosting the session.

The name of the firewall rule can be different depending on the version of Windows. Use the Get-NetFirewallRule cmdlet to list the names of the rules on your system.

Parameters

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Forces the command to run without asking for user confirmation.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Indicates that this cmdlet enables remoting on client versions of the Windows operating system when the computer is on a public network. This parameter enables a firewall rule for public networks that allows remote access only from computers in the same local subnet.

This parameter does not affect server versions of the Windows operating system, which, by default, have a local subnet firewall rule for public networks. If the local subnet firewall rule is disabled on a server version, Enable-PSRemoting re-enables it, regardless of the value of this parameter.

To remove the local subnet restriction and enable remote access from all locations on public networks, use the Set-NetFirewallRule cmdlet in the NetSecurity module.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Inputs

None

You cannot pipe input to this cmdlet.

Outputs

This cmdlet returns strings that describe its results.

Notes

This cmdlet is only available on Windows platforms.

On server versions of the Windows operating system, Enable-PSRemoting creates firewall rules for private and domain networks that allow remote access, and creates a firewall rule for public networks that allows remote access only from computers in the same local subnet.

On client versions of the Windows operating system, Enable-PSRemoting creates firewall rules for private and domain networks that allow unrestricted remote access. To create a firewall rule for public networks that allows remote access from the same local subnet, use the SkipNetworkProfileCheck parameter.

On client or server versions of the Windows operating system, to create a firewall rule for public networks that removes the local subnet restriction and allows remote access , use the Set-NetFirewallRule cmdlet in the NetSecurity module to run the following command: Set-NetFirewallRule -Name «WINRM-HTTP-In-TCP-PUBLIC» -RemoteAddress Any

Enable-PSRemoting enables all session configurations by setting the value of the Enabled property of all session configurations to $True .

Enable-PSRemoting removes the Deny_All and Network_Deny_All settings. This provides remote access to session configurations that were reserved for local use.

Оцените статью