forked from greearb/lanforge-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeviceConfig.py
More file actions
executable file
·1871 lines (1640 loc) · 83.3 KB
/
DeviceConfig.py
File metadata and controls
executable file
·1871 lines (1640 loc) · 83.3 KB
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
#!/usr/bin/env python3
"""
DeviceConfig: A script for managing device configurations and network profiles for ADB devices and laptops.
This script allows you to interact with both Android and Laptop devices, configure them for Wi-Fi connectivity,
manage groups of devices, and monitor their connections. It provides various features like creating Wi-Fi profiles,
configuring devices, and creating or managing groups using a CSV file as the database.
Mainly we use these script classes in other script that uses Groups and Profiles
Classes:
- ADB_DEVICES: Manages Android devices using ADB commands.
- LAPTOPS: Manages Linux, Windows, and macOS laptops using CLI commands.
- DeviceConfig: The main class that integrates both Android and Laptop, allowing configuration,
mapping, profile management, and monitoring.
Methods (Class ADB_DEVICES):
- stop_app: Stops a specified app on the ADB devices.
- set_wifi_state: Enables or disables Wi-Fi on ADB devices.
- forget_all_networks: Clears Wi-Fi profiles on ADB devices.
- configure_wifi: Configures Wi-Fi settings (SSID, password, encryption) on ADB devices.
- reboot_android: Reboots the ADB devices.
- get_devices: Fetches the list of connected ADB devices.
Methods (Class LAPTOPS):
- post_data: Sends a POST request to the Lanforge server with the given URL and data.
- get_encoding: Maps encryption types to numeric values used in Wi-Fi configuration for laptops.
- rm_station: Removes a station.
- add_station: Adds a station to a laptop (Linux/Apple/Windows) and connects it to Wi-Fi.
- set_wifi_extra: Configures additional Wi-Fi parameters for enterprise connections (Linux laptops).
- set_port: Sets network port settings for laptops.
- reboot_laptop: Reboots the laptops.
- disconnect_wifi: Disconnects Wi-Fi on the laptops.
- get_devices: Fetches the list of connected laptops from the Lanforge server.
- get_station_name: Fetches the station name for a laptop.
Methods (Class DeviceConfig):
- get_all_devices: Retrieves all ADB and laptop devices from the respective classes.
- map_all_devices: Maps devices by serial or hostname for further usage.
- read_groups_file: Reads a CSV file containing device group information.
- get_all_available_devices: Retrieves all devices that have not been added to a group.
- take_input: Takes user input to manage groups (add, remove, or edit groups).
- device_csv_file: Creates a CSV file with device and performance information (if it does not exist).
- update_device_csv: Updates a CSV file with device test results (ping, bandwidth, etc.).
- update_groups_file: Updates the groups file with the addition or removal of devices.
- display_groups: Displays the list of device groups in a tabular format.
- initiate_group: Initializes device group mapping from a CSV file.
- get_groups_devices: Retrieves devices belonging to selected groups.
- create_profile: Creates a Wi-Fi profile configuration based on input.
- create_profile_file: Writes the Wi-Fi profile configuration to a CSV file.
- display_profiles: Displays Wi-Fi profiles in a table.
- get_profiles: Fetches Wi-Fi profiles from the CSV file.
- connectivity: Configures selected devices to connect to Wi-Fi profiles or reboots/disconnects them.
- monitor_connection: Monitors the connection status of devices to ensure they are connected to the desired network.
CLI Arguments:
--lanforge_ip: IP address of the Lanforge server (default: 'localhost').
--create_file: Flag to create a new group file.
--file_name: Name of the CSV file for managing groups.
--create_group: Flag to create a new group in the group file.
--get_groups: Flag to display all available groups.
--remove_group: Flag to remove a group from the group file.
--update_group: Flag to update a group in the group file.
--profile_config: Creates Wi-Fi profiles
--delete_profiles: Deletes specified Wi-Fi profiles.
--create_profile: Flag to create a Wi-Fi profile file.
--connect_profile: Flag to connect devices to a specified Wi-Fi profile.
--create_csv: Flag to create a CSV file
Usage:
python DeviceConfig.py --lanforge_ip <LANFORGE_IP> --create_group --file_name group_file
python DeviceConfig.py --lanforge_ip <LANFORGE_IP> --connect_profile --profile_config "<profile details>"
"""
import re
import sys
import os
import importlib
import argparse
import time
import logging
import pandas as pd
import asyncio
import csv
import requests
from collections import defaultdict
sys.path.append(os.path.join(os.path.abspath(__file__ + "../../../")))
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(name)s %(levelname)s: %(message)s',
stream=sys.stdout
)
class ADB_DEVICES(Realm):
def __init__(self, lanforge_ip=None,
port=8080,
_debug_on=False,
):
super().__init__(lfclient_host=lanforge_ip,
debug_=_debug_on)
self.lanforge_ip = lanforge_ip
self.port = port
# adb post url
self.adb_post_url = '/cli-json/adb/'
# adb get url
self.adb_url = '/adb/'
# stop app
async def stop_app(self, port_list=None):
port_list = [] if port_list is None else port_list
if (port_list == []):
logger.info('Device list is empty')
return
data_list = []
command = 'shell am force-stop com.candela.wecan'
for port_data in port_list:
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': command
}
data_list.append(data)
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.json_post, self.adb_post_url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# toggle wifi
def set_wifi_state(self, port_list=None, state='enable'):
port_list = [] if port_list is None else port_list
if (port_list == []):
logger.info('Port list is empty')
return
state = state.lower()
if (state != 'enable' and state != 'disable'):
logger.warning('State argument should be either enable or disable')
return
command = 'shell svc wifi {}'.format(state)
data_list = []
for port_data in port_list:
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': command
}
data_list.append(data)
loop = asyncio.get_event_loop()
[loop.run_in_executor(None, self.json_post, self.adb_post_url, data) for data in data_list]
# Forget Networks
async def forget_all_networks(self, port_list=None):
port_list = [] if port_list is None else port_list
# Added stop app in prior to clearing wifi profiles because in build 5.5.2 we have issue with clearing profiles, so the app is still running with the existing ssid.
logger.info("STOPPING APP ANDROID")
await self.stop_app(port_list=port_list)
logger.info("FORGET ALL NETWORKS ANDROID")
if (port_list == []):
logger.info('Port list is empty')
return
url = 'cli-json/clear_wifi_profiles'
data_list = []
for port_data in port_list:
data = {
'shelf': 1,
'resource': port_data["shelf"],
'id': port_data["serial"],
'type': 'adb'
}
data_list.append(data)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.json_post, url, data) for data in data_list]
await asyncio.gather(*tasks)
# Configure Wifi ADB
async def configure_wifi(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("CONFIGURE ANDROIDS")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
data_list_1 = []
for port_data in port_list:
curr_ssid, curr_passwd, curr_encryption, curr_eap_method, curr_eap_identity, server_ip = port_data["ssid"], port_data[
"passwd"], port_data["enc"], port_data["eap_method"], port_data["eap_identity"], port_data["server_ip"]
username = port_data["user-name"]
# adding enable wifi option for android clients as a prerequisite step by-default
command = 'shell svc wifi enable'
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': command
}
data_list_1.append(data)
if (username is None):
# logger.warning('The device with serial {} not found'.format(serial))
username = \
self.get('http://{}:{}/adb/1/1/{}'.format(self.lanforge_ip, self.port, port_data["serial"])).json()['devices'][
'user-name']
# check if the encryption is personal
# if the encryption is enterprise
if port_data["ieee80211"]:
if curr_encryption == "wpa_enterprise":
curr_encryption = "wpa-ent"
if curr_encryption == "wpa2_enterprise":
curr_encryption = "wpa2-ent"
if curr_encryption == "wpa3_enterprise":
curr_encryption = "wpa3-ent"
adb_cmd = (
'shell am start -n com.candela.wecan/com.candela.wecan.StartupActivity '
'--es auto_start 1 '
'--es username {} '
'--es serverip {} '
'--es ssid \\"{}\\" '
'--es password \\"{}\\" '
'--es encryption {} '
'--es eap_method {} '
'--es eap_user {} '
'--es eap_passwd {} '
'--es app_flags 1 '
'--es auto_wifi 1'.format(
username, server_ip, curr_ssid, curr_passwd, curr_encryption,
curr_eap_method, curr_eap_identity, curr_passwd
)
)
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': adb_cmd
}
else:
adb_cmd = (
'shell am start -n com.candela.wecan/com.candela.wecan.StartupActivity '
'--es auto_start 1 '
'--es username {} '
'--es serverip {} '
'--es ssid \\"{}\\" '
'--es password \\"{}\\" '
'--es encryption {} '
'--es auto_wifi 1'.format(
username, server_ip, curr_ssid, curr_passwd, curr_encryption
)
)
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': adb_cmd
}
data_list.append(data)
# execution for enabling wifi
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.json_post, self.adb_post_url, data) for data in data_list_1]
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.json_post, self.adb_post_url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# Reboot ADB Devices
async def reboot_android(self, port_list=None, state='enable'):
port_list = [] if port_list is None else port_list
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
data = {
'shelf': 1,
'resource': port_data["shelf"],
'adb_id': port_data["serial"],
'key': 8,
'adb_cmd': "reboot"
}
data_list.append(data)
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.json_post, self.adb_post_url, data) for data in data_list]
await asyncio.gather(*tasks)
# fetch all android devices
def get_devices(self):
# fetching all devices from interop tab
interop_tab_data = self.json_get(self.adb_url)["devices"]
devices_data = []
# checking if there is only one device in interop tab. The value would be a dictionary instead of a list
if (type(interop_tab_data) is dict):
device = {}
name = interop_tab_data['name']
if (str(interop_tab_data['phantom']) == "true" or str(interop_tab_data['phantom']) == "True"):
logger.warning(
'{} is in phantom state. Please make sure debugging is enabled in developer settings.'.format(name))
else:
_, clustered_res, serial = name.split('.')
# parameters for adb post request
try:
shelf, resource = interop_tab_data['resource-id'].split('.')
except Exception:
# logger.warning('Resource id is missing for the device {} therefore skipping the device from usage'.format(name))
shelf, resource = '', ''
device["serial"] = serial
device["shelf"] = clustered_res
device["eid"] = interop_tab_data['resource-id']
device["resource"] = resource
device["os"] = interop_tab_data['device-type']
device["user-name"] = interop_tab_data['user-name']
device['type'] = 'adb'
devices_data.append(device)
else:
for device_data in interop_tab_data:
device = {}
for name, data in device_data.items():
if (str(data['phantom']) == "true" or str(data['phantom']) == "True"):
logger.warning(
'{} is in phantom state. Please make sure debugging is enabled in developer settings.'.format(
name))
continue
_, clustered_res, serial = name.split('.')
try:
shelf, resource = data['resource-id'].split('.')
except Exception:
# logger.warning('Resource id is missing for the device {} therefore skipping the device from usage'.format(name))
_, resource = '', ''
device["serial"] = serial
device["shelf"] = clustered_res
device["eid"] = data['resource-id']
device["resource"] = resource
device["os"] = data["device-type"]
device["user-name"] = data["user-name"]
device['type'] = 'adb'
devices_data.append(device)
return (devices_data)
def get_serial_from_port(self, port_list=None):
if (port_list == []):
logger.info('Androids list is empty')
return
devices_data = []
url = 'http://{}:{}/adb/'.format(self.lanforge_ip, self.port)
resource_response = requests.get(url)
android_devices = resource_response.json()['devices']
# checking if there is only one device in interop tab. The value would be a dictionary instead of a list
if (type(android_devices) is dict):
for port_id in port_list:
shelf, resource, port = port_id.split('.')
resource_id = '{}.{}'.format(shelf, resource)
device_name = android_devices['name']
if (resource_id == android_devices['resource-id']):
device_serial = device_name.split('.')[2]
devices_data.append((shelf, resource, device_serial))
break
else:
for port_id in port_list:
shelf, resource, port = port_id.split('.')
resource_id = '{}.{}'.format(shelf, resource)
for android_device in android_devices:
device_name, device_data = list(android_device.keys())[0], list(android_device.values())[0]
if (resource_id == device_data['resource-id']):
device_serial = device_name.split('.')[2]
devices_data.append((shelf, resource, device_serial))
continue
return (devices_data)
class LAPTOPS(Realm):
def __init__(self, lanforge_ip=None,
port=8080,
_debug_on=False,
):
super().__init__(lfclient_host=lanforge_ip,
debug_=_debug_on)
self.lanforge_ip = lanforge_ip
self.port = port
def post_data(self, url, data):
try:
logger.info(data)
requests.post(url, json=data)
# response.raise_for_status() # Raise an HTTPError for bad responses
except Exception as e:
logger.error(e)
logger.error('Request failed for port {}'.format(data['port']))
# method to get the station name from port manager
# set encoding value
def get_encoding(self, obj):
encryption = obj.get("enc")
logger.info("SET ENCODING FOR LAPTOP")
enc = 0
if (encryption == 'open'):
enc = 0
elif (encryption == "owe"):
enc = 562949953421312
elif (encryption == 'wpa_personal' or encryption == 'psk' or encryption == 'wpa'):
enc = 16
elif (encryption == "wpa2_personal" or encryption == 'psk2' or encryption == 'wpa2'):
enc = 1024
elif (encryption == "wpa3_personal" or encryption == 'psk3' or encryption == 'wpa3'):
enc = 1099511627776
elif (encryption == "wpa_enterprise"):
enc = 33554448
elif (encryption == "wpa2_enterprise"):
enc = 33555456
elif (encryption == "wpa3_enterprise"):
enc = 1099545182208
elif (encryption == "owe_advanced"):
enc = 564049498603520
if encryption == "wpa_enterprise" or encryption == "wpa2_enterprise" or encryption == "wpa3_enterprise" or encryption == "owe_advanced":
if obj.get("ieee80211u"):
enc = enc + 131072
if obj.get("enable_pkc"):
enc = enc + 67108864
if obj.get("bss_transition"):
enc = enc + 8796093022208
if obj.get("power_save"):
enc = enc + 34359738368
if obj.get("disable_ofdma"):
enc = enc + 35184372088832
if obj.get("roam_ft_ds"):
enc = enc + 140737488355328
return enc
# remove station
# NOTE this is only for Linux Laptops
async def rm_station(self, port_list=None):
port_list = [] if port_list is None else port_list
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
if ('Lin' == port_data['os']):
shelf, resource, sta_name = port_data['shelf'], port_data['resource'], port_data['sta_name']
logger.info(f"REMOVING Wifi Interface for LAPTOP {shelf}.{resource}.{sta_name}")
data = {
'shelf': shelf,
'resource': resource,
'port': sta_name
}
data_list.append(data)
url = 'http://{}:{}/cli-json/rm_vlan'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
time.sleep(2)
# add station
async def add_station(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("ADD STATION LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
sta_name = port_data['sta_name']
os = port_data['os']
curr_ssid = port_data["ssid"]
curr_passwd = port_data["passwd"]
curr_enc = self.get_encoding(port_data)
enterprise_status = port_data["ieee80211"]
enable_80211w = port_data["ieee80211w"]
if (os in ['Apple', 'Lin']):
if enterprise_status:
data = {
'shelf': shelf,
'resource': resource,
'radio': 'wiphy0',
'sta_name': sta_name,
'flags': curr_enc,
'ssid': curr_ssid,
'mac': 'xx:xx:xx:*:*:xx',
"ieee80211w": enable_80211w,
}
else:
data = {
'shelf': shelf,
'resource': resource,
'radio': 'wiphy0',
'sta_name': sta_name,
'flags': curr_enc,
'ssid': curr_ssid,
'mac': 'xx:xx:xx:*:*:xx',
'key': curr_passwd,
"ieee80211w": 1,
}
else:
if enterprise_status:
data = {
'shelf': shelf,
'resource': resource,
'radio': 'wiphy0',
'sta_name': sta_name,
'flags': curr_enc,
'ssid': curr_ssid,
"ieee80211w": enable_80211w,
}
else:
data = {
'shelf': shelf,
'resource': resource,
'radio': 'wiphy0',
'sta_name': sta_name,
'flags': curr_enc,
'ssid': curr_ssid,
'key': curr_passwd,
"ieee80211w": 1,
}
data_list.append(data)
url = 'http://{}:{}/cli-json/add_sta'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
results = await asyncio.gather(*tasks)
logger.info(results)
time.sleep(2)
# Set Wifi Extra
async def set_wifi_extra(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("SET WIFI EXTRA LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
os = port_data['os']
curr_passwd = port_data["passwd"]
enterprise_status = port_data["ieee80211"]
key_management = port_data["key_management"]
pairwise = port_data["pairwise"]
eap_method = port_data["eap_method"]
eap_identity = port_data["eap_identity"]
private_key = port_data["private_key"]
ca_cert = port_data["ca_cert"]
client_cert = port_data["client_cert"]
pk_passwd = port_data["pk_passwd"]
pac_file = port_data["pac_file"]
if eap_method == "EAP-TTLS":
eap_method = "TTLS"
if eap_method == "EAP-TLS":
eap_method = "TLS"
if eap_method == "EAP-PEAP":
eap_method = "PEAP"
if eap_method == "EAP-PEAP":
eap_method = "PEAP"
if (enterprise_status and os == 'Lin'):
data = {
'shelf': shelf,
'resource': resource,
"port": "wlan0",
"key_mgmt": key_management,
"pairwise": pairwise,
"group": pairwise,
"eap": eap_method,
"identity": eap_identity,
"password": curr_passwd,
"private_key": private_key,
"ca_cert": ca_cert,
"client_cert": client_cert,
"pk_passwd": pk_passwd,
"pac_file": pac_file
}
data_list.append(data)
url = 'http://{}:{}/cli-json/set_wifi_extra'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
if len(data_list) < 1:
logger.info("No devices for set wifi extra")
return
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
async def set_port_1(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("SET PORT LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
port = port_data['sta_name']
os = port_data['os']
if (os == 'Lin'):
data = {
'shelf': shelf,
'resource': resource,
'port': port,
'current_flags': 0,
'interest': 8388610,
'mac': 'xx:xx:xx:*:*:xx'
}
else:
data = {
'shelf': shelf,
'resource': resource,
'port': port,
"report_timer": 1,
'current_flags': 0,
'interest': 92291074,
}
data_list.append(data)
url = 'http://{}:{}/cli-json/set_port'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# set port (enable DHCP)
async def set_port(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("SET PORT LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
port = port_data['sta_name']
os = port_data['os']
if (os == 'Lin'):
data = {
'shelf': shelf,
'resource': resource,
'port': port,
"report_timer": 1,
'current_flags': 2147483648,
'interest': 92291074,
'mac': 'xx:xx:xx:*:*:xx'
}
else:
data = {
'shelf': shelf,
'resource': resource,
'port': port,
"report_timer": 1,
'current_flags': 2147483648,
'interest': 92291074,
}
data_list.append(data)
url = 'http://{}:{}/cli-json/set_port'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# Reboot Laptops
async def reboot_laptop(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("REBOOT LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
data = {
'shelf': shelf,
'resource': resource
}
data_list.append(data)
url = 'http://{}:{}/cli-json/reboot_os'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# Disconnect Wifi Laptops
async def disconnect_wifi(self, port_list=None):
port_list = [] if port_list is None else port_list
logger.info("SET PORT LAPTOP")
if (port_list == []):
logger.info('Port list is empty')
return
data_list = []
for port_data in port_list:
shelf = port_data['shelf']
resource = port_data['resource']
port = port_data['sta_name']
os = port_data['os']
if (os == 'Lin'):
data = {
'shelf': shelf,
'resource': resource,
'port': port,
'current_flags': 1,
'interest': 8388610,
'mac': 'xx:xx:xx:*:*:xx'
}
else:
data = {
'shelf': shelf,
'resource': resource,
'port': port,
"report_timer": 1,
'current_flags': 1,
'interest': 8388608,
}
data_list.append(data)
url = 'http://{}:{}/cli-json/set_port'.format(self.lanforge_ip, self.port)
logger.info(f"DATA LIST: {data_list}")
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(None, self.post_data, url, data) for data in data_list]
# Use asyncio.gather to await the completion of all tasks
await asyncio.gather(*tasks)
# Get all laptops devices
def get_devices(self):
# fetching all devices from Resource Manager tab
response = self.json_get("/resource/all")
resources = response['resources']
# if there are no resources except LANforge in resource manager tab
if (type(resources) is dict):
return ([])
resources_list = []
for resource_data in resources:
port, resource = list(resource_data.keys())[0], list(resource_data.values())[0]
# filtering LANforges from resources
if (resource['ct-kernel']):
continue
# filtering Androids from resources
if (resource['user'] != ''):
continue
# filtering phantom resources
if (resource['phantom']):
logger.info('The laptop on port {} is in phantom state.'.format(port))
continue
shelf, resource_id = port.split('.')
hostname = resource_data[port]['hostname']
sta_details = self.get_station_name(shelf=shelf, resource=resource_id)
if not sta_details["radio_up"]:
logger.info('The laptop on port {} has no wiphy port available.'.format(port))
continue
hw_version = resource['hw version']
# fetching data for Windows
if ('Win' in hw_version):
resources_list.append({
'os': 'Win',
'shelf': shelf,
'resource': resource_id,
'sta_name': sta_details['station_name'],
'sta_down': sta_details['sta_down'],
'hostname': hostname,
'type': 'laptop',
'report_timer': 1500,
'current_flags': 2147483648,
'interest': 16384
})
# fetching data for Linux
elif ('Lin' in hw_version):
resources_list.append({
'os': 'Lin',
'shelf': shelf,
'resource': resource_id,
'sta_name': sta_details['station_name'] if sta_details['station_name'] else "sta0",
'sta_down': sta_details['sta_down'] if sta_details['sta_down'] is not None else True,
'hostname': hostname,
'type': 'laptop',
'current_flags': 2147483648,
'interest': 16384
})
# fetching data for Mac
elif ('Apple' in hw_version and resource['device type'] != 'IOS'):
resources_list.append({
'os': 'Apple',
'shelf': shelf,
'resource': resource_id,
'sta_name': sta_details['station_name'],
'sta_down': sta_details['sta_down'],
'hostname': hostname,
'type': 'laptop',
'current_flags': 2147483648,
'interest': 16384
})
return (resources_list)
# Get laptops station names
def get_station_name(self, shelf, resource):
# shelf=1
# resource=503
url = '/ports/{}/{}/?fields=parent dev,phantom,down,alias'.format(shelf, resource)
station_response = self.json_get(url)
wiphy_non_phantom_found = False
if ('interfaces' in station_response.keys()):
stations = station_response['interfaces']
for station in stations:
station_name, station_details = list(station.keys())[0], list(station.values())[0]
if (station_details['parent dev'] != '' and not station_details['phantom']):
wiphy_non_phantom_found = True
return {"station_name": station_name.split('.')[2], "sta_down": station_details['down'], "radio_up": True}
if not wiphy_non_phantom_found:
for station in stations:
station_name, station_details = list(station.keys())[0], list(station.values())[0]
if (station_details['parent dev'] == '' and not station_details['phantom'] and station_details['alias'] == 'wiphy0'):
return {"station_name": None, "sta_down": None, "radio_up": True}
return {"station_name": None, "sta_down": None, "radio_up": False}
else:
logger.error(
'Malformed response. Response does not have interfaces data. Setting the station name to default i.e., wlan0')
return {"station_name": "wlan0", "sta_down": None, "radio_up": False}
class DeviceConfig(Realm):
def __init__(self, lanforge_ip=None,
port=8080, file_name=None,
_debug_on=False, csv_name=None, create_csv=False,
wait_time=60
):
super().__init__(lfclient_host=lanforge_ip,
debug_=_debug_on)
self.lanforge_ip = lanforge_ip
self.port = port
self.file_name = file_name
self.create_csv = create_csv
self.csv_name = csv_name
self.wait_time = wait_time
# Objects for alptops and adb class
self.adb_obj = ADB_DEVICES(lanforge_ip=self.lanforge_ip)
self.laptop_obj = LAPTOPS(lanforge_ip=self.lanforge_ip)
# available devices
self.all_available_devices = {}
self.all_mapped_devices = {}
# groups
self.groups = {}
# selected
self.already_added = {}
self.selected_devices = []
# wifi profiles
self.profile_data = []
def get_all_devices(self, adb=True, laptops=True):
adb_devices = []
laptop_devices = []
if adb:
adb_devices = self.adb_obj.get_devices()
if laptops:
laptop_devices = self.laptop_obj.get_devices()
self.all_devices = adb_devices + laptop_devices
return (adb_devices + laptop_devices)
def map_all_devices(self):
if not self.all_devices:
return self.all_mapped_devices
for index, device in enumerate(self.all_devices):
map_device = {}
if device["type"] == 'adb':
map_device["serial"] = device["serial"]
elif device["type"] == 'laptop':
map_device["serial"] = device["hostname"]
map_device["os"] = device["os"]
map_device["resource"] = device["resource"]
self.all_mapped_devices[str(index)] = map_device
return self.all_mapped_devices
def read_groups_file(self):
py_scripts_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
# Read CSV file into DataFrame
file_name = os.path.join(py_scripts_dir, self.file_name + '.csv')
try:
df = pd.read_csv(file_name)
except Exception:
# logger.error("CSV is empty or malformed")
return {}
df = df.where(pd.notna(df), None)
data = {col: df[col].dropna().apply(lambda x: str(int(x)) if isinstance(x, float) else str(x)).tolist() for col in df.columns}
return data
def get_all_available_devices(self):
dataset = self.groups
already_added = {}
not_added_mapped_devices = {}
for g_name, g_values in dataset.items():
for val in g_values:
if not already_added.get(val):
already_added[val] = [g_name]
else:
already_added[val].append()
idx = 1
for obj in self.all_mapped_devices.values():
if obj["serial"] not in already_added:
not_added_mapped_devices[str(idx)] = obj
idx += 1
self.already_added = already_added