How to get the IP address from a failed login notification

I am subscribing to persistent_notification.httplogin to notify me when there is a failed web login on my HA portal. The alert works well, but I figure out how to send the IP address along with the notification. Here is the code I borrowed from someone else’s forum post:

--- # automations.yaml

- alias: "Send notification upon failed login attempt"
  trigger:
    - platform: state
      entity_id: persistent_notification.httplogin
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state != off }}"
  action:
    - service: notify.pushover
      data_template:
        title: "Failed Home Assistant login attempt!"
        message: "{{ trigger.to_state.state }}"
        data:
          url: http://www.ip-tracker.org/locator/ip-lookup.php?ip={{ states.persistent_notification.httplogin.state.split ("from ") [1]}}

That alert works fine, but it is not getting the httplogin.state information and sending it with my alert.

1 Like

edit: see below

Ok fiddled with the template tool a bit more… try

http://www.ip-tracker.org/locator/ip-lookup.php?ip={{ states.persistent_notification.httplogin.attributes.message.split ("from ") [1]}}

2 Likes

That did it. First off, thanks for the awesome response! 2nd, how did you figure that out? I was trying to look through an api browser or something on httplogin and I couldn’t find antyhing.

There is a templating tool built into hass where you can try templates live. So I created a bad login (open incognito browser instance, bad password, click log in)

Then you have the persistent notification. Browse thought the states tab (Three bars in the upper right opens the side bar, if not already open). States tab has an icon that looks like < > .

From there you should be able to find the persistent notification. It has two attributes (far right column), one of which is message. The message contains the IP that was used from login.

From there it is a bit of templating knowledge and a few tests. The template tool is two icons over from the states tab. (looks like a page with the corner folded down) You can use some of what is in there. Experiment away, it just runs the template, no actions are taken.

Helps a bit, I find it better to browse the forum and github repos to see how people are using them. I learn better by example than reading the docs.

1 Like

That is really useful. Thanks so much for the help fixing and the directions on how I can figure things out in the future.

1 Like

you might want to contact @Bob_NL as he wrote the automation you’re using :wink:
or check Intruder alert! for further tweaks and adjustments.

Cheers,
Marius

1 Like

No problem, I found this forum extremely helpful when I was getting started, I try to repay the debt when I can.

1 Like

@silvrr i am trying to use your example but i have the error
https://hastebin.com/unugaxufaw.pl

how can solve it?

What notify platform are you using?

Not sure all of them accept the URL as part of the template. I had to move mine into the message.

Finally, put single quotes around the URL like I have done on my URL so its read as a single item and the symbols in it don’t throw HA off.

I am using push notifications html5, tomorrow i will try with quotes as you have.

@silvrr
i found the solution thanks:

 - alias: "Tentativa de Ataque Home Assistant"
    trigger:
      - platform: state
        entity_id: persistent_notification.httplogin
    condition:
      - condition: template
        value_template: "{{ trigger.to_state.state != 'None' }}"
    action:
      - service: notify.pushnotification_meu_telemovel
        data_template:
          title: "Tentativa de Ataque Home Assistant"
          message: "{{ states.persistent_notification.httplogin.attributes.message }}"
          data:
            url: https://whatismyipaddress.com/ip/{{ states.persistent_notification.httplogin.attributes.message.split("from ") [1]}}

Sorry to dig up this topic but after months of using this automations both stoped working:

- id: Send notification upon failed login attempt
  alias: Send notification upon failed login attempt
  initial_state: 'on'
  trigger:
    - platform: state
      entity_id: persistent_notification.httplogin
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state != off }}"
  action:
    - service: notify.ios_iphoneJPM
      data_template:
        title: "Failed Home Assistant login attempt!"
        message: >-
            {% set message = trigger.event.data.service_data.message %}
            {% if 'invalid authentication' in message|lower or 'login attempt' in message|lower %}
              {{ message }}: http://www.ip-tracker.org/locator/ip-lookup.php?ip={{ message.split('from ')[1] }}
            {% else %}
              {{ message }}
            {% endif %}

2018-09-13 22:23:28 WARNING (MainThread) [homeassistant.components.http.ban] Login attempt or request with invalid authentication from 192.168.1.106

- id: New Device Connected
  alias: New Device Connected
  initial_state: 'on'
  trigger:
    - platform: event
      event_type: device_tracker_new_device
  action:
   - service: notify.my_iphone
     data_template:
      title: "ALERT: Novo Dispositivo!"
      message: 'ALERT: Novo Dispositivo nome {{ trigger.event.data.name }} MAC: {{ trigger.event.data.mac }}'

2018-09-13 22:24:12 ERROR (MainThread) [homeassistant.helpers.service] Error rendering data template: UndefinedError: ‘trigger’ is undefined

2018-09-13 22:25:32 ERROR (MainThread) [homeassistant.helpers.service] Error rendering data template: UndefinedError: ‘trigger’ is undefined

@jpm - Did you get this resolved and working? This feature, notification upon IP ban, is something I’d like to get notifications of.

This works for me:

- alias: "HomeAssistant Attack attempt"
  initial_state: 'on'
  trigger:
   - platform: state
     entity_id: persistent_notification.httplogin
  condition:
   - condition: template
     value_template: "{{ trigger.to_state.state != 'None' }}"
  action:
    - service: notify.my_phone4
      data_template:
        title: "Failed login"
        message: "{{ states.persistent_notification.httplogin.attributes.message }}"
        data:
          url: https://whatismyipaddress.com/ip/{{ states.persistent_notification.httplogin.attributes.message.split("from ") [1]}}

anyone using this be sure to validate that it still works after the 0.86 update. I noticed that persistent_notification.httplogin has become persistent_notification.http_login on my configuration which breaks the automation many are using.

1 Like

wow, thnx a lot, thx for pointing me out, also had a notification automation, if i didnt read your comment, i wasnt aware that it was a broke

changed an _ to it, now its working

- id: notifylogin
  alias: "Send notification upon failed login attempt"
  trigger:
    - platform: state
      entity_id: persistent_notification.http_login
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state != 'None' }}"
  action:
    - service: notify.notifygmail
      data_template:
        title: "{{ states.persistent_notification.http_login.attributes.message }}"
        message: 'url: https://whatismyipaddress.com/ip/{{ states.persistent_notification.http_login.attributes.message.split ("from ") [1]}}'
    - service: persistent_notification.dismiss
      data:
        notification_id: 'http_login'  
    - service: notify.html5
      data_template: 
        message: "Home Assistant Bad Login"
1 Like

guys, i am also using this, but when i clear my notification, i always get the error below inmy log

any idea?

automation:

- id: notifylogin
  initial_state: 'on'
  alias: "Send notification upon failed login attempt"
  trigger:
    - platform: state
      entity_id: persistent_notification.http_login
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state != 'None' }}"
  action:
    - service: notify.notifygmail
      data_template:
        #title: "{{ states.persistent_notification.http_login.attributes.message }}"
        title: "{{ state_attr('persistent_notification.http_login', 'message') }}"
        message: 'url: https://whatismyipaddress.com/ip/{{ states.persistent_notification.http_login.attributes.message.split ("from ") [1]}}'
2020-09-13 20:54:47 ERROR (MainThread) [homeassistant.components.automation.send_notification_upon_failed_login_attempt] Send notification upon failed login attempt: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'None' has no attribute 'attributes'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 230, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.8/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'None' has no attribute 'attributes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 132, in async_prepare_call_from_config
    template.render_complex(config[CONF_SERVICE_DATA_TEMPLATE], variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 74, in render_complex
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 74, in <dictcomp>
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 76, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 232, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'None' has no attribute 'attributes'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 191, in _async_step
    await getattr(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 352, in _async_call_service_step
    domain, service, service_data = async_prepare_call_from_config(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 135, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'None' has no attribute 'attributes'
2020-09-13 20:54:47 ERROR (MainThread) [homeassistant.components.automation.send_notification_upon_failed_login_attempt] While executing automation automation.send_notification_upon_failed_login_attempt
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 230, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.8/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'None' has no attribute 'attributes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 132, in async_prepare_call_from_config
    template.render_complex(config[CONF_SERVICE_DATA_TEMPLATE], variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 74, in render_complex
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 74, in <dictcomp>
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 76, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 232, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'None' has no attribute 'attributes'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/automation/__init__.py", line 430, in async_trigger
    await self.action_script.async_run(variables, trigger_context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 802, in async_run
    await asyncio.shield(run.async_run())
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 183, in async_run
    await self._async_step(log_exceptions=False)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 191, in _async_step
    await getattr(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 352, in _async_call_service_step
    domain, service, service_data = async_prepare_call_from_config(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 135, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'None' has no attribute 'attributes'

if anything you’d change that to

{{trigger.to_state.state is not none}} 

cool, fixed :slight_smile:
fast response :slight_smile: