#ban_ip service?

6 messages · Page 1 of 1 (latest)

tawdry token
#

I'd like to implement a service to dinamically ban an IP.
The easiest way I can think to achieve my goal is with a shell_command that would add an entry to /config/ip_bans.yaml:

shell_command:
  ban_ip: "echo '- ip_address: {{ ip_address }}' >> /config/ip_bans.yaml"

If I try to invoke the service:

action: shell_command.ban_ip
data:
  ip_address: "test"

it seems to work:

stdout: "- ip_address: test >> /config/ip_bans.yaml"
stderr: ""
returncode: 0

but no "test" entry is actually added to /config/ip_bans.yaml as the piping seems to be interpreted as plain text.
How may I implement this service? Are there alternative ways to achieve the desired result?

Thanks for your time.

#

When using templates, shell_command runs in a more secure environment which doesn’t allow [...] using pipe symbols to run multiple commands.
Source

😪 😪 😪

Home Assistant

Instructions on how to integrate Shell commands into Home Assistant.

tawdry token
#

I also tried the python_script route:

  • add python_script: to configuration.yaml
  • create the folder /python_scripts/
  • populate the script /python_scripts/ban_ip.py:
ip_address = data.get('ip_address')
with open('/config/ip_bans.yaml', 'a') as f:
    f.write(f'\n- ip_address: {ip_address}\n')
  • restart Home Assistant

But when I try to call it:

action: python_script.ban_ip
data:
  ip_address: test

it seems unable to call open function:

Failed to perform the action python_script.ban_ip. Error executing script (NameError): name 'open' is not defined
upbeat trench
#

Or use the built-in stuff, @tawdry token