Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ssh key connection added #22

Merged
merged 2 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,19 @@ script:
user: pi
pass: raspberry
command: ls -la
```

if you want connect with ssh key, use this

```yaml
script:
run_on_host:
alias: Run shell command on host
sequence:
- service: ssh_command.exec_command
data:
host: 192.168.1.123
user: pi
ssh_private_key_path: /config/ssh/id_rsa
command: ls -la
```
18 changes: 15 additions & 3 deletions custom_components/ssh_command/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging

from homeassistant.core import ServiceCall
from paramiko import SSHClient, AutoAddPolicy
from paramiko import AutoAddPolicy, RSAKey, SSHClient

_LOGGER = logging.getLogger(__name__)

Expand All @@ -15,10 +15,22 @@ async def exec_command(call: ServiceCall):
username = call.data.get('user', 'pi')
password = call.data.get('pass', 'raspberry')
command = call.data.get('command')
ssh_private_key_path = call.data.get('ssh_private_key_path')

client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(host, port, username, password)

if ssh_private_key_path:
try:
key = RSAKey.from_private_key_file(ssh_private_key_path)
client.connect(host, port, username, pkey=key)
except Exception as e:
_LOGGER.error(f"Failed to connect using SSH key: {e}")
return
else:
# Use password for authentication if SSH key is not provided
client.connect(host, port, username, password)

stdin, stdout, stderr = client.exec_command(command)
data = stdout.read()
stderr.read()
Expand All @@ -32,4 +44,4 @@ async def exec_command(call: ServiceCall):


async def async_setup_entry(hass, entry):
return True
return True
5 changes: 5 additions & 0 deletions custom_components/ssh_command/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,8 @@ exec_command:
required: true
selector:
text:

ssh_private_key_path:
example: /config/ssh/id_rsa
selector:
text:
Loading