-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_parser.py
More file actions
165 lines (129 loc) · 5.21 KB
/
Copy pathcsv_parser.py
File metadata and controls
165 lines (129 loc) · 5.21 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
"""Parser for Pdv.CSV file containing site credentials"""
import csv
import os
import logging
logger = logging.getLogger(__name__)
# Path to Pdv.CSV in project root
DEFAULT_CSV_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'Pdv.CSV')
def parse_pdv_csv(filepath=None):
"""
Parse Pdv.CSV file and return list of site dictionaries.
CSV Format (semicolon separated):
sito;Nome;Network;utente;password;Switch CORE;utente Core;password core
Returns:
list[dict]: List of site configurations with keys:
- sito: Site ID
- nome: Site name
- network: Network CIDR (e.g., 10.1.4.0/24)
- utente: Local switch username
- password: Local switch password
- switch_core_ip: Core switch IP
- utente_core: Core switch username
- password_core: Core switch password
"""
if filepath is None:
filepath = DEFAULT_CSV_PATH
sites = []
if not os.path.exists(filepath):
logger.warning(f"CSV file not found: {filepath}")
return sites
try:
with open(filepath, 'r', encoding='utf-8-sig') as f:
# Use semicolon as delimiter
reader = csv.DictReader(f, delimiter=';')
for row in reader:
# Skip empty rows or header-like rows
sito = row.get('sito', '').strip()
if not sito or sito.upper() == 'SITO':
continue
# Skip CORE fallback row
if sito.upper() == 'CORE':
continue
# Clean password fields (handle escaped quotes)
password = row.get('password', '').strip()
password_core = row.get('password core', '').strip()
# Remove surrounding quotes and unescape double quotes
password = _clean_password(password)
password_core = _clean_password(password_core)
site = {
'sito': sito,
'nome': row.get('Nome', '').strip(),
'network': row.get('Network', '').strip(),
'utente': row.get('utente', '').strip(),
'password': password,
'switch_core_ip': row.get('Switch CORE', '').strip(),
'utente_core': row.get('utente Core', '').strip(),
'password_core': password_core,
}
sites.append(site)
logger.info(f"Loaded {len(sites)} sites from CSV")
except Exception as e:
logger.error(f"Error parsing CSV: {e}")
return sites
def _clean_password(password):
"""Clean password field from CSV escaping.
Note: Python's csv module already handles quote unescaping,
so we only need to handle edge cases where quotes might remain.
"""
if not password:
return password
# Only remove surrounding quotes if they exist (shouldn't happen with csv module)
if password.startswith('"') and password.endswith('"'):
password = password[1:-1]
# DO NOT unescape double quotes - csv module already does this
# The password may legitimately contain "" as part of the actual password
return password
def get_site_by_id(sito_id, filepath=None):
"""Get a specific site by its ID (returns first match)"""
sites = parse_pdv_csv(filepath)
for site in sites:
if site['sito'] == str(sito_id):
return site
return None
def get_all_credentials_for_site(sito_id, filepath=None):
"""
Get all credential sets for a site ID.
Returns a list of unique credential combinations for sites with multiple entries.
Useful for credential fallback when some switches use different credentials.
Returns:
list[dict]: List of credential sets with keys:
- username: L2 switch username
- password: L2 switch password
- username_core: Core switch username
- password_core: Core switch password
"""
sites = parse_pdv_csv(filepath)
credentials = []
seen = set()
for site in sites:
if site['sito'] == str(sito_id):
# Create a unique key for this credential set
cred_key = (site['utente'], site['password'])
if cred_key not in seen:
seen.add(cred_key)
credentials.append({
'username': site['utente'],
'password': site['password'],
'username_core': site['utente_core'] or site['utente'],
'password_core': site['password_core'] or site['password'],
})
return credentials
def get_site_by_name(nome, filepath=None):
"""Get a specific site by its name"""
sites = parse_pdv_csv(filepath)
for site in sites:
if site['nome'].lower() == nome.lower():
return site
return None
def get_sites_dropdown():
"""Get sites formatted for dropdown selection"""
sites = parse_pdv_csv()
return [
{
'value': site['sito'],
'label': f"{site['nome']} ({site['sito']})",
'ip': site['switch_core_ip'],
'network': site['network'],
}
for site in sites
]