Can I create a binary sensor that scans a port rather than pinging?

Try this one:

binary_sensor:
  - platform: command_line
    name: <sensorName>
    command: "nmap -PS<portToTest> --host-timeout 2s <hostToTest> 2>&1 | grep 'Host is up' > /dev/null && (echo 1) || (echo 0)"
    payload_on: '1'
    payload_off: '0'
    device_class: 'connectivity'
    scan_interval: <inSeconds>

Please note that -PS<portToTest> has no space between parameter and port e.g. -PS80

You can also check this post: Command line binary sensor never switches to on

I did not find a proper documentation on this, just looked at the code: core/binary_sensor.py at ccfe32257e1def92f8c5fbc096af2c1e2bbd9d46 · home-assistant/core · GitHub

What is also extremely convenient about command_line integration is that it is possible to reload only command_line (except for scan_interval for binary_sensor) configuration without restarting whole HA.

3 Likes