kbr / fritzconnection Goto Github PK
View Code? Open in Web Editor NEWPython-Tool to communicate with the AVM Fritz!Box by the TR-064 protocol and the AHA-HTTP-Interface
License: MIT License
Python-Tool to communicate with the AVM Fritz!Box by the TR-064 protocol and the AHA-HTTP-Interface
License: MIT License
Is it possible to connect via SSL to a fritzbox.
I am using a custom component for Home Assistant called ha-fritzbox-tools.
Unfortunately, it cannot get the state of my guest wifi. See this issue for more information.
Ticked the necessary checkboxes in Access Settings in the Home Network
Occurred after upgrading to version: 0.8.4
Surprisingly this has worked before with 0.6.5
, however I cannot seem to replicate it anymore.
Requests version: 2.22.0
Fritzbox model: FritzBox 7560
After entering this:
import fritzconnection as fc
c = fc.FritzConnection(
address='yourhost',
port= 49000,
user='yourusername',
password='yourpassword'
)
print(c.call_action('WLANConfiguration:3', 'GetInfo'))
the last line returns an empty dict {}
which is needed for getting the guest wifi state.
However, the connection is established successfully, since this:
print(c.call_action('Layer3Forwarding:1','GetDefaultConnectionService')['NewDefaultConnectionService'])
returns 1.WANPPPConnection.1
Hope you guys can help me out :)
When I try to login through the library, I get an AuthorizationError. I can confirm the same login info lets me log into the web UI.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sylvia/.local/lib/python3.7/site-packages/fritzconnection/fritzconnection.py", line 456, in reconnect
self.call_action('WANIPConnection', 'ForceTermination')
File "/home/sylvia/.local/lib/python3.7/site-packages/fritzconnection/fritzconnection.py", line 449, in call_action
return action.execute(**kwargs)
File "/home/sylvia/.local/lib/python3.7/site-packages/fritzconnection/fritzconnection.py", line 134, in execute
raise AuthorizationError('unauthorized request')
fritzconnection.fritzconnection.AuthorizationError: unauthorized request
Any clue what could be wrong and how I could figure it out? Do I have an unsupported model perhaps? (FRITZ!Box 7581)
Hello!
I'd like to have support for the following use case. I'm willing to pay a beer casket (maybe with Durstexpress.de)
I'd like to be able to take down all port forwarding assigned to any device with a specific port, such as 80. Then I'd like to enable one device to port forward.
In this case, does the TR-069 Fritz protocol or any of it's extensions allow a single host in the network to manage port forwarding for other hosts?
I'd like to use Home Assistant and detect if a host is online to turn on port-forwarding and then if it's offline disable the port-forwarding.
The format for .coveralls.yml
is
repo_token: $TOKEN
Once this is working locally follow the instructions for setting up for GitHub using an env var.
Hi,
I have a problem with my integration of Fritz into hassio into log i recive alots of messages about an error include /usr/local/lib/python3.7/site-packages/fritzconnection/fritzhosts.py method get_hosts_info.
File "/usr/local/lib/python3.7/site-packages/fritzconnection/fritzhosts.py", line 73, in get_hosts_info
'ip': host['NewIPAddress'],
KeyError: 'NewIPAddress'
I thing the problem it is in these point for some reason my fritz don't give any host result
I have FRITZ!Box 4040 with 07.12.
Thanks for the Help.
First of all thank you for this great component.
I have a problem with the new version 1.1.0.
(venv37) rene@DERNHASS01:~/home-assistant$ fritzconnection -i XXX -p XXX
FritzConnection v1.1
Traceback (most recent call last):
File "/home/rene/home-assistant/venv37/bin/fritzconnection", line 8, in <module>
sys.exit(main())
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 163, in main
run_inspector(inspector, args)
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 143, in run_inspector
inspector.view_header()
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 36, in view_header
print(self.fc)
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/core/fritzconnection.py", line 90, in __repr__
return f"{self.modelname} at ip {self.soaper.address}\n"\
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/core/fritzconnection.py", line 105, in modelname
return self.device_manager.modelname
File "/home/rene/home-assistant/venv37/lib/python3.7/site-packages/fritzconnection/core/devices.py", line 34, in modelname
return self.descriptions[0].device_model_name
IndexError: list index out of range
The same command in V1.0.1 works without error:
(vnev) rene@DERNHASS01:~/projects/tests$ fritzconnection -i XXX -p XXX
FritzConnection v1.0.1
FRITZ!Box 7590 at ip 192.168.178.1
FRITZ!OS: 7.12
If I do not deliver the IP address then the error is the same, but takes much longer.
(vnev) rene@DERNHASS01:~/projects/tests$ fritzconnection
FritzConnection v1.0.1
Traceback (most recent call last):
File "/home/rene/projects/tests/vnev/bin/fritzconnection", line 10, in <module>
sys.exit(main())
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 163, in main
run_inspector(inspector, args)
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 143, in run_inspector
inspector.view_header()
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/cli/fritzinspection.py", line 36, in view_header
print(self.fc)
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/core/fritzconnection.py", line 83, in __repr__
return f"{self.modelname} at ip {self.soaper.address}\n"\
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/core/fritzconnection.py", line 98, in modelname
return self.device_manager.modelname
File "/home/rene/projects/tests/vnev/lib/python3.7/site-packages/fritzconnection/core/devices.py", line 33, in modelname
return self.descriptions[0].device_model_name
IndexError: list index out of range
Environment:
Linux Mint 19.1
Python: 3.7.6
Hi Klaus,
is there a way to conntect to FB using IPV6 ?
didn't find it in "https://fritzconnection.readthedocs.io/en/1.2.1/"
tnx
Norbert
The Fritz!Box has no way to share the local hostnames/IP resolution with remote locations (e.g. VPN).
It would be helpful if fritzhosts
gets an argument to create a hosts file (e.g. /etc/hosts.fritz
) with a user supplied domain name.
Currently I use
*/2 * * * * fritzhosts --ip-address '192.168.178.1' --port 49000 --username '<myuser>' --password '<mypasswd>' | sed -e '/^$/d' -e '/^[[:graph:]].*/d' -e '/ n:/d' -e 's/^ \{1,2\}[[:digit:]]\{1,2\}: \([[:graph:]]\+\) \+\([[:graph:]]\+\) \+\([[:graph:]]\+\).*/\1\t\t\2.<mydomain.tld>/' -e 's/fritz.box/fritz/' -e 's/RIPE-Atlas-Probe-3156/ripe/' > /etc/hosts.fritz
as a cronjob on OpenWRT which is a quite complicated syntax.
I need to forward multiple ports, so i configured a port-forwarding range. If i try to get it with your tool, i get this error:
File "<input>", line 1, in <module>
File "C:\Users\kimm8\PycharmProjects\arithmetische\venv\lib\site-packages\fritzconnection\core\fritzconnection.py", line 209, in call_action
return self.soaper.execute(service, action_name, arguments)
File "C:\Users\kimm8\PycharmProjects\arithmetische\venv\lib\site-packages\fritzconnection\core\soaper.py", line 170, in execute
return handle_response(response)
File "C:\Users\kimm8\PycharmProjects\arithmetische\venv\lib\site-packages\fritzconnection\core\soaper.py", line 154, in handle_response
return self.parse_response(response, service, action_name)
File "C:\Users\kimm8\PycharmProjects\arithmetische\venv\lib\site-packages\fritzconnection\core\soaper.py", line 197, in parse_response
value = self.conversion_table[data_type](value)
ValueError: invalid literal for int() with base 10: '27005-27015'
As mentioned in previous issue, but this should go in an extra ticket, e.g. so we can solve it with a PR:
When debugging I get this for building the envelope: there is really no space between s:encodingStyle and the followed xmlns:s
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
<?xml version="1.0" encoding="utf-8"?><s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><u:GetPhonebook xmlns:u="urn:dslforum-org:service:X_AVM-DE_OnTel:1"><s:NewPhonebookId>0</s:NewPhonebookId></u:GetPhonebook></s:Body></s:Envelope>
The even more strange thing is, AVM Fritzbox does not care and will still process it, although it's TBH invalid XML!
So, what's the culprit?:
soaper.py L124:
envelope = re.sub(r'\s +', '', """
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">{body}
</s:Envelope>
""")
the re.sub expression glues both together. If you instead write it side by side, with a space between, it will not glue, but be over the 80 columns of course .)
I'm somewhat only linking an issue from @home-assistant on the "fritzbox_netmonitor" integration to here since it relies on fritzconnection IIRC.
Problem is that the transmission rates (both up and down) show spikes (both negative/positive). Is this something actually reported by the FB or due to the implementation?
Hi
I will soon buy a FritzBox and I would like to use it to detect home presence. To do so, I would like to use fritzconnection and polling the router every 30 seconds.
Most probably, rather than running the fritzconnection.py every 30s, I think I'd better establish the connection with the router just once and do the poll every 30s with a python program: am I correct?
I wonder if this continuous 24/7 polling would kill the router or if this is a perfectly safe procedure I can use. Any experience about that?
Thanks for your suggestion!
I'm in the middle of converting Home Assistant compontent for FritzBox. It used the old version 0.8.4 with gives some errors (#21). While converting the code to version 1.0.1, I came across class FritzPhonebook
that exists in version 0.8.4 and doesn't seem to be available in 1.0.1.
Is there an equal class of FritzPhonebook
in the new version that I can use?
Hi Klaus,
was the fritzcallforwarding module i contributed somehow removed on purpose or did it get lost in the translation somewhere?
fritzcall.py could be enhanced with "new" call types, see page 20 here:
https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/x_contactSCPD.pdf
1 incoming,
2 missed,
3 outgoing,
9 active incoming,
10 rejected incoming,
11 active outgoing
Especially type 10 is important for me, as I maintain a phonebook just for blocked numbers. And it really exists if I retrieve last calls, example:
<Call><Id>6380</Id><Type>10</Type><Caller>021197633xxx</Caller><Called>SIP: 12345</Called><CalledNumber>12345</CalledNumber><Name>ZeitschriftenAbo mvd</Name><Numbertype>sip</Numbertype><Device></Device><Port>-1</Port><Date>15.06.20 13:27</Date><Duration>0:00</Duration><Count></Count><Path /></Call>
The only change in version 0.8.5 is, as a0e202b suggests, that the lxml dependency changed.
Installing it with pip
gives a different picture, done on an Ubuntu 18.04 system:
virtualenv --no-site-packages venv
. ./venv/bin/activate
pip install fritzconnection
pip list
fritzconnection 0.8.5
lxml 4.5.1
fritzconnection -s
FritzConnection:
version: 0.8.4
So lxml is indeed 4.5.1, but the fritzconnection
command still returns 0.8.4
.
Beyond that, the ip-address heuristics seems to have changed. My setup is
fritz.box 192.168.178.1
fritz.repeater 192.168.178.39
The 0.8.4 fritzconnection finds the fritz.box without -i
option.'
fritzconnection -s
FritzConnection:
version: 0.8.4
model: FRITZ!Box 7590
Servicenames:
WANCommonIFC:1
....
The 0.8.5 fritzconnection doesn't find a device (empty list).
When 0.8.5 fritzconnection is called with -u
and -p
and without -i
is finds the fritz.repeater.
fritzconnection -s
FritzConnection:
version: 0.8.4
model: None
Servicenames:
()
fritzconnection -p xxx -u xxx -s
FritzConnection:
version: 0.8.4
model: FRITZ!Repeater 3000
Servicenames:
DeviceConfig:1
DeviceInfo:1
Hosts:1
UserInterface:1
WLANConfiguration:1
WLANConfiguration:2
WLANConfiguration:3
WLANConfiguration:4
It seems that the code base changed in a different way than suggested by a0e202b.
Does the API already have WOL support? I couldn't find it in the FritzHosts class
Hello,
i would to use your program. Seems very powerfull!
I installed it on Raspberry PI4, Buster.
Would like to use call-dial-help function like i saw in example
$ fritzcall -i 192.168.178.1 -p <password> -c <phonenumber>
dialing number: <phonenumber>
dialing done, please wait for signal.
but i et error - fritzcall.py: error: unrecognized arguments: --call 32536
Is it a bug or am i doning somthing wrong?
Thanks a lot!
As said I maintain a phonebook for cold calls. Sometimes, I will just use similar or even equal names, because it's just gambling 1,2,3.. so e.g. I have these items:
Gewinnspiel ['02212928xxx']
Gewinnspiel ['0892213xxx']
But both methods:
contacts = fp.get_all_names(phonebook_id)
contacts = fp.get_all_numbers(phonebook_id)
will just print out the latter one:
Gewinnspiel ['0892213xxx']
Like all the same named before are overwritten by the last one. If I change one of the two items in the Fritzbox, e.g. to Gewinnspiel1.. then it works and I get printed them both.
As I created 4 issues now let me be clear: I am a big fan of this tool set! I just want to document any strange behavior, or give incentives what could be improved.
add.description()
should be called in the test not the fixture.
["Maybe" unrelated to the overall project]
I just found (at least I think) by coincidence a awesome Goodie.
With Fritzconection u can get the current Down-/Upstream to the ISP. But not the "Bandwidth Saturation" which would provide useful information.
The Fritzbox has an "Online-Monitor" with a graph for that.
I found that the browser makes a simple GET Req to a Url to retrieve that info and build the ajaxgraph every second.
Ok, turns out you need auth for the URL. You need to create a sid for the URL.
For me the URL looks like: "http://fritz.box/internet/inetstat_monitor.lua?sid=[YOUR-SID]&myXhr=1&action=get_graphic&useajax=1&xhr=1&t1569928285267=nocache"
Just go to the Online-Monitor page activate DevTools>Network and you will see the Packages coming in.
It should retrive Data simular to:
downstream: 106826000
ds_bps_curr: [17375, 105760, 5752, 73004, 9411, 2519, 4005, 2796, 2646, 8175, 4399, 4426, 2791, 4559, 3367, 2320,…]
ds_bps_curr_max: 105760
ds_bps_max: 13353250
ds_guest_bps_curr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ds_mc_bps_curr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
dynamic: false
guest_us_bps: [0]
mode: "VDSL"
name: "sync_dsl"
upstream: 36680000
us_background_bps_curr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
us_bps_curr_max: 9914
us_bps_max: 4585000
us_default_bps_curr: [1468, 1048, 1249, 1182, 1321, 1296, 1253, 1405, 1642, 1207, 1206, 1538, 1452, 1009, 2106, 1315, 1491,…]
us_important_bps_curr: [1117, 272, 284, 134, 52, 88, 39, 28, 13, 84, 66, 56, 181, 57, 15, 15, 60, 93, 106, 136]
us_realtime_bps_curr: [658, 8594, 1914, 3741, 3962, 124, 632, 342, 119, 2607, 878, 475, 514, 3162, 578, 1650, 989, 122, 7,…]
_node: "sg0"
where the frist element of ds_bps_curr
is the current Downstream viseversa to us_default_bps_curr
for upstream.
I thought you might like that as well. Implementations for that are limitless. ;)
Thx for creating this excellent library!
Using 0.8.4 which was installed by pip I am trying
fc.call_action("X_VoIP:1", "X_AVM-DE_DialNumber",arguments={'NewX_AVM-DE_PhoneNumber':'**612#'})
and get an empty result and nothing happens
fc.call_action("X_VoIP:1", "X_AVM-DE_DialNumber",NewX_AVM-DE_PhoneNumber='**612#'})
would probably work but is invalid syntax due to the dash in the parameter name ...
What would be needed to get this working?
fritzwlan throws error
Hosts registered at WLANConfiguration1:
WLAN name: Boromir6
channel : 1
index active mac ip signal speed
Traceback (most recent call last):
File "/usr/local/bin/fritzwlan", line 10, in
sys.exit(main())
File "/usr/local/lib/python3.7/dist-packages/fritzconnection/cli/fritzwlan.py", line 85, in main
report_devices(fw, args)
File "/usr/local/lib/python3.7/dist-packages/fritzconnection/cli/fritzwlan.py", line 67, in report_devices
report_wlanconfiguration(fw, n)
File "/usr/local/lib/python3.7/dist-packages/fritzconnection/cli/fritzwlan.py", line 52, in report_wlanconfiguration
print(f'{index:>5}{status:>8}{mac:>20}{ip:>18}{signal:>8}{speed:>8}')
TypeError: unsupported format string passed to NoneType.format
Most likely caused by the fact that ip returns a None instead of an ip-number
http://192.168.2.30:49000/upnp/control/wlanconfig1 <s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><u:GetGenericAssociatedDeviceInfo xmlns:u="urn:dslforum-org:service:WLANConfiguration:1"><s:NewAssociatedDeviceIndex>5</s:NewAssociatedDeviceIndex></u:GetGenericAssociatedDeviceInfo></s:Body></s:Envelope> {'soapaction': 'urn:dslforum-org:service:WLANConfiguration:1#GetGenericAssociatedDeviceInfo', 'content-type': 'text/xml', 'charset': 'utf-8'}
[{'service': 1, 'index': 0, 'status': True, 'mac': '64:27:37:44:F7:2C', 'ip': None, 'signal': 93, 'speed': 0}, {'service': 1, 'index': 1, 'status': True, 'mac': '12:81:2B:76:92:EC', 'ip': '192.168.2.24', 'signal': 91, 'speed': 72}, {'service': 1, 'index': 2, 'status': True, 'mac': 'EE:CE:1E:E0:CD:21', 'ip': None, 'signal': 65, 'speed': 0}, {'service': 1, 'index': 3, 'status': True, 'mac': '48:0B:B2:51:2E:FE', 'ip': '192.168.2.33', 'signal': 41, 'speed': 6}, {'service': 1, 'index': 4, 'status': True, 'mac': '84:F3:EB:E3:9C:1F', 'ip': '192.168.2.83', 'signal': 65, 'speed': 70}]
Issue appears between on connection between 2 Fritz!wlan 1750 repeaters.
In Fritz web-interface this shows up as 1 up-number on 2 MAC addresses (1 mac for 2,4 and one for 5
Henri
Any chance to enhance this lib and allow updates to addressbook(s) entries and adding new entries?
I am monitoring a remote fritzbox with several Fritz!DECT200 and 301 devices.
The monitoring software (munin) runs every 5 minutes and starts ~12 scripts. Each script uses fritzconnection to connect to the remote box and extracts a single value. Because fritzconnection starts from scratch on every call it has to download all the xml files before the actual call can be executed. In my setup getting the xml descriptions takes ~25 seconds and then another second for the call to request the wanted information.
I therefore propose the introduction of a file-based cache for the given address, maybe by adding another parameter cacheDir which must point to an existing directory where a sub-directory for each ip-address is created which contains the xml files as downloaded on the first run.
Today I discovered a reset of fritzstatus values bytes sent
and bytes received
v to 0, if it overcome around 4300 Megabytes. I cant precise this because 4300MB was the highest value I was able to monitor (just to much idle traffic)
I'm not sure if this is releated to this topic at all, as I debugged a bit and got the zero values directly as api response, but I still wantetd to discuss here before reporting it to avm.
I created a minimum example showing the issue:
#!/usr/bin/env python
from fritzconnection import FritzConnection
import sys
import os
FRITZBOX_IP = os.environ.get('TGFB_IP', '192.168.178.1')
FRITZBOX_USER = os.environ.get('TGFB_USER', 'telegraf')
FRITZBOX_PASSWORD = os.environ.get('TGFB_PASSWD')
FRITZBOX_ID = os.environ.get('TGFB_ID', 'FrizBox')
def readfritz(module, action):
try:
answer= fc.call_action(module, action)
except BaseException:
print(f"Could not query {module} with action {action}")
raise
return answer
try:
print(f"Connecting to {FRITZBOX_IP} as user {FRITZBOX_USER}")
fc = FritzConnection(address=FRITZBOX_IP, user=FRITZBOX_USER, password=FRITZBOX_PASSWORD, timeout=5.0)
except BaseException:
print("Cannot connect to fritzbox.")
sys.exit(1)
deviceInfo = readfritz('DeviceInfo1', 'GetInfo')
print(f"connected to {deviceInfo['NewModelName']}")
connectionInfo = readfritz('WANPPPConnection1', 'GetInfo')
print(connectionInfo)
When ran with, it fails with:
$ TGFB_IP=192.168.0.1 TGFB_USER=someuser TGFB_PASSWD=secret python3 ./test.py
Connecting to 192.168.0.1 as user someuser
connected to FRITZ!Box 6490 Cable (lgi)
Could not query WANPPPConnection1 with action GetInfo
Traceback (most recent call last):
File "./test.py", line 31, in <module>
connectionInfo = readfritz('WANPPPConnection1', 'GetInfo')
File "./test.py", line 14, in readfritz
answer= fc.call_action(module, action)
File "/usr/local/lib/python3.8/site-packages/fritzconnection/core/fritzconnection.py", line 218, in call_action
return self.soaper.execute(service, action_name, arguments)
File "/usr/local/lib/python3.8/site-packages/fritzconnection/core/soaper.py", line 233, in execute
return handle_response(response)
File "/usr/local/lib/python3.8/site-packages/fritzconnection/core/soaper.py", line 218, in handle_response
raise_fritzconnection_error(response)
File "/usr/local/lib/python3.8/site-packages/fritzconnection/core/soaper.py", line 147, in raise_fritzconnection_error
raise exception(message)
fritzconnection.core.exceptions.FritzActionError: UPnPError:
errorCode: 401
errorDescription: Invalid Action
This was obviously ran with a valid user and password.
I am not sure if this problem is because of myself, I even debugged your code, but still I am lost what is the problem. In short the problem: although it seems everything to be utf-8, even the name 'CallBlockerTest-Ümlaut' itself, it will not work because and only because of the ü (if I remove it, all works fine). I post the stacktrace below. I also searched in the official documentation but did find nothing about how to handle Umlaute/Umlauts correctly.. fc is fritzconnection in my case..
arg = {'NewPhonebookID': pb_id,
'NewPhonebookEntryID': '',
'NewPhonebookEntryData':
f'<?xml version="1.0" encoding="utf-8"?>'
f'<Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
f'<contact>'
f'<category>0</category>'
f'<person><realName>{name}</realName></person>'
f'<telephony nid="1"><number type="home" prio="1" id="0">{number}</number></telephony>'
f'</contact>'
f'</Envelope>'}
return self.fc.call_action('X_AVM-DE_OnTel:1', 'SetPhonebookEntry', arguments=arg)
Traceback (most recent call last):
File "C:/workspace/python/a1-fritzbox/a1fritzbox/phonebook.py", line 146, in <module>
result = pb.add_contact(2, 'CallBlockerTest-Ümlaut', '009912345', skip_existing=False)
File "C:/workspace/python/a1-fritzbox/a1fritzbox/phonebook.py", line 81, in add_contact
return self.fc.call_action('X_AVM-DE_OnTel:1', 'SetPhonebookEntry', arguments=arg)
File "C:\Python3\lib\site-packages\fritzconnection\core\fritzconnection.py", line 215, in call_action
return self.soaper.execute(service, action_name, arguments)
File "C:\Python3\lib\site-packages\fritzconnection\core\soaper.py", line 194, in execute
return handle_response(response)
File "C:\Python3\lib\site-packages\fritzconnection\core\soaper.py", line 176, in handle_response
raise_fritzconnection_error(response)
File "C:\Python3\lib\site-packages\fritzconnection\core\soaper.py", line 105, in raise_fritzconnection_error
raise exception(message)
fritzconnection.core.exceptions.FritzConnectionException: UPnPError:
errorCode: 502
errorDescription: XML error
BTW, if I use ü
instead of ü it will work and arrive as ü in the phonebook. But TBH I don't want to create html entities, or do I have to? Although everything is set to utf-8, even the content-type header? Is it something AVM Fritzbox specific?
When I try to call the fritzconnection command "fritzwlan" I get the following python error:
Traceback (most recent call last): File "/usr/local/bin/fritzwlan", line 10, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 205, in main _print_status(_get_cli_arguments()) File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 202, in _print_status print_hosts(fh) File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 105, in print_hosts hosts = fh.get_hosts_info() File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 73, in get_hosts_info while index < self.host_numbers: File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 55, in host_numbers result = self.action('GetTotalAssociations') File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzwlan.py", line 47, in action return self.fc.call_action(service, actionname, **kwargs) File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzconnection.py", line 489, in call_action action = self._get_action(service_name, action_name) File "/usr/local/lib/python2.7/dist-packages/fritzconnection/fritzconnection.py", line 462, in _get_action raise ServiceError('Unknown Service: ' + service_name) fritzconnection.fritzconnection.ServiceError: Unknown Service: WLANConfiguration:1
Something similar happens when using "fritzhosts".
Any idea on how to solve this? 'fritzstatus' works flawlessly.
print_api has moved in version 1.0 and i had to comment it out. What is the replacement?
When I try:
fc = fritzconnection.FritzConnection(address='192.168.90.1', password='wrong_password')
fc.call_action('WLANConfiguration', 'GetInfo')
I get a trace back error:
/home/heti/Development/fritzconnection/fritzconnection/core/soaper.py(53)raise_fritzconnection_error()
-> root = etree.fromstring(response.content)
(Pdb) l
48 Will raise a FritzConnectionException or a subclass.
49 """
50 parts = []
51 error_code = None
52 import pdb;pdb.set_trace()
53 -> root = etree.fromstring(response.content)
54 detail = root.find('.//detail')
55 for node in detail.iterdescendants():
56 tag = node.tag.split('}')[-1]
57 text = node.text.strip()
58 if tag == 'errorCode':
(Pdb) p response.content
b'<HTML><HEAD><TITLE>401 Unauthorized (ERR_NONE)</TITLE></HEAD><BODY><H1>401 Unauthorized</H1><BR>ERR_NONE<HR><B>Webserver</B> Sun, 17 Nov 2019 10:17:47 GMT</BODY></HTML>\r\n'
(Pdb) c
Traceback (most recent call last):
File "/home/heti/.local/share/virtualenvs/fritzconnection-ehIjW6m7/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-5cee539ecdc0>", line 1, in <module>
fc.call_action('WLANConfiguration', 'GetInfo')
File "/home/heti/Development/fritzconnection/fritzconnection/core/fritzconnection.py", line 124, in call_action
return self.soaper.execute(service, action_name, arguments)
File "/home/heti/Development/fritzconnection/fritzconnection/core/soaper.py", line 140, in execute
raise_fritzconnection_error(response)
File "/home/heti/Development/fritzconnection/fritzconnection/core/soaper.py", line 53, in raise_fritzconnection_error
root = etree.fromstring(response.content)
File "src/lxml/etree.pyx", line 3222, in lxml.etree.fromstring
File "src/lxml/parser.pxi", line 1877, in lxml.etree._parseMemoryDocument
File "src/lxml/parser.pxi", line 1765, in lxml.etree._parseDoc
File "src/lxml/parser.pxi", line 1127, in lxml.etree._BaseParser._parseDoc
File "src/lxml/parser.pxi", line 601, in lxml.etree._ParserContext._handleParseResultDoc
File "src/lxml/parser.pxi", line 711, in lxml.etree._handleParseResult
File "src/lxml/parser.pxi", line 640, in lxml.etree._raiseParseError
File "<string>", line 1
XMLSyntaxError: Opening and ending tag mismatch: HR line 1 and BODY, line 1, column 162
Hello,
I'm using fritzconnection (0.8.4), fritzcollectd (0.6.3), lxml (4.4.1) and requests (2.22.0) with collectd (5.8.1) on raspbian (10.1).
I'm getting following error while starting collectd:
error_collectd.txt
and when im using command line directly it gives me this:
using_python.txt
Is there something I can do to correct this?
Hello!
im using https://github.com/pdreker/fritzbox_exporter to export fritz!box data to my prometheus instance. For some reason, the data returned by GetTotalBytesReceived in NewTotalBytesReceived is resetted after ~4.23GB.
Can i somehow prevent this?
The code the exporter uses (conn
is a instance of fc.FritzConnection
):
fritzbox_wan_result = self.conn.call_action('WANCommonInterfaceConfig:1', 'GetTotalBytesReceived')
wan_bytes_rx = fritzbox_wan_result['NewTotalBytesReceived']
Regards
SeaLife
On my system fritzstatus
gives
max. bit rate : ('11.9 MBit/s', '59.3 MBit/s')
while my FrizBox GUI states
Geschwindigkeit: down 62,2 Mbit/s up 12,4 Mbit/s
The culprit is that fritzstatus
defines str_max_bit_rate
as
format_rate(upstream, unit='bits'),
format_rate(downstream, unit ='bits')
and format_rate
is defined as
return format_num(num, unit=unit) + '/s'
and format_num
converts in power of 1024 units.
Thus the classical MB vs MiB confusion, see Mebibyte.
The binary units are used for addressable items in binary systems. Memory size is in general measured in these units.
In all other cases decimal units are used. Bit rates, which are frequencies, are always expressed in decimal units, so 1 Mbps always means 1000*1000 bits/sec and not 1024*1024 bits/sec.
So usage of format_num
in fritzconnection should imho be reviewed.
FritzConnection on FB7590 / OS:7.12 produces the following errors. However on FB7490 & FB7390 it runs fine.
fritzconnection v1.3.4 -s -i 192.168.178.x
Traceback (most recent call last):
File "/usr/local/bin/fritzconnection", line 8, in
sys.exit(main())
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/cli/fritzinspection.py", line 149, in main
run_inspector(inspector, args)
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/cli/fritzinspection.py", line 126, in run_inspector
print_header(inspector.fc)
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/cli/utils.py", line 24, in print_header
print(instance)
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/core/fritzconnection.py", line 132, in repr
return f"{self.modelname} at {self.soaper.address}\n"
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/core/fritzconnection.py", line 147, in modelname
return self.device_manager.modelname
File "/usr/local/lib/python3.8/dist-packages/fritzconnection/core/devices.py", line 39, in modelname
return self.descriptions[0].device_model_name
IndexError: list index out of range
TLDR: the xml phonebook provided via Fritz!Box Lua seems to contain all internal numbers, too.
I tried to get all the entries for my phonebook id 2, which is for cold calls only. To do so, I used:
contacts = fp.get_all_names(2)
for name, numbers in contacts.items():
print(name, numbers)
However it seems every (!) phonebook will also include internal numbers as well, even in my list for cold calls, like: (I removed private numbers and names). [Possible solution below]
Alle (Rundruf) ['**9']
Anrufbeantworter ['**600', '**605']
Faxgerät ['**1']
FRITZ!App Fon (LGE LG-Hxxx, Name) ['**622']
Gewinnspiel ['0892213xxx']
I1 Nummer ['**610']
I2 Nummer ['**612']
I3 Nummer ['**613']
I4 Nummer ['**611']
ISDN/DECT Rundruf ['**50']
Lotto Berlin ['030422068xxx']
Lotto Neuss ['021317085xxx']
Names iPad ['**621']
Names iPhone ['**620']
Stromanbieter ['0493058877xxx']
Wecker 1 ['**41']
Wecker 2 ['**42']
Wecker 3 ['**43']
I checked the URL for the XML which is downloaded, unfortunately it also contains these internal numbers, it's a 7490 model here. So how could we filter them? I had a glimpse in the XML:
<number type="intern" vanity="" prio="1" >**9</number>
so type="intern" seems to represent an internal number, I've also seen "memo" or "". And:
<number type="home" vanity="" prio="1" >02212928xxx</number>
so only type="home" (wrong, see * below) seems to represent a real entry.
I could create an own branch and a pull request, if wished.
However, I've seen the processor for the xml.etree in the processor code is heavily examining node values, not attributes, before adding e.g the numbers via ValueSequencer just as a simple list. I guess, the author is more into this ;-) In case of a telephony record when the node is processed it would be available as: node.attrib with a dict of 3 entries, the keys are 'type', 'vanity', 'prio'. I guess it would be best to also extract at least the type. The other way would be to manipulate the xml.etree before processing it, e.g. by removing all (but full contact) entries where type != "home" (*)
(*) But, to make it even worse.. if comparing this with section "5.1 Phonebook Content" in https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/x_contactSCPD.pdf
it seems "home" is not the only value for "real" records, it could be also e.g. "work" etc. So we have to find out first the values for "real" records (whitelisting), or otherwise need a blacklist ("intern", "memo", "" spotted so far).
I just filled out anything in the Fritzbox for an invented whitelist number and set all the stuff, it seems "home", "mobile", "work" and "fax_work" would do the job for the whitelist.
<number type="home" vanity="" prio="1" >030xx</number>
<number type="mobile" vanity="" prio="" >030xx</number>
<number type="work" vanity="" prio="" >030xx</number>
<number type="fax_work" vanity="" prio="" >030xx</number>
Another very simple solution would be just to skip all numbers starting with "**", see above.
Hello!
I can't see my dect-repeater in home-automation devices. Is it possible to get (any) stats from a dect- repeater? Perhaps with another module? A simple "connected" would be enough...
Thanks for your efforts!
lxml is not buildable under Ubuntu Focal and fritzcollectd still depends on pre 1.0.0 fritzconnection. Could you release a version 0.8.5 which has no strict dependency on 4.3.4 but instead on 4.3.5? This would probably fix fritzcollectd under Ubuntu Focal/20.04 without any major reworks on either sides.
It would be nice if you could add new phone numbers by command line. Reason: I get a lot of cold calls and it drives me nuts always to have to re-login to the Fritzbox and go to the place of the correct phonebook, then to add it. How it could work I have found here:
https://forum.fhem.de/index.php?topic=64152.0
get FritzBox tr064Command X_AVM-DE_OnTel:1 x_contact SetPhonebookEntryUID NewPhonebookID 1 NewPhonebookEntryData '<Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><contact><category>0</category><person><realName>Sperr-KONTAKT</realName></person><telephony nid="1"><number type="home" prio="1" id="0">030123456789</number></telephony></contact>'
another solution (German) here: https://administrator.de/wissen/powershell-fritzbox-tr-064-netzwerk-konfigurieren-auslesen-303474.html - check method "Add-FBPhoneBookEntry".
I currently have two phonebooks: the first for normal users, and the other is called "ColdCalls". The latter one is configured to block all contained numbers. Of course it have to be ensured you add the number to the right list ;-)
The idea would be to add it by command line, something like:
fritzphonebook -i ip -p pass -add "ColdCalls | 0700123456 | CompanyXY"
or maybe add it by the phonebook id, in my case normal numbers is 0, ColdCalls is 1:
fritzphonebook -i ip -p pass -add -pbid 1 -phone 0700123456 -name CompanyXY
I would also understand if you want to keep the phonebook read-only. So I already forked this nice repository in case I have to solve it on my own ;-)
Currently fritzhosts
shows IPv4 addresses. It would be great if it also shows IPv6 addresses.
Hi,
just trying to switch to current version of your awesome library and wanted to add the timeout setting.
During testing I discovered that the timeout param seems to have no effect.
2020-07-30 12:18:04,034 - INFO: Done parsing config file
2020-07-30 12:18:04,034 - INFO: Connection timeout setting: 2
2020-07-30 12:18:04,042 - DEBUG: Starting new HTTP connection (1): 192.168.178.2:49000
2020-07-30 12:19:19,082 - ERROR: Failed to connect to FritzBox 'HTTPConnectionPool(host='192.168.178.2', port=49000): Max retries exceeded with url: /igddesc.xml (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x1022ea190>: Failed to establish a new connection: [Errno 60] Operation timed out'))'
I see that the timeout is passed on to requests here: https://github.com/kbr/fritzconnection/blob/master/fritzconnection/core/soaper.py#L241
but for some reason it is not honored.
Hi, I found in the documentation with URL:
this:
get_calls(calltype=0, update=True, num=None, days=None)
I did not inspect the code yet, but I think it would be great to mention at least in which order the calls are returned. Is it random, or first is last call, first is first call?
If it's random, could we establish additional parameters, something like:
Background: if someone just wants to check the last 10 calls, it is currently not clear if that would work with this libary module. Maybe it's just enough to extend the explanation in the documentation how to do so? Maybe it is already ordered in some way, but that should be written explicitely on top I guess.
It would be great if it where possible to set the timeouts for outgoing http requests (and therefore for the used requests module and lxml).
Motivation: i do have a use case where i would prefer the FritzConnection to fall rather than to stall the execution for two minutes.
Minimal Example:
start = datetime.now()
try:
fc = FritzConnection("google.com")
finally:
print(datetime.now()-start)
Output: 0:02:00.105666
I can't replicate that error on the 1.0 branch but I do have trouble connecting even with the correct password from the CLI. Testing on a Fritz 6490 Unitymedia.
fritzconnection charlieclark$ fritzconnection -i fritz.box -p pw
FritzConnection v1.0a1
Traceback (most recent call last):
File "/Users/charlieclark/Projects/fritzconnection/bin/fritzconnection", line 11, in <module>
load_entry_point('fritzconnection', 'console_scripts', 'fritzconnection')()
File "/Users/charlieclark/Projects/fritzconnection/fritzconnection/cli/fritzinspection.py", line 139, in main
inspector.view_header()
File "/Users/charlieclark/Projects/fritzconnection/fritzconnection/cli/fritzinspection.py", line 35, in view_header
print(self.fc)
File "/Users/charlieclark/Projects/fritzconnection/fritzconnection/core/fritzconnection.py", line 77, in __repr__
return f'{self.device_manager.modelname} at ip {self.soaper.address}'
File "/Users/charlieclark/Projects/fritzconnection/fritzconnection/core/devices.py", line 33, in modelname
return self.descriptions[0].device_model_name
IndexError: list index out of range
Moved from #12
The exceptions are are in the top-level namespace of the package. This obviously for a reason but I find it unusual and sightly confusing.
On a Fritz 6490, if I can connect I get an exception trying to access the WLANConfiguration.
fc.call_action('WLANConfiguration1', 'GetInfo')
Traceback (most recent call last):
Python Shell, prompt 7, line 121
builtins.KeyError: 'WLANConfiguration1'
During handling of the above exception, another exception was raised:
Traceback (most recent call last):
Python Shell, prompt 7, line 1
# Used internally for debug sandbox under external interpreter
File "/Users/charlieclark/Projects/fritzconnection/fritzconnection/core/fritzconnection.py", line 123, in call_action
raise FritzServiceError(f'unknown service: "{service_name}"')
fritzconnection.core.exceptions.FritzServiceError: unknown service: "WLANConfiguration1"
Moved from #12
The polled max bit rate does not equal with the actual value to be found at FB.
(Fritzconnection 1.2.1;PI3; FB7590)
Hi, we're using fritzconnection
over at https://github.com/mammuth/ha-fritzbox-tools (a custom component for Home Assistant). Thanks for providing the library (and moving it forward with updates) 🚀
When upgrading from 0.8.4 to 1.2.0 we noticed that argument and return types of action calls don't share the same type anymore.
See the following example:
>>>c.call_action("WLANConfiguration:3", "GetInfo")
# Note: 'NewEnable' in the result dict is a boolean
{'NewEnable': True, 'NewStatus': 'Up', 'NewMaxBitRate': 'Auto', 'NewChannel': 11, 'NewSSID': 'myssid', [...]}
# Let's try setting the state of the guest wifi by passing NewEnable=False (seems correct, since it just returned `False`, doesn't it?
>>> c.call_action("WLANConfiguration:3", "SetEnable", NewEnable=False)
Traceback (most recent call last):
File "<input>", line 1, in <module>
c.call_action("WLANConfiguration:3", "SetEnable", NewEnable=False)
File "/usr/local/lib/python3.7/site-packages/fritzconnection/core/fritzconnection.py", line 209, in call
_action
return self.soaper.execute(service, action_name, arguments)
File "/usr/local/lib/python3.7/site-packages/fritzconnection/core/soaper.py", line 170, in execute
return handle_response(response)
File "/usr/local/lib/python3.7/site-packages/fritzconnection/core/soaper.py", line 153, in handle_respon
se
raise_fritzconnection_error(response)
File "/usr/local/lib/python3.7/site-packages/fritzconnection/core/soaper.py", line 82, in raise_fritzcon
nection_error
raise exception(message)
fritzconnection.core.exceptions.FritzArgumentError: UPnPError:
errorCode: 402
errorDescription: Invalid Args
# Using "0" (as in previous versions) works fine
>>> c.call_action("WLANConfiguration:3", "SetEnable", NewEnable="0")
{}
When dealing with port forwards this produces some more overhead because the AddPortMapping
action requires the whole dictionary to be passed when you want to turn on/off the port forward.
So you would store the response dict of GetGenericPortMappingEntry
(which has a boolean) and then have to change it to "[0,1]" when using it as an argument for the AddPortMapping
action.
While people using fritzconnection
are surely able to handle this, I think it should be streamlined in fritzconnection
itself, so it's easier to use. What's your opinion on this?
We also noticed a change in the format of the services dict (FritzConnection(...)
.services).
While it used to be eg. {"WLANConfiguration:3": {...}}
, it's now {"WLANConfiguration3": {...}}
etc.
sorry i didnt know where to ask
so enabling WLAN like that works for me:
fc.call_action('WLANConfiguration3', 'SetEnable', NewEnable=True)
i wanted to set the SSID / Key, but im still not lucky
fc.call_action('WLANConfiguration3', 'SetSSID', NewSSID='guest-net')
current error say 402 / Argument error
same goes for setting the keys
fc.call_action('WLANConfiguration3', 'SetSecurityKeys', NewPreSharedKey='St4Rk3SP422w0rD')
i got the SSID set with 'SetEnable' instead of SetSSID
fc.call_action('WLANConfiguration3', 'SetEnable', NewSSID='guest-net')
which confuses me even more
so i tried this
arguments={'SetSSID': {'NewSSID': 'guest-net'}}
fc.call_action("WLANConfiguration3", 'SetEnable', arguments=arguments)
i got no error like befor, but nothing was changed
pls help
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.