improve logging messages

This commit is contained in:
Mathieu Broillet 2023-07-17 20:49:08 +02:00
parent 1562bdd58b
commit c5e35d0ea6
Signed by: mathieu
GPG Key ID: A08E484FE95074C1
4 changed files with 55 additions and 26 deletions

View File

@ -1,33 +1,41 @@
# 🖧 Easy Computer Manage
[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration)
[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration)
![img.png](.images/example1.png)
## 🐧 Configure Linux-running computer to be managed by Home Assistant.
We need to allow your user to run specific sudo command without asking for password. To do this, we need to edit sudoers file. To do this, run the following command ``visudo`` in a terminal and append the following the to end of the file :
We need to allow your user to run specific sudo command without asking for password. To do this, we need to edit sudoers
file. To do this, run the following command ``visudo`` in a terminal and append the following the to end of the file :
```
# Allow your user user to execute shutdown, init, systemctl, pm-suspend, awk, grub-reboot, and grub2-reboot without a password
username ALL=(ALL) NOPASSWD: /sbin/shutdown, /sbin/init, /usr/bin/systemctl, /usr/sbin/pm-suspend, /usr/bin/awk, /usr/sbin/grub-reboot, /usr/sbin/grub2-reboot
```
*Note : It might be necessary to allow port 22 (ssh) in your firewall.*
**⚠️ Be sure to replace username with your username.**
## 🪟 Configure Windows-running computer to be managed by Home Assistant.
First go to "Optional Features" in Windows 10, look for "OpenSSH Server" and install it.
Then open "Services", find "OpenSSH Server", open "Properties" and set the service to start "Automatically", you can also manually start the service for the first time.
First go to "Optional Features" in Windows 10/11, look for "OpenSSH Server" and install it.
Then open "Services", find "OpenSSH Server", open "Properties" and set the service to start "Automatically", you can
also manually start the service for the first time.
*Note : It might be necessary to allow port 22 (ssh) in the Windows firewall.*
## 🖧 Configure dual-boot (Windows/Linux) computer to be managed by Home Assistant.
To configure dual-boot computer, you need to configure both Windows and Linux, for this look at the 2 sections above.
You will need to have the same username and password on both Windows and Linux.
*Note : Be sure to enable the checkbox "Dual boot system" when adding your PC to home assistant.*
## 🔑 Why not use SSH keys?
Well, simply because it would require the user to do some extra steps. Using the password, it's almost plug and play.
But maybe in the future I will add the option to use SSH keys depending on the feedback.
## 🔑 Why not use SSH keys?
Well, simply because it would require the user to do some extra steps. Using the password, it's almost plug and play but
compromise the security a bit.
_In the future, the option to use SSH keys might be added depending on user feedback._

View File

@ -168,7 +168,7 @@ class ComputerSwitch(SwitchEntity):
if self._broadcast_port is not None:
service_kwargs["port"] = self._broadcast_port
_LOGGER.info(
_LOGGER.debug(
"Send magic packet to mac %s (broadcast: %s, port: %s)",
self._mac_address,
self._broadcast_address,
@ -195,7 +195,10 @@ class ComputerSwitch(SwitchEntity):
if self._dualboot:
utils.restart_to_windows_from_linux(self._connection)
else:
_LOGGER.error("This computer is not running a dualboot system.")
_LOGGER.error(
"The computer with the IP address %s is not running a dualboot system or hasn't been configured "
"correctly in the UI.",
self._host)
def restart_to_linux_from_windows(self) -> None:
"""Restart the computer to Linux from a running Windows by setting grub-reboot and restarting."""
@ -204,7 +207,10 @@ class ComputerSwitch(SwitchEntity):
# TODO: check for default grub entry and adapt accordingly
utils.restart_system(self._connection)
else:
_LOGGER.error("This computer is not running a dualboot system.")
_LOGGER.error(
"The computer with the IP address %s is not running a dualboot system or hasn't been configured "
"correctly in the UI.",
self._host)
def put_computer_to_sleep(self) -> None:
"""Put the computer to sleep using appropriate sleep command based on running OS and/or distro."""
@ -219,7 +225,10 @@ class ComputerSwitch(SwitchEntity):
self._hass.loop.create_task(self.service_restart_to_windows_from_linux())
else:
_LOGGER.error("This computer is not running a dualboot system.")
_LOGGER.error(
"The computer with the IP address %s is not running a dualboot system or hasn't been configured "
"correctly in the UI.",
self._host)
async def service_restart_to_windows_from_linux(self) -> None:
"""Method to be run in a separate thread to wait for the computer to boot and then reboot to Windows."""
@ -256,7 +265,7 @@ class ComputerSwitch(SwitchEntity):
# Update the state attributes and the connection only if the computer is on
if self._state:
if not utils.test_connection(self._connection):
_LOGGER.info("RENEWING SSH CONNECTION")
_LOGGER.info("Renewing SSH connection to %s using username %s", self._host, self._username)
if self._connection is not None:
self._connection.close()
@ -266,11 +275,12 @@ class ComputerSwitch(SwitchEntity):
try:
self._connection.open()
except AuthenticationException as error:
_LOGGER.error("Could not authenticate to %s: %s", self._host, error)
_LOGGER.error("Could not authenticate to %s using username %s : %s", self._host, self._username,
error)
self._state = False
return
except Exception as error:
_LOGGER.error("Could not connect to %s: %s", self._host, error)
_LOGGER.error("Could not connect to %s using username %s : %s", self._host, self._username, error)
self._state = False
return

View File

@ -2,8 +2,10 @@ import logging
import fabric2
from fabric2 import Connection
_LOGGER = logging.getLogger(__name__)
# _LOGGER.setLevel(logging.DEBUG)
@ -21,7 +23,7 @@ def create_ssh_connection(host: str, username: str, password: str, port=22):
config=conf
)
_LOGGER.info("CONNECTED SSH")
_LOGGER.info("Successfully created SSH connection to %s using username %s", host, username)
return connection
@ -80,7 +82,7 @@ def shutdown_system(connection: Connection, is_unix=None):
# Try a third method using systemctl command
result = connection.run("sudo systemctl poweroff")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot shutdown system running at %s, all methods failed.", connection.host)
else:
# First method using shutdown command
@ -89,7 +91,7 @@ def shutdown_system(connection: Connection, is_unix=None):
# Try a second method using init command
result = connection.run("wmic os where Primary=TRUE call Shutdown")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot shutdown system running at %s, all methods failed.", connection.host)
connection.close()
@ -110,7 +112,7 @@ def restart_system(connection: Connection, is_unix=None):
# Try a third method using systemctl command
result = connection.run("sudo systemctl reboot")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot restart system running at %s, all methods failed.", connection.host)
else:
# First method using shutdown command
result = connection.run("shutdown /r /t 0")
@ -118,7 +120,7 @@ def restart_system(connection: Connection, is_unix=None):
# Try a second method using wmic command
result = connection.run("wmic os where Primary=TRUE call Reboot")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot restart system running at %s, all methods failed.", connection.host)
def sleep_system(connection: Connection, is_unix=None):
@ -134,7 +136,7 @@ def sleep_system(connection: Connection, is_unix=None):
# Try a second method using pm-suspend command
result = connection.run("sudo pm-suspend")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot put system running at %s to sleep, all methods failed.", connection.host)
else:
# First method using shutdown command
result = connection.run("shutdown /h /t 0")
@ -142,7 +144,7 @@ def sleep_system(connection: Connection, is_unix=None):
# Try a second method using rundll32 command
result = connection.run("rundll32.exe powrprof.dll,SetSuspendState Sleep")
if result.return_code != 0:
_LOGGER.error("Cannot restart system, all methods failed.")
_LOGGER.error("Cannot put system running at %s to sleep, all methods failed.", connection.host)
def get_windows_entry_in_grub(connection: Connection):
@ -157,16 +159,17 @@ def get_windows_entry_in_grub(connection: Connection):
else:
result = connection.run("sudo awk -F \"'\" '/windows/ {print $2}' /boot/grub2/grub.cfg")
if result.return_code == 0:
_LOGGER.debug("Found windows entry in grub2 : " + result.stdout.strip())
_LOGGER.debug("Successfully found Windows Grub entry (%s) for system running at %s.", result.stdout.strip(),
connection.host)
else:
_LOGGER.error("Cannot find windows entry in grub")
_LOGGER.error("Could not find Windows entry on computer with address %s.")
return None
# Check if the entry is valid
if result.stdout.strip() != "":
return result.stdout.strip()
else:
_LOGGER.error("Cannot find windows entry in grub")
_LOGGER.error("Could not find Windows entry on computer with address %s.")
return None
@ -188,6 +191,9 @@ def restart_to_windows_from_linux(connection: Connection):
_LOGGER.info("Rebooting to Windows")
restart_system(connection)
else:
_LOGGER.error("Cannot restart system to windows from linux, all methods failed.")
_LOGGER.error("Could not restart system running on %s to Windows from Linux, all methods failed.",
connection.host)
else:
_LOGGER.error("Cannot restart to Windows from Linux, system is not Linux/Unix")
_LOGGER.error(
"Could not restart system running on %s to Windows from Linux, system does not appear to be a Linux-based OS.",
connection.host)

5
requirements.txt Normal file
View File

@ -0,0 +1,5 @@
fabric2~=3.1.0
paramiko~=3.2.0
voluptuous~=0.13.1
wakeonlan~=3.0.0
homeassistant~=2023.7.2