MCPcopy Create free account
hub / github.com/AlexxIT/SSHCommand / async_setup

Function async_setup

custom_components/ssh_command/__init__.py:28–84  ·  view source on GitHub ↗
(hass: HomeAssistant, config: dict)

Source from the content-addressed store, hash-verified

26
27
28async def async_setup(hass: HomeAssistant, config: dict) -> bool:
29 default = config.get(DOMAIN) or DEFAULT_SCHEMA({})
30
31 def exec_command(call: ServiceCall) -> dict:
32 kwargs = default | call.data
33 kwargs["hostname"] = kwargs.pop("host")
34 kwargs["username"] = kwargs.pop("user")
35 kwargs["password"] = kwargs.pop("pass", None)
36 kwargs["key_filename"] = kwargs.pop("private_key", None)
37
38 commands = kwargs.pop("command")
39 if isinstance(commands, str):
40 commands = [commands]
41
42 client = SSHClient()
43 client.set_missing_host_key_policy(AutoAddPolicy())
44
45 try:
46 client.connect(**kwargs)
47
48 for command in commands:
49 _, stdout, stderr = client.exec_command(
50 command, timeout=kwargs.get("timeout")
51 )
52
53 # noinspection PyUnboundLocalVariable
54 return {
55 "stdout": stdout.read().decode("utf-8"),
56 "stderr": stderr.read().decode("utf-8"),
57 }
58
59 except TimeoutError as e:
60 _LOGGER.error(f"Command execution timeout")
61 return {"error": repr(e)}
62
63 except Exception as e:
64 _LOGGER.error(f"Failed to connect: {repr(e)}")
65 return {"error": repr(e)}
66
67 finally:
68 client.close()
69
70 try:
71 # ServiceResponse from Hass 2023.7
72 # https://github.com/home-assistant/core/blob/2023.7.0/homeassistant/core.py
73 from homeassistant.core import SupportsResponse
74
75 hass.services.async_register(
76 DOMAIN,
77 "exec_command",
78 exec_command,
79 supports_response=SupportsResponse.OPTIONAL,
80 )
81 except ImportError:
82 hass.services.async_register(DOMAIN, "exec_command", exec_command)
83
84 return True
85

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected