or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-parsing.mdindex.mdinterface-parsing.mdnetwork-objects.mdutilities.md

utilities.mddocs/

0

# Utilities and Helpers

1

2

Comprehensive utility functions for DNS operations, text processing, validation, logging control, and Cisco-specific utilities like password decryption and command execution. These tools support advanced network automation workflows and configuration management tasks.

3

4

## Capabilities

5

6

### DNS Operations

7

8

Comprehensive DNS query functionality with support for multiple record types and configurable DNS servers.

9

10

```python { .api }

11

def dns_query(query_name, query_type='A', server='8.8.8.8', timeout=0.5):

12

"""

13

Perform DNS query for specified record type.

14

15

Parameters:

16

- query_name (str): Domain name to query

17

- query_type (str): DNS record type ('A', 'AAAA', 'MX', 'NS', 'TXT', etc.)

18

- server (str): DNS server IP address

19

- timeout (float): Query timeout in seconds

20

21

Returns:

22

DNSResponse: DNS query response object

23

"""

24

25

def dns_lookup(input_name, timeout=0.5, server='8.8.8.8'):

26

"""

27

DNS A record lookup for IPv4 addresses.

28

29

Parameters:

30

- input_name (str): Domain name to resolve

31

- timeout (float): Query timeout in seconds

32

- server (str): DNS server IP address

33

34

Returns:

35

list[str]: List of IPv4 addresses

36

"""

37

38

def dns6_lookup(input_name, timeout=0.5, server='8.8.8.8'):

39

"""

40

DNS AAAA record lookup for IPv6 addresses.

41

42

Parameters:

43

- input_name (str): Domain name to resolve

44

- timeout (float): Query timeout in seconds

45

- server (str): DNS server IP address

46

47

Returns:

48

list[str]: List of IPv6 addresses

49

"""

50

51

def reverse_dns_lookup(input_addr, timeout=0.5, server='8.8.8.8'):

52

"""

53

Reverse DNS lookup for hostname resolution.

54

55

Parameters:

56

- input_addr (str): IP address to resolve

57

- timeout (float): Query timeout in seconds

58

- server (str): DNS server IP address

59

60

Returns:

61

list[str]: List of hostnames

62

"""

63

```

64

65

### System Command Execution

66

67

Execute system commands with timeout control and result capture.

68

69

```python { .api }

70

def run_this_posix_command(command, timeout=60.0):

71

"""

72

Execute POSIX commands with timeout and error handling.

73

74

Parameters:

75

- command (str): Command string to execute

76

- timeout (float): Command timeout in seconds

77

78

Returns:

79

dict: Command execution results with stdout, stderr, and return code

80

"""

81

```

82

83

### Logging and Debug Control

84

85

Configure and control logging for ciscoconfparse operations.

86

87

```python { .api }

88

def ccp_logger_control(action='disable', sink_path=None, level='INFO'):

89

"""

90

Control ciscoconfparse logging configuration.

91

92

Parameters:

93

- action (str): Logging action ('enable', 'disable', 'reset')

94

- sink_path (str): Log file path (None for console)

95

- level (str): Log level ('DEBUG', 'INFO', 'WARNING', 'ERROR')

96

"""

97

98

def configure_loguru(sink=None, level='INFO', format=None):

99

"""

100

Configure loguru logging system.

101

102

Parameters:

103

- sink (str): Log destination (file path or console)

104

- level (str): Minimum log level

105

- format (str): Log message format string

106

"""

107

108

def log_function_call():

109

"""

110

Decorator to log function calls for debugging purposes.

111

Use as @log_function_call() before function definitions.

112

"""

113

```

114

115

### Text Processing

116

117

Text manipulation and formatting utilities for configuration processing.

118

119

```python { .api }

120

def as_text_list(config, syntax='ios'):

121

"""

122

Convert configuration objects to text list format.

123

124

Parameters:

125

- config: Configuration object, text, or list

126

- syntax (str): Configuration syntax type

127

128

Returns:

129

list[str]: Configuration as list of text lines

130

"""

131

132

def fix_repeated_words(text):

133

"""

134

Fix repeated words in configuration text.

135

136

Parameters:

137

- text (str): Input text with potential repeated words

138

139

Returns:

140

str: Text with repeated words removed

141

"""

142

```

143

144

### Regular Expression Utilities

145

146

Enhanced regular expression matching with additional functionality.

147

148

```python { .api }

149

class __ccp_re__:

150

"""Enhanced regular expression utilities for configuration parsing."""

151

152

@staticmethod

153

def search(pattern, string, flags=0):

154

"""

155

Enhanced regex search with additional error handling.

156

157

Parameters:

158

- pattern (str): Regular expression pattern

159

- string (str): String to search

160

- flags (int): Regex flags

161

162

Returns:

163

Match: Regex match object or None

164

"""

165

166

@staticmethod

167

def match(pattern, string, flags=0):

168

"""

169

Enhanced regex match with additional error handling.

170

171

Parameters:

172

- pattern (str): Regular expression pattern

173

- string (str): String to match

174

- flags (int): Regex flags

175

176

Returns:

177

Match: Regex match object or None

178

"""

179

180

@staticmethod

181

def sub(pattern, repl, string, count=0, flags=0):

182

"""

183

Enhanced regex substitution with additional functionality.

184

185

Parameters:

186

- pattern (str): Regular expression pattern

187

- repl (str): Replacement string

188

- string (str): Input string

189

- count (int): Maximum substitutions (0 for all)

190

- flags (int): Regex flags

191

192

Returns:

193

str: String with substitutions applied

194

"""

195

```

196

197

### Configuration Processing Utilities

198

199

Core utilities for configuration parsing and manipulation.

200

201

```python { .api }

202

def get_version_number():

203

"""

204

Get ciscoconfparse package version.

205

206

Returns:

207

str: Package version string

208

"""

209

210

def initialize_ciscoconfparse():

211

"""

212

Initialize ciscoconfparse package with default settings.

213

Performs package-level initialization and setup.

214

"""

215

216

def parse_line_braces(line):

217

"""

218

Parse configuration line with brace syntax support.

219

220

Parameters:

221

- line (str): Configuration line to parse

222

223

Returns:

224

str: Parsed configuration line

225

"""

226

227

def build_space_tolerant_regex(linespec):

228

"""

229

Build flexible regex pattern that handles variable whitespace.

230

231

Parameters:

232

- linespec (str): Base pattern specification

233

234

Returns:

235

Pattern: Compiled regex pattern with space tolerance

236

"""

237

```

238

239

### Type Validation

240

241

Runtime type checking and validation for function parameters.

242

243

```python { .api }

244

def enforce_valid_types(func, args, kwargs):

245

"""

246

Enforce valid parameter types for function calls.

247

248

Parameters:

249

- func (callable): Function to validate

250

- args (tuple): Function positional arguments

251

- kwargs (dict): Function keyword arguments

252

253

Raises:

254

TypeError: If parameter types don't match expectations

255

"""

256

```

257

258

### Decorators

259

260

Function decorators for enhanced functionality and debugging.

261

262

```python { .api }

263

def junos_unsupported():

264

"""

265

Decorator to mark functions as unsupported for Junos configurations.

266

Raises appropriate exceptions when used with Junos syntax.

267

"""

268

```

269

270

## Protocol and Port Constants

271

272

### ASA Protocol Support

273

274

Protocol definitions and port mappings for Cisco ASA configurations.

275

276

```python { .api }

277

# Protocol constants from ciscoconfparse.protocol_values

278

ASA_IP_PROTOCOLS = {

279

# Dictionary mapping protocol names to numbers

280

'icmp': 1,

281

'tcp': 6,

282

'udp': 17,

283

# ... additional protocols

284

}

285

286

ASA_TCP_PORTS = {

287

# Dictionary mapping TCP service names to port numbers

288

'ftp': 21,

289

'ssh': 22,

290

'telnet': 23,

291

'smtp': 25,

292

'http': 80,

293

'https': 443,

294

# ... additional TCP ports

295

}

296

297

ASA_UDP_PORTS = {

298

# Dictionary mapping UDP service names to port numbers

299

'dns': 53,

300

'dhcp': 67,

301

'tftp': 69,

302

'snmp': 161,

303

# ... additional UDP ports

304

}

305

```

306

307

## Exception Handling

308

309

### Comprehensive Exception Hierarchy

310

311

All exceptions inherit from BaseError for consistent error handling.

312

313

```python { .api }

314

class BaseError(Exception):

315

"""Base exception class for ciscoconfparse."""

316

317

class PythonOptimizeException(BaseError):

318

"""Python optimization related errors."""

319

320

class RequirementFailure(BaseError):

321

"""Requirement validation failures."""

322

323

class ListItemMissingAttribute(BaseError):

324

"""Missing attribute in list item operations."""

325

326

class ListItemTypeError(BaseError):

327

"""Type errors in list item operations."""

328

329

class DNSLookupError(BaseError):

330

"""DNS lookup operation failures."""

331

332

class DNSTimeoutError(BaseError):

333

"""DNS query timeout errors."""

334

335

class DuplicateMember(BaseError):

336

"""Duplicate member errors in collections."""

337

338

class DynamicAddressException(BaseError):

339

"""Dynamic address handling errors."""

340

341

class InvalidCiscoInterface(BaseError):

342

"""Invalid Cisco interface specifications."""

343

344

class InvalidCiscoEthernetTrunkAction(BaseError):

345

"""Invalid Ethernet trunk action configurations."""

346

347

class InvalidCiscoEthernetVlan(BaseError):

348

"""Invalid VLAN specifications."""

349

350

class InvalidMember(BaseError):

351

"""Invalid member in collection operations."""

352

353

class InvalidParameters(BaseError):

354

"""Invalid function parameter errors."""

355

356

class InvalidCiscoRange(BaseError):

357

"""Invalid Cisco range format specifications."""

358

359

class InvalidShellVariableMapping(BaseError):

360

"""Invalid shell variable mapping errors."""

361

362

class InvalidTypecast(BaseError):

363

"""Invalid type casting operations."""

364

365

class NoRegexMatch(BaseError):

366

"""No regex match found errors."""

367

368

class MismatchedType(BaseError):

369

"""Type mismatch errors."""

370

371

class UnexpectedType(BaseError):

372

"""Unexpected type errors."""

373

374

class UntypedError(BaseError):

375

"""Untyped error conditions."""

376

```

377

378

## Usage Examples

379

380

### DNS Operations

381

382

```python

383

from ciscoconfparse import dns_lookup, dns6_lookup, reverse_dns_lookup, dns_query

384

385

# Basic DNS lookups

386

ipv4_addresses = dns_lookup('www.cisco.com')

387

print(f"IPv4 addresses: {ipv4_addresses}")

388

389

ipv6_addresses = dns6_lookup('www.cisco.com')

390

print(f"IPv6 addresses: {ipv6_addresses}")

391

392

# Reverse DNS lookup

393

hostnames = reverse_dns_lookup('8.8.8.8')

394

print(f"Hostnames: {hostnames}")

395

396

# Advanced DNS query

397

mx_response = dns_query('cisco.com', query_type='MX')

398

print(f"MX record: {mx_response.response}")

399

print(f"Preference: {mx_response.preference}")

400

```

401

402

### System Command Execution

403

404

```python

405

from ciscoconfparse import run_this_posix_command

406

407

# Execute system command with timeout

408

result = run_this_posix_command('ping -c 3 8.8.8.8', timeout=10.0)

409

print(f"Return code: {result['returncode']}")

410

print(f"Output: {result['stdout']}")

411

if result['stderr']:

412

print(f"Errors: {result['stderr']}")

413

```

414

415

### Logging Configuration

416

417

```python

418

from ciscoconfparse import ccp_logger_control, configure_loguru

419

420

# Enable logging to file

421

ccp_logger_control(action='enable', sink_path='ciscoconfparse.log', level='DEBUG')

422

423

# Configure loguru logging

424

configure_loguru(sink='debug.log', level='INFO', format='{time} {level} {message}')

425

426

# Disable logging

427

ccp_logger_control(action='disable')

428

```

429

430

### Protocol and Port Lookups

431

432

```python

433

from ciscoconfparse.protocol_values import ASA_TCP_PORTS, ASA_UDP_PORTS, ASA_IP_PROTOCOLS

434

435

# Look up well-known ports

436

http_port = ASA_TCP_PORTS['http'] # 80

437

https_port = ASA_TCP_PORTS['https'] # 443

438

dns_port = ASA_UDP_PORTS['dns'] # 53

439

440

# Look up protocol numbers

441

tcp_proto = ASA_IP_PROTOCOLS['tcp'] # 6

442

udp_proto = ASA_IP_PROTOCOLS['udp'] # 17

443

444

print(f"HTTP runs on TCP port {http_port}")

445

print(f"DNS runs on UDP port {dns_port}")

446

```

447

448

### Text Processing

449

450

```python

451

from ciscoconfparse import as_text_list, fix_repeated_words

452

453

# Convert configuration to text list

454

config_lines = as_text_list(parse, syntax='ios')

455

print(f"Configuration has {len(config_lines)} lines")

456

457

# Fix repeated words in text

458

corrected_text = fix_repeated_words("interface interface GigabitEthernet0/1")

459

print(f"Corrected: {corrected_text}") # "interface GigabitEthernet0/1"

460

```

461

462

### Version Information

463

464

```python

465

from ciscoconfparse import get_version_number

466

467

version = get_version_number()

468

print(f"CiscoConfParse version: {version}")

469

```

470

471

### Regular Expression Utilities

472

473

```python

474

from ciscoconfparse.ccp_util import __ccp_re__

475

476

# Enhanced regex operations

477

pattern = r'interface.*GigabitEthernet'

478

text = "interface GigabitEthernet0/1"

479

480

match = __ccp_re__.search(pattern, text)

481

if match:

482

print(f"Found match: {match.group()}")

483

484

# Enhanced substitution

485

new_text = __ccp_re__.sub(r'GigabitEthernet', 'Gi', text)

486

print(f"Abbreviated: {new_text}") # "interface Gi0/1"

487

```

488

489

### Error Handling

490

491

```python

492

from ciscoconfparse import CiscoConfParse, InvalidCiscoInterface, DNSLookupError

493

494

try:

495

# This might raise InvalidCiscoInterface

496

parse = CiscoConfParse('config.txt', syntax='ios')

497

interface_obj = parse.find_objects(r'^interface InvalidName')[0]

498

499

except InvalidCiscoInterface as e:

500

print(f"Interface error: {e}")

501

except DNSLookupError as e:

502

print(f"DNS error: {e}")

503

except BaseError as e:

504

print(f"CiscoConfParse error: {e}")

505

```