mirror of
https://github.com/home-assistant/core.git
synced 2025-09-02 09:01:05 +00:00
.github
docs
homeassistant
auth
components
abode
ads
air_quality
alarm_control_panel
alarmdecoder
alert
alexa
ambient_station
amcrest
android_ip_webcam
androidtv
apcupsd
api
apple_tv
aqualogic
arduino
arlo
asterisk_mbox
asuswrt
august
auth
automation
axis
bbb_gpio
binary_sensor
blink
bloomsky
bmw_connected_drive
browser
calendar
camera
canary
cast
cisco_mobility_express
climate
cloud
cloudflare
coinbase
comfoconnect
config
configurator
conversation
counter
cover
cppm_tracker
daikin
danfoss_air
datadog
deconz
default_config
demo
device_sun_light_trigger
device_tracker
__init__.py
actiontec.py
aruba.py
asuswrt.py
automatic.py
bbox.py
bluetooth_le_tracker.py
bluetooth_tracker.py
bt_home_hub_5.py
bt_smarthub.py
cisco_ios.py
ddwrt.py
demo.py
ee_brightbox.py
fritz.py
google_maps.py
hitron_coda.py
huawei_router.py
icloud.py
keenetic_ndms2.py
linksys_ap.py
linksys_smart.py
luci.py
meraki.py
mikrotik.py
mqtt_json.py
netgear.py
nmap_tracker.py
ping.py
quantum_gateway.py
ritassist.py
services.yaml
sky_hub.py
snmp.py
swisscom.py
synology_srm.py
thomson.py
tile.py
tomato.py
tplink.py
traccar.py
trackr.py
ubee.py
ubus.py
unifi.py
unifi_direct.py
upc_connect.py
xfinity.py
xiaomi.py
dialogflow
digital_ocean
discovery
dominos
doorbird
dovado
downloader
duckdns
dweet
dyson
ebusd
ecoal_boiler
ecobee
ecovacs
edp_redy
egardia
eight_sleep
elkm1
emoncms_history
emulated_hue
emulated_roku
enigma2
enocean
envisalink
esphome
eufy
evohome
fan
fastdotcom
feedreader
ffmpeg
fibaro
folder_watcher
foursquare
freebox
freedns
fritzbox
frontend
gc100
geo_location
geofency
goalfeed
google
google_assistant
google_domains
google_pubsub
googlehome
gpslogger
graphite
greeneye_monitor
group
habitica
hangouts
harmony
hassio
hdmi_cec
history
history_graph
hive
hlk_sw16
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
http
huawei_lte
hue
hydrawise
idteck_prox
ifttt
ihc
image_processing
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
insteon_local
insteon_plm
intent_script
introduction
ios
iota
iperf3
ipma
isy994
itach
joaoapps_join
juicenet
keyboard
keyboard_remote
kira
knx
konnected
lametric
lcn
lifx
light
lightwave
linode
lirc
litejet
locative
lock
logbook
logentries
logger
logi_circle
lovelace
luftdaten
lupusec
lutron
lutron_caseta
mailbox
mailgun
map
matrix
maxcube
media_extractor
media_player
melissa
meteo_france
microsoft_face
mobile_app
mochad
modbus
mqtt
mqtt_eventstream
mqtt_statestream
mychevy
mycroft
mysensors
mythicbeastsdns
namecheapdns
neato
ness_alarm
nest
netatmo
netgear_lte
nissan_leaf
no_ip
notify
nuheat
nuimo_controller
octoprint
onboarding
opentherm_gw
openuv
owlet
owntracks
panel_custom
panel_iframe
persistent_notification
person
pilight
plant
plum_lightpad
point
prometheus
proximity
ps4
python_script
qwikswitch
rachio
rainbird
raincloud
rainmachine
raspihats
recorder
reddit
remember_the_milk
remote
rest_command
rflink
rfxtrx
ring
roku
route53
rpi_gpio
rpi_pfio
rss_feed_template
sabnzbd
satel_integra
scene
script
scsgate
sense
sensor
shell_command
shiftr
shopping_list
simplisafe
sisyphus
skybell
sleepiq
smappee
smartthings
smhi
snips
sonos
spaceapi
spc
speedtestdotnet
spider
splunk
statsd
stream
sun
switch
system_health
system_log
tado
tahoma
telegram_bot
tellduslive
tellstick
tesla
thethingsnetwork
thingspeak
thinkingcleaner
tibber
timer
tof
toon
tplink
tplink_lte
tradfri
transmission
tts
tuya
twilio
unifi
upcloud
updater
upnp
usps
utility_meter
vacuum
velbus
velux
vera
verisure
volvooncall
vultr
w800rf32
wake_on_lan
water_heater
waterfurnace
watson_iot
weather
webhook
weblink
webostv
websocket_api
wemo
wink
wirelesstag
wunderlist
xiaomi_aqara
xiaomi_miio
xs1
zabbix
zeroconf
zha
zigbee
zone
zoneminder
zwave
__init__.py
services.yaml
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
requirements.py
setup.py
script
tests
virtualization
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
mypy.ini
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini

* Add python 3.7 to travis and tox * Use pyyaml from github * Don't version constraints * Fix version tag * Change to new pyyaml release * Python 3.7 requires xenial * Fix namespace detection * Use correct RegEx type * Update pexpect to 4.6 * Use correct validation for dictionaries * Disable Py37 incompatible packages * Upgrade all pexpect to 4.6 * Add explicit None as default param
156 lines
4.6 KiB
Python
156 lines
4.6 KiB
Python
"""
|
|
Support for Cisco IOS Routers.
|
|
|
|
For more details about this platform, please refer to the documentation at
|
|
https://home-assistant.io/components/device_tracker.cisco_ios/
|
|
"""
|
|
import logging
|
|
|
|
import voluptuous as vol
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
|
from homeassistant.components.device_tracker import (
|
|
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
|
|
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, \
|
|
CONF_PORT
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
REQUIREMENTS = ['pexpect==4.6.0']
|
|
|
|
PLATFORM_SCHEMA = vol.All(
|
|
PLATFORM_SCHEMA.extend({
|
|
vol.Required(CONF_HOST): cv.string,
|
|
vol.Required(CONF_USERNAME): cv.string,
|
|
vol.Optional(CONF_PASSWORD, default=''): cv.string,
|
|
vol.Optional(CONF_PORT): cv.port,
|
|
})
|
|
)
|
|
|
|
|
|
def get_scanner(hass, config):
|
|
"""Validate the configuration and return a Cisco scanner."""
|
|
scanner = CiscoDeviceScanner(config[DOMAIN])
|
|
|
|
return scanner if scanner.success_init else None
|
|
|
|
|
|
class CiscoDeviceScanner(DeviceScanner):
|
|
"""This class queries a wireless router running Cisco IOS firmware."""
|
|
|
|
def __init__(self, config):
|
|
"""Initialize the scanner."""
|
|
self.host = config[CONF_HOST]
|
|
self.username = config[CONF_USERNAME]
|
|
self.port = config.get(CONF_PORT)
|
|
self.password = config.get(CONF_PASSWORD)
|
|
|
|
self.last_results = {}
|
|
|
|
self.success_init = self._update_info()
|
|
_LOGGER.info('cisco_ios scanner initialized')
|
|
|
|
def get_device_name(self, device):
|
|
"""Get the firmware doesn't save the name of the wireless device."""
|
|
return None
|
|
|
|
def scan_devices(self):
|
|
"""Scan for new devices and return a list with found device IDs."""
|
|
self._update_info()
|
|
|
|
return self.last_results
|
|
|
|
def _update_info(self):
|
|
"""
|
|
Ensure the information from the Cisco router is up to date.
|
|
|
|
Returns boolean if scanning successful.
|
|
"""
|
|
string_result = self._get_arp_data()
|
|
|
|
if string_result:
|
|
self.last_results = []
|
|
last_results = []
|
|
|
|
lines_result = string_result.splitlines()
|
|
|
|
# Remove the first two lines, as they contains the arp command
|
|
# and the arp table titles e.g.
|
|
# show ip arp
|
|
# Protocol Address | Age (min) | Hardware Addr | Type | Interface
|
|
lines_result = lines_result[2:]
|
|
|
|
for line in lines_result:
|
|
parts = line.split()
|
|
if len(parts) != 6:
|
|
continue
|
|
|
|
# ['Internet', '10.10.11.1', '-', '0027.d32d.0123', 'ARPA',
|
|
# 'GigabitEthernet0']
|
|
age = parts[2]
|
|
hw_addr = parts[3]
|
|
|
|
if age != "-":
|
|
mac = _parse_cisco_mac_address(hw_addr)
|
|
age = int(age)
|
|
if age < 1:
|
|
last_results.append(mac)
|
|
|
|
self.last_results = last_results
|
|
return True
|
|
|
|
return False
|
|
|
|
def _get_arp_data(self):
|
|
"""Open connection to the router and get arp entries."""
|
|
from pexpect import pxssh
|
|
import re
|
|
|
|
try:
|
|
cisco_ssh = pxssh.pxssh()
|
|
cisco_ssh.login(self.host, self.username, self.password,
|
|
port=self.port, auto_prompt_reset=False)
|
|
|
|
# Find the hostname
|
|
initial_line = cisco_ssh.before.decode('utf-8').splitlines()
|
|
router_hostname = initial_line[len(initial_line) - 1]
|
|
router_hostname += "#"
|
|
# Set the discovered hostname as prompt
|
|
regex_expression = ('(?i)^%s' % router_hostname).encode()
|
|
cisco_ssh.PROMPT = re.compile(regex_expression, re.MULTILINE)
|
|
# Allow full arp table to print at once
|
|
cisco_ssh.sendline("terminal length 0")
|
|
cisco_ssh.prompt(1)
|
|
|
|
cisco_ssh.sendline("show ip arp")
|
|
cisco_ssh.prompt(1)
|
|
|
|
devices_result = cisco_ssh.before
|
|
|
|
return devices_result.decode('utf-8')
|
|
except pxssh.ExceptionPxssh as px_e:
|
|
_LOGGER.error("pxssh failed on login")
|
|
_LOGGER.error(px_e)
|
|
|
|
return None
|
|
|
|
|
|
def _parse_cisco_mac_address(cisco_hardware_addr):
|
|
"""
|
|
Parse a Cisco formatted HW address to normal MAC.
|
|
|
|
e.g. convert
|
|
001d.ec02.07ab
|
|
|
|
to:
|
|
00:1D:EC:02:07:AB
|
|
|
|
Takes in cisco_hwaddr: HWAddr String from Cisco ARP table
|
|
Returns a regular standard MAC address
|
|
"""
|
|
cisco_hardware_addr = cisco_hardware_addr.replace('.', '')
|
|
blocks = [cisco_hardware_addr[x:x + 2]
|
|
for x in range(0, len(cisco_hardware_addr), 2)]
|
|
|
|
return ':'.join(blocks).upper()
|