-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathfritzBoxShell.sh
executable file
·2162 lines (1735 loc) · 96.6 KB
/
fritzBoxShell.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# shellcheck disable=SC1090,SC2154
#************************************************************#
#** Autor: Johannes Hubig <[email protected]> **#
#** Autor: Jürgen Key https://elbosso.github.io/index.html **#
#************************************************************#
# The following script should work from FritzOS 6.0 on-
# wards.
#
# Protokoll TR-064 was used to control the Fritz!Box and
# Fritz!Repeater. For sure not all commands are
# available on Fritz!Repeater.
# Additional info and documentation can be found here:
# http://fritz.box:49000/tr64desc.xml
# https://wiki.fhem.de/wiki/FRITZBOX#TR-064
# https://avm.de/service/schnittstellen/
# AVM, FRITZ!, Fritz!Box and the FRITZ! logo are registered trademarks of AVM GmbH - https://avm.de/
version=1.0.dev
dir=$(dirname "$0")
DIRECTORY=$(cd "$dir" && pwd)
source "$DIRECTORY/fritzBoxShellConfig.sh"
cd "$(dirname "$0")"
#******************************************************#
#*********************** SCRIPT ***********************#
#******************************************************#
# Parsing arguments
# Example:
# ./fritzBoxShell.sh --boxip 192.168.178.1 --boxuser foo --boxpw baa WLAN_2G 1
POSITIONAL=()
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
--boxip)
BoxIP="$2"
shift ; shift
;;
--boxuser)
BoxUSER="$2"
shift ; shift
;;
--boxpw)
BoxPW="$2"
shift ; shift
;;
--repeaterip)
RepeaterIP="$2"
shift ; shift
;;
--repeateruser)
RepeaterUSER="$2"
shift ; shift
;;
--repeaterpw)
RepeaterPW="$2"
shift ; shift
;;
-O|--outputformat)
OutputFormat="$2"
shift ; shift
;;
-F|--outputfilter)
OutputFilter="$2"
shift ; shift
;;
--backupconffolder)
backupConfFolder="$2"
shift ; shift
;;
--backupconffilename)
backupConfFilename="$2"
shift ; shift
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
# handle output format as wrapper to self
if [ -n "$OutputFormat" ]; then
# call self again with arguments
export BoxIP BoxUSER BoxPW RepeaterIP RepeaterUSER RepeaterPW
output=$($0 $*)
rc=$?
if [ $rc -ne 0 ]; then
echo "$(basename "$0"): error occured, output suppressed because option '-O|--outputformat ...' is provided" >&2
exit $rc
fi
if [ -n "$OutputFilter" ]; then
# apply output filter
output=$(echo "$output" | egrep $OutputFilter)
fi
# quote non-numbered values (skip empty lines)
output=$(echo "$output" | awk 'length($0) > 0 { if ($2 ~ "^[0-9]+$") print $1 " " $2; else print $1 " \"" $2 "\""; }')
case $OutputFormat in
influx)
# convert to influx input data string with prefix 'fritz'
echo "$output" | tr '\n' ',' | tr ' ' '=' | sed "s/,$//" | echo "fritz $(cat -)"
exit $rc
;;
graphite)
# convert to . separated key=value (skip empty lines)
echo "$output" | awk 'length($0) > 0 { print "fritz." $1 "=" $2 }'
exit $rc
;;
mrtg)
# convert to 2-line separated bytes received/sent value
echo "$output" | awk '$1 ~ /Bytes(Received|Sent)$/ { print $2 }'
exit $rc
;;
*)
# unsupported OutputFormat
echo "$(basename "$0"): error occured, '-O|--outputformat ...' active, but format not supported: $OutputFormat" >&2
exit 1
;;
esac
fi
# Storing shell parameters in variables
# Example:
# ./fritzBoxShell.sh WLAN_2G 1
# $1 = "WLAN_2G"
# $2 = "1"
option1="$1"
option2="$2"
option3="$3"
option4="$4"
### ----------------------------------------------------------------------------------------------------- ###
### --------- FUNCTION getSID is used to get a SID for all requests through AHA-HTTP-Interface----------- ###
### ------------------------------- SID is stored then in global variable ------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
# Global variable for SID
SID=""
getSID(){
location="/upnp/control/deviceconfig"
uri="urn:dslforum-org:service:DeviceConfig:1"
action='X_AVM-DE_CreateUrlSID'
SID=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" -H 'Content-Type: text/xml; charset="utf-8"' -H "SoapAction:$uri#$action" -d "<?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:$action xmlns:u='$uri'></u:$action></s:Body></s:Envelope>" | grep "NewX_AVM-DE_UrlSID" | awk -F">" '{print $2}' | awk -F"<" '{print $1}' | awk -F"=" '{print $2}')
if [ -z "$SID" ]; then
echo "Von SID could be retrieved. Please check your password and username eitehr by parameter or defined in the fritzBoxShellConfig.sh."
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------- FUNCTION SetInternet FOR allowing / disallowing Internet --------------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
SetInternet(){
# Get the a valid SID
getSID
# param2 = profile
# param3 = on/off
wget -O /dev/null --post-data "sid=$SID&toBeBlocked=$option2&blocked=$option3&page=kidLis" "http://$BoxIP/data.lua" 2>/dev/null
echo "Kindersicherung für $option2 steht auf $option3"
}
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------- FUNCTION SetProfile FOR putting a device into a profiles list ---------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
SetProfile(){
# Get the a valid SID
getSID
# param2 = device name
# param3 = device ID
# param4 = profile ID
wget -O /dev/null --post-data "sid=$SID&dev_name=$option2&dev=$option3&kisi_profile=$option4&page=edit_device&apply=true" "http://$BoxIP/data.lua" 2>/dev/null
echo "Gerät $option2 ($option3) in Profil $option4 verschoben"
}
### ----------------------------------------------------------------------------------------------------- ###
### ----------- FUNCTION LEDswitch FOR SWITCHING ON OR OFF THE LEDS IN front of the Fritz!Box ----------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
LEDswitch(){
# Get the a valid SID
getSID
# led_display=0 -> ON
# led_display=1 -> DELAYED ON (20200106: not really slower that option 0 - NOT USED)
# led_display=2 -> OFF
if [ "$option2" = "0" ]; then LEDstate=2; fi # When
if [ "$option2" = "1" ]; then LEDstate=0; fi
# Check if device supports LED dimming
json=$(wget -q -O - --post-data "xhr=1&sid=$SID&page=led" "http://$BoxIP/data.lua" | tr -d '"')
if grep -q 'canDim:1' <<< "$json"
then
# Extract LED brightness
dim=$(grep -o 'dimValue:[[:digit:]]*' <<< "$json" | cut -d : -f 2)
[[ -z "$dim" || "$dim" -lt 1 || "$dim" -gt 3 ]] && dim=3
wget -O /dev/null --post-data "sid=$SID&led_brightness=$dim&dimValue=$dim&led_display=$LEDstate&ledDisplay=$LEDstate&page=led&apply=" "http://$BoxIP/data.lua" 2>/dev/null
else
# For newer FritzOS (>5.5)
if grep -q 'ledDisplay:' <<< "$json"
then
wget -O - --post-data "sid=$SID&apply=&page=led&ledDisplay=$LEDstate" "http://$BoxIP/data.lua" &>/dev/null
else
wget -O - --post-data "sid=$SID&led_display=$LEDstate&apply=" "http://$BoxIP/system/led_display.lua" &>/dev/null
fi
fi
if [ "$option2" = "0" ]; then echo "LEDs switched OFF"; fi
if [ "$option2" = "1" ]; then echo "LEDs switched ON"; fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### ------ FUNCTION LEDbrightness FOR SETTING THE BRIGHTNESS OF THE LEDS IN front of the Fritz!Box ------ ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
LEDbrightness(){
# Get the a valid SID
getSID
# led_display=0 -> ON
# led_display=1 -> DELAYED ON (20200106: not really slower that option 0 - NOT USED)
# led_display=2 -> OFF
# Check if device supports LED dimming
json=$(wget -q -O - --post-data "xhr=1&sid=$SID&page=led" "http://$BoxIP/data.lua" | tr -d '"')
if grep -q 'canDim:1' <<< "$json"
then
# Extract LED state
display=$(grep -o 'ledDisplay:[[:digit:]]*' <<< "$json" | cut -d : -f 2)
[[ -z "$display" || "$display" -lt 0 || "$display" -gt 2 ]] && display=0
# Extract LED brightness
dim=$(grep -o 'dimValue:[[:digit:]]*' <<< "$json" | cut -d : -f 2)
[[ -z "$dim" || "$dim" -lt 1 || "$dim" -gt 3 ]] && dim=3
if [ "$option2" -eq 0 ]
then
display=2
else
display=0
dim=$option2
fi
wget -O /dev/null --post-data "sid=$SID&led_brightness=$dim&dimValue=$dim&led_display=$display&ledDisplay=$display&page=led&apply=" "http://$BoxIP/data.lua" 2>/dev/null
echo "Brightness set to $dim; LEDs switched $(if [ "$display" -eq 2 ]; then echo "OFF"; else echo "ON"; fi)"
else
echo "Brightness setting on this FritzBox not possible."
fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### --------- FUNCTION keyLockSwitch FOR ACTIVATING or DEACTIVATING the buttons on the Fritz!Box -------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
keyLockSwitch(){
# Get the a valid SID
getSID
wget -O - --post-data "sid=$SID&keylock_enabled=$option2&apply=" "http://$BoxIP/system/keylocker.lua" 2>/dev/null
if [ "$option2" = "0" ]; then echo "KeyLock NOT active"; fi
if [ "$option2" = "1" ]; then echo "KeyLock active"; fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------- FUNCTION SIGNAL STRENGTH change ---------------------------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
SignalStrengthChange(){
# Get the a valid SID
getSID
# Check for possible values for signal strength
# {"value":"1","text":"100 %"},{"value":"2","text":"50 %"},{"value":"3","text":"25 %"},{"value":"4","text":"12 %"},{"value":"5","text":"6 %"}
if [ "$option2" = "100" ]; then SIGNALStrengthlevel=1;
elif [ "$option2" = "50" ]; then SIGNALStrengthlevel=2;
elif [ "$option2" = "25" ]; then SIGNALStrengthlevel=3;
elif [ "$option2" = "12" ]; then SIGNALStrengthlevel=4;
elif [ "$option2" = "6" ]; then SIGNALStrengthlevel=5;
else DisplayArguments # No valid input given
fi
wget -O - --post-data "xhr=1&sid=$SID&page=chan&channelSelectMode=manual&autopowerlevel=$SIGNALStrengthlevel&apply=" "http://$BoxIP/data.lua" &>/dev/null
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------- FUNCTION WIREGUARD VPN connection change ------------------------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
WireguardVPNstate(){
# Get the a valid SID
getSID
connectionName="$option2"
if [ "$option3" != "0" ] && [ "$option3" != "1" ]; then echo "Add 0 for switching OFF or 1 for switching ON."
else
connectionState=$option3
if [ "$connectionState" = "1" ]; then connectionStateString="on";
elif [ "$connectionState" = "0" ]; then connectionStateString="off";
fi
# Get the connection ID
connectionID=$(wget -O - --post-data "xhr=1&sid=$SID&page=shareWireguard&xhrId=all" "http://$BoxIP/data.lua" 2>/dev/null | jq '.data.init.boxConnections | to_entries[] | select( .value.name == "'"$connectionName"'" ) | .key' | tr -d '"')
# Switch on/off the connection if the connection was found
if [ "$connectionID" != "" ]; then
wget -O - --post-data "xhr=1&sid=$SID&page=shareWireguard&$connectionID=$connectionStateString&active_$connectionID=$connectionState&apply=" "http://$BoxIP/data.lua" &>/dev/null
echo "$connectionName ($connectionID) successfuly switched $connectionStateString."
elif [ "$connectionID" == "" ]; then
echo "$connectionName not found."
fi
fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------------- FUNCTION get_filtered_clients - TR-064 Protocol --------------------------- ###
### -------------- Function to get total number of 2.4 Ghz, 5 Ghz, ethernet or all clients -------------- ###
### ----------------------------------------------------------------------------------------------------- ###
# Function for SOAP requests
soap_request() {
local location=$1
local service=$2
local action=$3
local body=$4
local FRITZBOX_URL="http://$BoxIP:49000"
local USERNAME=$BoxUSER
local PASSWORD=$BoxPW
curl -m 25 --anyauth -s -u "$USERNAME:$PASSWORD" \
-H 'Content-Type: text/xml; charset="utf-8"' \
-H "SOAPAction: \"$service#$action\"" \
-d "$body" \
"$FRITZBOX_URL$location"
}
get_ip_from_mac() {
local mac=$1
local show_ip=$2 # Parameter that indicates whether the IP address should be retrieved
# If the -withIP parameter is set, retrieve the IP address
if [ "$show_ip" == "-withIP" ]; then
local SOAP_BODY='<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:GetSpecificHostEntry xmlns:u="urn:dslforum-org:service:Hosts:1">
<NewMACAddress>'$mac'</NewMACAddress>
</u:GetSpecificHostEntry>
</s:Body>
</s:Envelope>'
# Use curl to send the SOAP request (replace this with your actual method)
local response=$(soap_request "/upnp/control/hosts" "urn:dslforum-org:service:Hosts:1" "GetSpecificHostEntry" "$SOAP_BODY")
local ip=$(echo "$response" | xmlstarlet sel -t -v "//NewIPAddress" 2>/dev/null)
echo "$ip"
else
echo "" # If -withIP is not set, leave the IP empty
fi
}
get_filtered_clients() {
local filter=$1
local show_ip=$2 # Parameter that indicates whether the IP address should be retrieved
# Retrieve the host list
local SOAP_BODY='<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:GetMeshListPath xmlns:u="urn:dslforum-org:service:Hosts:1" />
</s:Body>
</s:Envelope>'
local mesh_list_xml=$(soap_request "/upnp/control/hosts" "urn:dslforum-org:service:Hosts:1" "X_AVM-DE_GetMeshListPath" "$SOAP_BODY")
local mesh_list_path=$(echo "$mesh_list_xml" | xmlstarlet sel -t -v "//NewX_AVM-DE_MeshListPath")
if [[ -z "$mesh_list_path" ]]; then
echo "Error: Could not retrieve mesh list."
return 1
fi
# Retrieve the Security Port
location="/upnp/control/deviceinfo"
uri="urn:dslforum-org:service:DeviceInfo:1"
action="GetSecurityPort"
securityPort=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" -H 'Content-Type: text/xml; charset="utf-8"' -H "SoapAction:$uri#$action" -d "<?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:$action xmlns:u='$uri'></u:$action></s:Body></s:Envelope>" | grep NewSecurityPort | awk -F">" '{print $2}' | awk -F"<" '{print $1}')
# Retrieve the mesh list
local sid=$(echo "$mesh_list_path" | grep -o 'sid=[^&]*' | cut -d'=' -f2)
local mesh_url="https://$BoxIP:$securityPort/meshlist.lua?sid=$sid"
# echo "DEBUG: Retrieving the mesh list from: $mesh_url"
# Retrieve the mesh list
local mesh_list_json=$(curl -s -k -m 30 --anyauth -u "$BoxUSER:$BoxPW" "$mesh_url")
# Check if the response is HTML (e.g., an error page)
if echo "$mesh_list_json" | grep -iq "<html>"; then
echo "Error: Received HTML response (likely an authentication problem)."
return 1
fi
# Check if the response is valid JSON
if ! echo "$mesh_list_json" | jq empty 2>/dev/null; then
echo "Error: Retrieved JSON data is invalid."
echo "DEBUG: Raw data:"
echo "$mesh_list_json"
return 1
fi
# Clean the JSON data
mesh_list_json=$(echo "$mesh_list_json" | tr -d '\r' | sed 's/\\//g')
if [ -z "$mesh_list_json" ]; then
echo "Error: mesh_list_json is empty!"
return 1
fi
# Filtering the devices based on the specified filter
local clients=""
echo "DEBUG: Applying filter '$filter' to the mesh list..."
case "$filter" in
"2.4")
# Filter for 2.4 GHz (only WLAN devices)
clients=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "WLAN" and .current_channel_info?.primary_freq < 3000000) | {mac: .node_interfaces[].mac_address, name: .device_name, type: "WLAN_2G", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
;;
"5")
# Filter for 5 GHz (only WLAN devices)
clients=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "WLAN" and .current_channel_info?.primary_freq >= 5000000) | {mac: .node_interfaces[].mac_address, name: .device_name, type: "WLAN_5G", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
;;
"ETH")
# Filter for Ethernet (only LAN devices)
clients=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "LAN") | {mac: .node_interfaces[].mac_address, name: .device_name, type: "ETH", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
;;
"all")
# Clear clients variable
clients=""
# Filter for 2.4 GHz WLAN
clients+=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "WLAN" and .current_channel_info?.primary_freq < 3000000) | {mac: .node_interfaces[].mac_address, name: .device_name, type: "WLAN_2G", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
# Filter for 5 GHz WLAN
clients+=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "WLAN" and .current_channel_info?.primary_freq >= 5000000) | {mac: .node_interfaces[].mac_address, name: .device_name, type: "WLAN_5G", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
# Filter for Ethernet (LAN)
clients+=$(echo "$mesh_list_json" | jq -r '.nodes[] | select(.device_name != "fritz.repeater" and .device_name != "fritz.box") | select(.node_interfaces[] | .type == "LAN") | {mac: .node_interfaces[].mac_address, name: .device_name, type: "ETH", ip: .node_interfaces[].ip_address, status: (if (.node_interfaces[].node_links | length) > 0 then "ONLINE" else "OFFLINE" end)}')
;;
*)
echo "Invalid filter. Available options: 2.4, 5, ETH, all"
return 1
;;
esac
# Remove duplicate devices based on MAC address but display device names
unique_clients=$(echo "$clients" | jq -s 'map({mac, name, type, ip, status}) | unique_by(.mac)')
# echo "$unique_clients" > unique_clients_debug.json
# Loop over all clients and retrieve the IP only if -withIP is set
#
# OLD CODE which was making toubles on Cygwin or windows based shell envorinments
#
# for i in $(echo "$unique_clients" | jq -r '. | keys_unsorted | .[]'); do
# mac=$(echo "$unique_clients" | jq -r ".[$i].mac") # Get MAC address
# ip=$(get_ip_from_mac "$mac" "$show_ip") # Retrieve IP only if -withIP is set
# # Update the JSON with the IP address if it exists
# if [ -n "$ip" ]; then
# unique_clients=$(echo "$unique_clients" | jq ".[$i].ip = \"$ip\"")
# fi
# done
# Loop over all clients and retrieve the IP only if -withIP is set
for i in $(echo "$unique_clients" | jq -r '. | keys_unsorted | .[]'); do
# Hole die MAC-Adresse sicher mit --argjson
mac=$(echo "$unique_clients" | jq -r --argjson i "$i" '.[$i].mac')
# Get the IP-Address based on the MAC-Address
ip=$(get_ip_from_mac "$mac" "$show_ip")
# Update the JSON with the IP address if it exists with --arg
if [ -n "$ip" ]; then
unique_clients=$(echo "$unique_clients" | jq --argjson i "$i" --arg ip "$ip" '.[$i].ip = $ip')
fi
done
unique_clients=$(echo "$unique_clients" | jq 'sort_by(.type)')
# Count the filtered devices (only unique)
local num_clients=$(echo "$unique_clients" | jq length)
# Count the ONLINE and OFFLINE devices
local online_count=$(echo "$unique_clients" | jq '[.[] | select(.status == "ONLINE")] | length')
local offline_count=$(echo "$unique_clients" | jq '[.[] | select(.status == "OFFLINE")] | length')
# Output the total number and the online/offline count
echo
echo "Found devices: $num_clients"
echo "ONLINE: $online_count | OFFLINE: $offline_count"
echo
# Create the header line, matching the data
header="Type\tClient Name\tIP Address\tMAC Address\tStatus"
# Output the devices in a format suitable for `column` (with header)
(
echo -e "$header"
echo "$unique_clients" | jq -r '.[] | "\(.type)\t\(.name)\t\(.ip // "No IP")\t\(.mac)\t\(.status)"'
) | column -t -s $'\t'
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------------------ FUNCTION to readout misc from data.lua ------------------------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
LUAmisc(){
# Get the a valid SID
getSID
overview=$(wget -O - --post-data "xhr=1&sid=$SID&page=overview&xhrId=first&noMenuRef=1" "http://$BoxIP/data.lua" 2>/dev/null)
# This could be extended in the future to also get other information
if [ "$option2" == "totalConnectionsWLAN" ]; then
# - not working on all machines - maybe linked to different jq versions - Works with 1.7 but not with 1.5 and 1.6
# totalConnectionsWLAN=$(wget -O - --post-data "xhr=1&sid=$SID&page=overview&xhrId=first&noMenuRef=1" "http://$BoxIP/data.lua" 2>/dev/null | jq '.data.net.devices.[] | select(.type=="wlan" ) | length' | wc -l)
totalConnectionsWLAN2G=$(grep -ow '"desc":"2,4 GHz"' <<< $overview | wc -l)
totalConnectionsWLAN5G=$(grep -ow '"desc":"5 GHz"' <<< $overview | wc -l)
totalConnectionsWLANguest=$(grep -ow '"guest":true,"online"' <<< $overview | wc -l)
echo "2,4G WLAN: $totalConnectionsWLAN2G"
echo "5G WLAN: $totalConnectionsWLAN5G"
echo "Guest WLAN: $totalConnectionsWLANguest"
elif [ "$option2" == "totalConnectionsWLAN2G" ]; then
totalConnectionsWLAN2G=$(grep -ow '"desc":"2,4 GHz"' <<< $overview | wc -l)
echo $totalConnectionsWLAN2G
elif [ "$option2" == "totalConnectionsWLAN5G" ]; then
totalConnectionsWLAN5G=$(grep -ow '"desc":"5 GHz"' <<< $overview | wc -l)
echo $totalConnectionsWLAN5G
elif [ "$option2" == "totalConnectionsWLANguest" ]; then
totalConnectionsWLANguest=$(grep -ow '"guest":true,"online"' <<< $overview | wc -l)
echo $totalConnectionsWLANguest
elif [ "$option2" == "totalConnectionsLAN" ]; then
# - not working on all machines - maybe linked to different jq versions - Works with 1.7 but not with 1.5 and 1.6
# totalConnectionsLAN=$(wget -O - --post-data "xhr=1&sid=$SID&page=overview&xhrId=first&noMenuRef=1" "http://$BoxIP/data.lua" 2>/dev/null | jq '.data.net.devices.[] | select(.type=="lan" ) | length' | wc -l)
totalConnectionsLAN=$(echo $overview | grep -ow '"type":"lan"' | wc -l)
echo $totalConnectionsLAN
fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### --------------------------- FUNCTION to readout event log from query.lua ---------------------------- ###
### ----------------------------- Here the TR-064 protocol cannot be used. ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
### ---------------------------------------- AHA-HTTP-Interface ----------------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
LUAmisc_Log(){
# Get the a valid SID
getSID
# This could be extended in the future to also get other information
if [ "$option2" == "ReadLog" ]; then
# Readout the event log of the Fritz!Box
log=$(curl -k -s -G "http://$BoxIP/query.lua" \
-d "mq_log=logger:status/log" \
-d "sid=$SID" | \
jq -r '.mq_log[] | .[0]' | \
tail -r)
echo "Event Log of FritzBox:"
echo "$log"
elif [ "$option2" == "ResetLog" ]; then
reset=$(curl -s "http://$BoxIP/data.lua" --compressed --data "xhr=1&sid=$SID&lang=de&page=log&xhrId=del&del=1&useajax=1&no_sidrenew=")
if [[ "$reset" == *"Ereignisse wurden gelöscht"* ]]; then
echo "The event log was successfully resetted."
else
echo "The event log was not resetted."
fi
fi
# Logout the "used" SID
wget -O - "http://$BoxIP/home/home.lua?sid=$SID&logout=1" &>/dev/null
}
### ----------------------------------------------------------------------------------------------------- ###
### -------------------------------- FUNCTION readout - TR-064 Protocol --------------------------------- ###
### -- General function for sending the SOAP request via TR-064 Protocol - called from other functions -- ###
### ----------------------------------------------------------------------------------------------------- ###
readout() {
# Before performing the readout, check if the action is available
if verify_action_availability "$location" "$uri" "$action"; then
curlOutput1=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" -H 'Content-Type: text/xml; charset="utf-8"' -H "SoapAction:$uri#$action" -d "<?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:$action xmlns:u='$uri'></u:$action></s:Body></s:Envelope>" | grep "<New" | awk -F"</" '{print $1}' |sed -En "s/<(.*)>(.*)/\1 \2/p")
echo "$curlOutput1"
else
echo "Action '$action' canot be executed, because it seems to be not available."
echo "You can try with "fritzBoxShell.sh ACTIONS" to get a list of available services and actions."
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------------ FUNCTION check if action available - TR-064 Protocol ----------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
# Function to verify if an action is available
verify_action_availability() {
local location=$1
local uri=$2
local action=$3
# Retrieve tr64desc.xml
tr64desc=$(curl -s "http://$BoxIP:49000/tr64desc.xml")
if [ -z "$tr64desc" ]; then
echo "Error: Could not retrieve tr64desc.xml."
return 1
fi
# Temporary file for the XML data
temp_file=$(mktemp)
echo "$tr64desc" > "$temp_file"
# Find the SCPD URL
scpd_url=$(xmlstarlet sel -t -m "//*[local-name()='service']" \
-if "./*[local-name()='controlURL'][text()='$location']" \
-v "./*[local-name()='SCPDURL']" -n "$temp_file" | head -n 1)
rm "$temp_file"
if [ -z "$scpd_url" ]; then
echo "Error: No SCPD URL found for the provided controlURL ($location)."
return 1
fi
# Retrieve SCPD data
scpd_data=$(curl -s "http://$BoxIP:49000$scpd_url")
if [ -z "$scpd_data" ]; then
echo "Error: SCPD data could not be retrieved for the URL ($scpd_url)."
return 1
fi
# Temporary file for the SCPD data
scpd_file=$(mktemp)
echo "$scpd_data" > "$scpd_file"
# Check if the action is available
available_action=$(xmlstarlet sel -t -m "//*[local-name()='action']" \
-if "./*[local-name()='name'][text()='$action']" \
-v "./*[local-name()='name']" -n "$scpd_file" | head -n 1)
rm "$scpd_file"
if [ -n "$available_action" ]; then
# echo "Action '$action' is available for the service '$uri'."
return 0
else
echo "Error: Action '$action' is not available for the service '$uri'."
return 1
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------------------ FUNCTION UPNPMetaData - TR-064 Protocol ------------------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
UPNPMetaData(){
location="/tr64desc.xml"
if [ "$option2" = "STATE" ]; then curl -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location"
else curl -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" >"$DIRECTORY/$option2"
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------------------ FUNCTION IGDMetaData - TR-064 Protocol ------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
IGDMetaData(){
location="/igddesc.xml"
if [ "$option2" = "STATE" ]; then curl -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location"
else curl -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" >"$DIRECTORY/$option2"
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ---- FUNCTION getWLANGUESTNum returns WLAN-Guest service number (if available) - TR-064 Protocol ---- ###
### ----------------------------------------------------------------------------------------------------- ###
getWLANGUESTNum() {
for wlanNum in {2..4}; do
location="/upnp/control/wlanconfig$wlanNum"
uri="urn:dslforum-org:service:WLANConfiguration:$wlanNum"
action="X_AVM-DE_GetWLANExtInfo"
# Check availability of the defined action
if verify_action_availability "$location" "$uri" "$action"; then
echo "Starte readout..."
# Hier die tatsächliche Funktion aufrufen, wenn die Aktion verfügbar ist
wlanType=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$location" -H 'Content-Type: text/xml; charset="utf-8"' -H "SoapAction:$uri#$action" -d "<?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:$action xmlns:u='$uri'></u:$action></s:Body></s:Envelope>" | grep NewX_AVM-DE_APType | awk -F">" '{print $2}' | awk -F"<" '{print $1}')
if [ "$wlanType" = "guest" ]; then
echo $wlanNum
break
fi
else
echo "Action '$action' canot be executed, because it seems to be not available."
echo "You can try with "fritzBoxShell.sh ACTIONS" to get a list of available services and actions."
fi
done
}
### ----------------------------------------------------------------------------------------------------- ###
### ----------------------- FUNCTION WLANstatistics for 2.4 Ghz - TR-064 Protocol ----------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
WLANstatistics() {
location="/upnp/control/wlanconfig1"
uri="urn:dslforum-org:service:WLANConfiguration:1"
action='GetStatistics'
readout
action='GetTotalAssociations'
readout
action='GetInfo'
readout
echo "NewGHz 2.4"
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------ FUNCTION WLANstatistics for 5 Ghz - Channel 1 - TR-064 Protocol ------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
WLAN5statistics() {
location="/upnp/control/wlanconfig2"
uri="urn:dslforum-org:service:WLANConfiguration:2"
action='GetStatistics'
readout
action='GetTotalAssociations'
readout
action='GetInfo'
readout
echo "NewGHz 5"
}
### ----------------------------------------------------------------------------------------------------- ###
### ------------------ FUNCTION WLANstatistics for 5 Ghz - Channel 2 - TR-064 Protocol ------------------ ###
### ----------------------------------------------------------------------------------------------------- ###
WLAN5statistics_ch2() {
location="/upnp/control/wlanconfig3"
uri="urn:dslforum-org:service:WLANConfiguration:3"
action='GetStatistics'
readout
action='GetTotalAssociations'
readout
action='GetInfo'
readout
echo "NewGHz 5"
}
### ----------------------------------------------------------------------------------------------------- ###
### -------------------- FUNCTION WLANstatistics for Guest Network - TR-064 Protocol -------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
WLANGUESTstatistics() {
wlanNum=$(getWLANGUESTNum)
if [ -z "$wlanNum" ]; then
echo "Guest Network not available"
else
location="/upnp/control/wlanconfig$wlanNum"
uri="urn:dslforum-org:service:WLANConfiguration:$wlanNum"
action='GetStatistics'
readout
action='GetTotalAssociations'
readout
action='GetInfo'
readout
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### -------------------------------- FUNCTION LANcount - TR-064 Protocol -------------------------------- ###
### ----------------------------------------------------------------------------------------------------- ###
LANcount() {
# TR-064 service information
SERVICE="urn:dslforum-org:service:Hosts:1"
CONTROL_URL="/upnp/control/hosts"
if verify_action_availability "$CONTROL_URL" "$SERVICE" "GetHostNumberOfEntries"; then
# Do nothing but continue script execution
:
else
echo "Action '$action' cannot be executed, because it seems to be not available."
echo "You can try with 'fritzBoxShell.sh ACTIONS' to get a list of available services and actions."
return
fi
total_hosts=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$CONTROL_URL" \
-H 'Content-Type: text/xml; charset="utf-8"' \
-H "SoapAction:$SERVICE#GetHostNumberOfEntries" \
-d "<?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:GetHostNumberOfEntries xmlns:u='$SERVICE'></u:GetHostNumberOfEntries>
</s:Body>
</s:Envelope>" | grep NewHostNumberOfEntries | awk -F">" '{print $2}' | awk -F"<" '{print $1}')
# Check if total_hosts has a valid numerical value
if [[ "$total_hosts" =~ ^[0-9]+$ ]]; then
if [ "$total_hosts" -gt 0 ]; then
# Maximal parallel processes
max_parallel=10
pids=() # Array for process IDs
# Loop through all hosts and query them in parallel
for ((i=0; i<total_hosts; i++)); do
# Query the interface for each device
(
interface_type=$(curl -s -k -m 5 --anyauth -u "$BoxUSER:$BoxPW" "http://$BoxIP:49000$CONTROL_URL" \
-H "Content-Type: text/xml; charset=\"utf-8\"" \
-H "SoapAction:$SERVICE#GetGenericHostEntry" \
-d "<?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:GetGenericHostEntry xmlns:u=\"$SERVICE\"><NewIndex>$i</NewIndex></u:GetGenericHostEntry>
</s:Body>
</s:Envelope>" | grep NewInterfaceType | awk -F">" '{print $2}' | awk -F"<" '{print $1}')
if [[ "$interface_type" == "Ethernet" ]]; then
# Count Ethernet connections
echo 1 >> /tmp/ethernet_count.tmp
fi
) &
# Store process IDs
pids+=($!)
# If the number of background processes reaches the limit, we wait for the first process
if (( ${#pids[@]} >= max_parallel )); then
# Wait for one of the running processes
wait "${pids[0]}"
# Remove the first process from the array
pids=("${pids[@]:1}")
fi
done
wait
# Sum of Ethernet connections
if [[ -s /tmp/ethernet_count.tmp ]]; then
ethernet_count=$(wc -l < /tmp/ethernet_count.tmp | awk '{print $1}')
else
ethernet_count=0
fi
# Print result
echo "NumberOfEthernetConnections: $ethernet_count"
# Delete temporary file if it exists
if [[ -e /tmp/ethernet_count.tmp ]]; then
rm /tmp/ethernet_count.tmp
fi
else
echo "NumberOfEthernetConnections: 0"
fi
else
echo "Error: Unable to determine the total number of hosts. Check your connection or credentials."
return
fi
}
### ----------------------------------------------------------------------------------------------------- ###
### ----------------------------- FUNCTION TR064_actions - TR-064 Protocol ------------------------------ ###
### ---- This function allows to go through all available services and actions on your Fritz device ----- ###
### ---------- After selecting the service and action you can launch teh according SOAP call ------------ ###
### ----------------------------------------------------------------------------------------------------- ###
TR064_actions() {
# URL to the XML document
XML_URL="http://$BoxIP:49000/tr64desc.xml"
# Retrieve XML data with curl
xml_data=$(curl -s "$XML_URL")
# Save the XML data to a temporary file
temp_file=$(mktemp)
echo "$xml_data" > "$temp_file"