Skip to content

base_channel

scrapli.channel.base_channel

BaseChannel

Source code in channel/base_channel.py
 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
class BaseChannel:
    def __init__(
        self,
        transport: Union[AsyncTransport, Transport],
        base_channel_args: BaseChannelArgs,
    ):
        """
        BaseChannel Object -- provides convenience methods to both sync and async Channels

        Args:
            transport: initialized scrapli Transport/AsyncTransport object
            base_channel_args: BaseChannelArgs object

        Returns:
            None

        Raises:
            N/A

        """
        self.transport = transport
        self._base_channel_args = base_channel_args

        self.logger = get_instance_logger(
            instance_name="scrapli.channel",
            host=self.transport._base_transport_args.host,
            port=self.transport._base_transport_args.port,
            uid=self.transport._base_transport_args.logging_uid,
        )

        self.channel_log: Optional[BinaryIO] = None

        self._auth_telnet_login_pattern = r"^(.*username:)|(.*login:)\s?$"
        self._auth_password_pattern = r"(.*@.*)?password:\s?$"
        self._auth_passphrase_pattern = r"enter passphrase for key"

    @property
    def auth_telnet_login_pattern(self) -> Pattern[bytes]:
        """
        Getter for `auth_telnet_login_pattern` attribute

        Args:
            N/A

        Returns:
            Pattern: compiled pattern of the set auth_telnet_login_pattern value

        Raises:
            N/A

        """
        return re.compile(self._auth_telnet_login_pattern.encode(), flags=re.I | re.M)

    @auth_telnet_login_pattern.setter
    def auth_telnet_login_pattern(self, value: str) -> None:
        """
        Setter for `auth_telnet_login_pattern` attribute

        Args:
            value: str value for auth_telnet_login_pattern; this value will be compiled withe re.I
                and re.M flags when the getter is called.

        Returns:
            None

        Raises:
            ScrapliTypeError: if value is not of type str

        """
        self.logger.debug(f"setting 'auth_telnet_login_pattern' value to '{value}'")

        if not isinstance(value, str):
            raise ScrapliTypeError

        self._auth_telnet_login_pattern = value

    @property
    def auth_password_pattern(self) -> Pattern[bytes]:
        """
        Getter for `auth_password_pattern` attribute

        Args:
            N/A

        Returns:
            Pattern: compiled pattern of the set auth_password_pattern value

        Raises:
            N/A

        """
        return re.compile(self._auth_password_pattern.encode(), flags=re.I | re.M)

    @auth_password_pattern.setter
    def auth_password_pattern(self, value: str) -> None:
        """
        Setter for `auth_password_pattern` attribute

        Args:
            value: str value for auth_password_pattern; this value will be compiled withe re.I
                and re.M flags when the getter is called.

        Returns:
            None

        Raises:
            ScrapliTypeError: if value is not of type str

        """
        self.logger.debug(f"setting 'auth_password_pattern' value to '{value}'")

        if not isinstance(value, str):
            raise ScrapliTypeError

        self._auth_password_pattern = value

    @property
    def auth_passphrase_pattern(self) -> Pattern[bytes]:
        """
        Getter for `auth_passphrase_pattern` attribute

        Args:
            N/A

        Returns:
            Pattern: compiled pattern of the set auth_passphrase_pattern value

        Raises:
            N/A

        """
        return re.compile(self._auth_passphrase_pattern.encode(), flags=re.I | re.M)

    @auth_passphrase_pattern.setter
    def auth_passphrase_pattern(self, value: str) -> None:
        """
        Setter for `auth_passphrase_pattern` attribute

        Args:
            value: str value for auth_passphrase_pattern; this value will be compiled withe re.I
                and re.M flags when the getter is called.

        Returns:
            None

        Raises:
            ScrapliTypeError: if value is not of type str

        """
        self.logger.debug(f"setting '_auth_passphrase_pattern' value to '{value}'")

        if not isinstance(value, str):
            raise ScrapliTypeError

        self._auth_passphrase_pattern = value

    def open(self) -> None:
        """
        Channel open method

        Args:
            N/A

        Returns:
            None

        Raises:
            N/A

        """
        if self._base_channel_args.channel_log:
            if isinstance(self._base_channel_args.channel_log, BytesIO):
                self.channel_log = self._base_channel_args.channel_log
            else:
                channel_log_destination = "scrapli_channel.log"
                if isinstance(self._base_channel_args.channel_log, str):
                    channel_log_destination = self._base_channel_args.channel_log
                self.logger.info(
                    f"channel log enabled, logging channel output to '{channel_log_destination}'"
                )
                # have to ignore type due to mypy not wanting to read the mode from formatted string
                # if you change the mode --> "wb" or "ab" it works as you would hope/expect; those
                # are the only values it can possibly be at this point though so we can safely
                # ignore here
                # note that this will *always* be binary mode, so there doesn't need to be any
                # encoding, hence ignoring that pylint message!
                self.channel_log = open(  # pylint: disable=W1514,R1732
                    channel_log_destination,
                    mode=f"{self._base_channel_args.channel_log_mode}b",  # type: ignore
                )

    def close(self) -> None:
        """
        Channel close method

        Args:
            N/A

        Returns:
            None

        Raises:
            N/A

        """
        if self.channel_log:
            self.channel_log.close()

    def _process_read_buf(self, read_buf: BytesIO) -> bytes:
        """
        Process the read buffer

        Seeks backwards up to search depth then partitions on newlines. Partition is to ensure that
        the resulting search_buf does not end up with partial lines in the output which can cause
        prompt patterns to match places they should not match!

        Args:
            read_buf: bytesio object read from the transport

        Returns:
            bytes: cleaned up search buffer

        Raises:
            N/A

        """
        read_buf.seek(-self._base_channel_args.comms_prompt_search_depth, SEEK_END)
        search_buf = read_buf.read()

        before, _, search_buf = search_buf.partition(b"\n")

        if not search_buf:
            # didn't split on anything or nothing after partition
            search_buf = before

        return search_buf

    def write(self, channel_input: str, redacted: bool = False) -> None:
        """
        Write input to the underlying Transport session

        Args:
            channel_input: string of input to send
            redacted: redact channel input from log or not

        Returns:
            None

        Raises:
            N/A

        """
        log_output = "REDACTED" if redacted else repr(channel_input)
        self.logger.debug(f"write: {log_output}")

        self.transport.write(channel_input=channel_input.encode())

    def send_return(self) -> None:
        """
        Convenience method to send return char

        Args:
            N/A

        Returns:
            None

        Raises:
            N/A

        """
        self.write(channel_input=self._base_channel_args.comms_return_char)

    @staticmethod
    def _join_and_compile(channel_outputs: Optional[List[bytes]]) -> Pattern[bytes]:
        """
        Convenience method for read_until_prompt_or_time to join channel inputs into a regex pattern

        Args:
            channel_outputs: list of bytes channel inputs to join into a regex pattern

        Returns:
            Pattern: joined regex pattern or an empty pattern (empty bytes)

        Raises:
            N/A

        """
        regex_channel_outputs = b""
        if channel_outputs:
            regex_channel_outputs = b"|".join(
                [b"(" + channel_output + b")" for channel_output in channel_outputs]
            )
        regex_channel_outputs_pattern = re.compile(pattern=regex_channel_outputs, flags=re.I | re.M)

        return regex_channel_outputs_pattern

    def _ssh_message_handler(self, output: bytes) -> None:  # noqa: C901
        """
        Parse EOF messages from _pty_authenticate and create log/stack exception message

        Args:
            output: bytes output from _pty_authenticate

        Returns:
            N/A  # noqa: DAR202

        Raises:
            ScrapliAuthenticationFailed: if any errors are read in the output

        """
        msg = ""
        if b"host key verification failed" in output.lower():
            msg = "Host key verification failed"
        elif b"operation timed out" in output.lower() or b"connection timed out" in output.lower():
            msg = "Timed out connecting to host"
        elif b"no route to host" in output.lower():
            msg = "No route to host"
        elif b"no matching host key" in output.lower():
            msg = "No matching host key type found for host"
            key_exchange_pattern = re.compile(
                pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I
            )
            offered_key_exchanges_match = re.search(pattern=key_exchange_pattern, string=output)
            if offered_key_exchanges_match:
                offered_key_exchanges = offered_key_exchanges_match.group(1).decode()
                msg += f", their offer: {offered_key_exchanges}"
        elif b"no matching key exchange" in output.lower():
            msg = "No matching key exchange found for host"
            key_exchange_pattern = re.compile(
                pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I
            )
            offered_key_exchanges_match = re.search(pattern=key_exchange_pattern, string=output)
            if offered_key_exchanges_match:
                offered_key_exchanges = offered_key_exchanges_match.group(1).decode()
                msg += f", their offer: {offered_key_exchanges}"
        elif b"no matching cipher" in output.lower():
            msg = "No matching cipher found for host"
            ciphers_pattern = re.compile(pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I)
            offered_ciphers_match = re.search(pattern=ciphers_pattern, string=output)
            if offered_ciphers_match:
                offered_ciphers = offered_ciphers_match.group(1).decode()
                msg += f", their offer: {offered_ciphers}"
        elif b"bad configuration" in output.lower():
            msg = "Bad SSH configuration option(s) for host"
            configuration_pattern = re.compile(
                pattern=rb"bad configuration option: ([a-z0-9\+\=,]*)", flags=re.M | re.I
            )
            configuration_issue_match = re.search(pattern=configuration_pattern, string=output)
            if configuration_issue_match:
                configuration_issues = configuration_issue_match.group(1).decode()
                msg += f", bad option(s): {configuration_issues}"
        elif b"WARNING: UNPROTECTED PRIVATE KEY FILE!" in output:
            msg = "Permissions for private key are too open, authentication failed!"
        elif b"could not resolve hostname" in output.lower():
            msg = "Could not resolve address for host"
        elif b"permission denied" in output.lower():
            msg = str(output)
        if msg:
            self.logger.critical(msg)
            raise ScrapliAuthenticationFailed(msg)

    @staticmethod
    @lru_cache()
    def _get_prompt_pattern(class_pattern: str, pattern: Optional[str] = None) -> Pattern[bytes]:
        """
        Return compiled prompt pattern

        Given a potential prompt and the Channel class' prompt, return compiled prompt pattern

        Args:
            class_pattern: comms_prompt_pattern from the class itself; must be passed so that the
                arguments are recognized in lru cache; this way if a user changes the pattern during
                normal scrapli operations the lru cache can "notice" the pattern changed!
            pattern: optional regex pattern to compile, if not provided we use the class' pattern

        Returns:
            pattern: compiled regex pattern to use to search for a prompt in output data

        Raises:
            N/A

        """
        if not pattern:
            return re.compile(class_pattern.encode(), flags=re.M | re.I)

        bytes_pattern = pattern.encode()
        if bytes_pattern.startswith(b"^") and bytes_pattern.endswith(b"$"):
            return re.compile(bytes_pattern, flags=re.M | re.I)
        return re.compile(re.escape(bytes_pattern))

    def _pre_channel_authenticate_ssh(
        self,
    ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes]]:
        """
        Handle pre ssh authentication work for parity between sync and sync versions.

        Args:
            N/A

        Returns:
            tuple: tuple of pass/passphrase/prompt patterns

        Raises:
            N/A

        """
        prompt_pattern = self._get_prompt_pattern(
            class_pattern=self._base_channel_args.comms_prompt_pattern
        )

        return self.auth_password_pattern, self.auth_passphrase_pattern, prompt_pattern

    def _pre_channel_authenticate_telnet(
        self,
    ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes], float, float]:
        """
        Handle pre telnet authentication work for parity between sync and sync versions.

        Args:
            N/A

        Returns:
            tuple: tuple of user/pass/prompt patterns, start timestamp and return interval

        Raises:
            N/A

        """
        prompt_pattern = self._get_prompt_pattern(
            class_pattern=self._base_channel_args.comms_prompt_pattern
        )

        # capture the start time of the authentication event; we also set a "return_interval" which
        # is 1/10 the timout_ops value, we will send a return character at roughly this interval if
        # there is no output on the channel. we do this because sometimes telnet needs a kick to get
        # it to prompt for auth -- particularity when connecting to terminal server/console port
        auth_start_time = datetime.now().timestamp()
        return_interval = self._base_channel_args.timeout_ops / 10

        return (
            self.auth_telnet_login_pattern,
            self.auth_password_pattern,
            prompt_pattern,
            auth_start_time,
            return_interval,
        )

    def _process_output(self, buf: bytes, strip_prompt: bool) -> bytes:
        """
        Process output received form the device

        Remove inputs and prompts if desired

        Args:
            buf: bytes output from the device
            strip_prompt: True/False strip the prompt from the device output

        Returns:
            bytes: cleaned up byte string

        Raises:
            N/A

        """
        buf = b"\n".join([line.rstrip() for line in buf.splitlines()])

        if strip_prompt:
            prompt_pattern = self._get_prompt_pattern(
                class_pattern=self._base_channel_args.comms_prompt_pattern
            )
            buf = re.sub(pattern=prompt_pattern, repl=b"", string=buf)

        buf = buf.lstrip(self._base_channel_args.comms_return_char.encode()).rstrip()
        return buf

    @staticmethod
    def _strip_ansi(buf: bytes) -> bytes:
        """
        Strip ansi characters from output

        Args:
            buf: bytes from previous reads if needed

        Returns:
            bytes: bytes output read from channel with ansi characters removed

        Raises:
            N/A

        """
        buf = re.sub(pattern=ANSI_ESCAPE_PATTERN, repl=b"", string=buf)
        return buf

    @staticmethod
    def _pre_send_input(channel_input: str) -> None:
        """
        Handle pre "send_input" tasks for consistency between sync/async versions

        Args:
            channel_input: string input to send to channel

        Returns:
            bytes: current channel buffer

        Raises:
            ScrapliTypeError: if input is anything but a string

        """
        if not isinstance(channel_input, str):
            raise ScrapliTypeError(
                f"`send_input` expects a single string, got {type(channel_input)}."
            )

    @staticmethod
    def _pre_send_inputs_interact(interact_events: List[Tuple[str, str, Optional[bool]]]) -> None:
        """
        Handle pre "send_inputs_interact" tasks for consistency between sync/async versions

        Args:
            interact_events: interact events passed to `send_inputs_interact`

        Returns:
            None

        Raises:
            ScrapliTypeError: if input is anything but a string

        """
        if not isinstance(interact_events, list):
            raise ScrapliTypeError(f"`interact_events` expects a List, got {type(interact_events)}")

__init__(transport: Union[AsyncTransport, Transport], base_channel_args: BaseChannelArgs)

BaseChannel Object -- provides convenience methods to both sync and async Channels

Parameters:

Name Type Description Default
transport Union[AsyncTransport, Transport]

initialized scrapli Transport/AsyncTransport object

required
base_channel_args BaseChannelArgs

BaseChannelArgs object

required

Returns:

Type Description

None

Source code in channel/base_channel.py
 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
def __init__(
    self,
    transport: Union[AsyncTransport, Transport],
    base_channel_args: BaseChannelArgs,
):
    """
    BaseChannel Object -- provides convenience methods to both sync and async Channels

    Args:
        transport: initialized scrapli Transport/AsyncTransport object
        base_channel_args: BaseChannelArgs object

    Returns:
        None

    Raises:
        N/A

    """
    self.transport = transport
    self._base_channel_args = base_channel_args

    self.logger = get_instance_logger(
        instance_name="scrapli.channel",
        host=self.transport._base_transport_args.host,
        port=self.transport._base_transport_args.port,
        uid=self.transport._base_transport_args.logging_uid,
    )

    self.channel_log: Optional[BinaryIO] = None

    self._auth_telnet_login_pattern = r"^(.*username:)|(.*login:)\s?$"
    self._auth_password_pattern = r"(.*@.*)?password:\s?$"
    self._auth_passphrase_pattern = r"enter passphrase for key"

auth_passphrase_pattern() -> Pattern[bytes] writable property

Getter for auth_passphrase_pattern attribute

Returns:

Name Type Description
Pattern Pattern[bytes]

compiled pattern of the set auth_passphrase_pattern value

Source code in channel/base_channel.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@property
def auth_passphrase_pattern(self) -> Pattern[bytes]:
    """
    Getter for `auth_passphrase_pattern` attribute

    Args:
        N/A

    Returns:
        Pattern: compiled pattern of the set auth_passphrase_pattern value

    Raises:
        N/A

    """
    return re.compile(self._auth_passphrase_pattern.encode(), flags=re.I | re.M)

auth_password_pattern() -> Pattern[bytes] writable property

Getter for auth_password_pattern attribute

Returns:

Name Type Description
Pattern Pattern[bytes]

compiled pattern of the set auth_password_pattern value

Source code in channel/base_channel.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@property
def auth_password_pattern(self) -> Pattern[bytes]:
    """
    Getter for `auth_password_pattern` attribute

    Args:
        N/A

    Returns:
        Pattern: compiled pattern of the set auth_password_pattern value

    Raises:
        N/A

    """
    return re.compile(self._auth_password_pattern.encode(), flags=re.I | re.M)

auth_telnet_login_pattern() -> Pattern[bytes] writable property

Getter for auth_telnet_login_pattern attribute

Returns:

Name Type Description
Pattern Pattern[bytes]

compiled pattern of the set auth_telnet_login_pattern value

Source code in channel/base_channel.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@property
def auth_telnet_login_pattern(self) -> Pattern[bytes]:
    """
    Getter for `auth_telnet_login_pattern` attribute

    Args:
        N/A

    Returns:
        Pattern: compiled pattern of the set auth_telnet_login_pattern value

    Raises:
        N/A

    """
    return re.compile(self._auth_telnet_login_pattern.encode(), flags=re.I | re.M)

close() -> None

Channel close method

Returns:

Type Description
None

None

Source code in channel/base_channel.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def close(self) -> None:
    """
    Channel close method

    Args:
        N/A

    Returns:
        None

    Raises:
        N/A

    """
    if self.channel_log:
        self.channel_log.close()

open() -> None

Channel open method

Returns:

Type Description
None

None

Source code in channel/base_channel.py
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
def open(self) -> None:
    """
    Channel open method

    Args:
        N/A

    Returns:
        None

    Raises:
        N/A

    """
    if self._base_channel_args.channel_log:
        if isinstance(self._base_channel_args.channel_log, BytesIO):
            self.channel_log = self._base_channel_args.channel_log
        else:
            channel_log_destination = "scrapli_channel.log"
            if isinstance(self._base_channel_args.channel_log, str):
                channel_log_destination = self._base_channel_args.channel_log
            self.logger.info(
                f"channel log enabled, logging channel output to '{channel_log_destination}'"
            )
            # have to ignore type due to mypy not wanting to read the mode from formatted string
            # if you change the mode --> "wb" or "ab" it works as you would hope/expect; those
            # are the only values it can possibly be at this point though so we can safely
            # ignore here
            # note that this will *always* be binary mode, so there doesn't need to be any
            # encoding, hence ignoring that pylint message!
            self.channel_log = open(  # pylint: disable=W1514,R1732
                channel_log_destination,
                mode=f"{self._base_channel_args.channel_log_mode}b",  # type: ignore
            )

send_return() -> None

Convenience method to send return char

Returns:

Type Description
None

None

Source code in channel/base_channel.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def send_return(self) -> None:
    """
    Convenience method to send return char

    Args:
        N/A

    Returns:
        None

    Raises:
        N/A

    """
    self.write(channel_input=self._base_channel_args.comms_return_char)

write(channel_input: str, redacted: bool = False) -> None

Write input to the underlying Transport session

Parameters:

Name Type Description Default
channel_input str

string of input to send

required
redacted bool

redact channel input from log or not

False

Returns:

Type Description
None

None

Source code in channel/base_channel.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def write(self, channel_input: str, redacted: bool = False) -> None:
    """
    Write input to the underlying Transport session

    Args:
        channel_input: string of input to send
        redacted: redact channel input from log or not

    Returns:
        None

    Raises:
        N/A

    """
    log_output = "REDACTED" if redacted else repr(channel_input)
    self.logger.debug(f"write: {log_output}")

    self.transport.write(channel_input=channel_input.encode())

BaseChannelArgs dataclass

Dataclass for all base Channel arguments

Parameters:

Name Type Description Default
comms_prompt_pattern str

comms_prompt_pattern to assign to the channel; should generally be created/passed from the driver class

'^[a-z0-9.\\-@()/:]{1,32}[#>$]$'
comms_return_char str

comms_return_char to assign to the channel, see above

'\n'
comms_prompt_search_depth int

depth of the buffer to search in for searching for the prompt in "read_until_prompt"; smaller number here will generally be faster, though may be less reliable; default value is 1000

1000
timeout_ops float

timeout_ops to assign to the channel, see above

30.0
channel_log Union[str, bool, BytesIO]

log "channel" output -- this would be the output you would normally see on a terminal. If True logs to scrapli_channel.log, if a string is provided, logs to wherever that string points

False
channel_log_mode str

"write"|"append", all other values will raise ValueError, does what it sounds like it should by setting the channel log to the provided mode

'write'
channel_lock bool

bool indicated if channel lock should be used for all read/write operations

False

Returns:

Type Description

None

Source code in channel/base_channel.py
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
@dataclass()
class BaseChannelArgs:
    """
    Dataclass for all base Channel arguments

    Args:
        comms_prompt_pattern: comms_prompt_pattern to assign to the channel; should generally be
            created/passed from the driver class
        comms_return_char: comms_return_char to assign to the channel, see above
        comms_prompt_search_depth: depth of the buffer to search in for searching for the prompt
            in "read_until_prompt"; smaller number here will generally be faster, though may be less
            reliable; default value is 1000
        timeout_ops: timeout_ops to assign to the channel, see above
        channel_log: log "channel" output -- this would be the output you would normally see on a
            terminal. If `True` logs to `scrapli_channel.log`, if a string is provided, logs to
            wherever that string points
        channel_log_mode: "write"|"append", all other values will raise ValueError,
            does what it sounds like it should by setting the channel log to the provided mode
        channel_lock: bool indicated if channel lock should be used for all read/write operations

    Returns:
        None

    Raises:
        N/A

    """

    comms_prompt_pattern: str = r"^[a-z0-9.\-@()/:]{1,32}[#>$]$"
    comms_return_char: str = "\n"
    comms_prompt_search_depth: int = 1000
    timeout_ops: float = 30.0
    channel_log: Union[str, bool, BytesIO] = False
    channel_log_mode: str = "write"
    channel_lock: bool = False

    def __post_init__(self) -> None:
        """
        Validate dataclass arguments at end of initialization

        Args:
            N/A

        Returns:
            None

        Raises:
            ScrapliValueError: if invalid channel_log_mode provided

        """
        if self.channel_log_mode.lower() not in (
            "write",
            "append",
        ):
            raise ScrapliValueError(
                f"provided channel_log_mode '{self.channel_log_mode}' is not valid, mode must be "
                f"one of: 'write', 'append'"
            )

        if self.channel_log_mode.lower() == "write":
            self.channel_log_mode = "w"
        else:
            self.channel_log_mode = "a"

__post_init__() -> None

Validate dataclass arguments at end of initialization

Returns:

Type Description
None

None

Raises:

Type Description
ScrapliValueError

if invalid channel_log_mode provided

Source code in channel/base_channel.py
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
def __post_init__(self) -> None:
    """
    Validate dataclass arguments at end of initialization

    Args:
        N/A

    Returns:
        None

    Raises:
        ScrapliValueError: if invalid channel_log_mode provided

    """
    if self.channel_log_mode.lower() not in (
        "write",
        "append",
    ):
        raise ScrapliValueError(
            f"provided channel_log_mode '{self.channel_log_mode}' is not valid, mode must be "
            f"one of: 'write', 'append'"
        )

    if self.channel_log_mode.lower() == "write":
        self.channel_log_mode = "w"
    else:
        self.channel_log_mode = "a"