Skip to content

Commit

Permalink
Remove SecretsFilter from log after disconnection
Browse files Browse the repository at this point in the history
A memory leak happens because a new 'SecretsFilter' is added to
the 'log' object every time a new 'BaseConnection' object is
initialized. Remove the filter when 'disconnect' is called.
  • Loading branch information
max-dw-i committed Jan 15, 2024
1 parent 1c75ca3 commit 6a0779c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 3 additions & 1 deletion netmiko/base_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,8 @@ def __init__(
if self.secret:
no_log["secret"] = self.secret
# Always sanitize username and password
log.addFilter(SecretsFilter(no_log=no_log))
self._secrets_filter = SecretsFilter(no_log=no_log)
log.addFilter(self._secrets_filter)

# Netmiko will close the session_log if we open the file
if session_log is not None:
Expand Down Expand Up @@ -2480,6 +2481,7 @@ def disconnect(self) -> None:
self.remote_conn = None
if self.session_log:
self.session_log.close()
log.removeFilter(self._secrets_filter)

def commit(self) -> str:
"""Commit method for platforms that support this."""
Expand Down
12 changes: 11 additions & 1 deletion tests/unit/test_base_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from os.path import dirname, join
from threading import Lock

from netmiko import NetmikoTimeoutException
from netmiko import NetmikoTimeoutException, log
from netmiko.base_connection import BaseConnection

RESOURCE_FOLDER = join(dirname(dirname(__file__)), "etc")
Expand Down Expand Up @@ -480,3 +480,13 @@ def test_strip_ansi_codes():

# code_next_line must be substituted with a return
assert connection.strip_ansi_escape_codes("\x1bE") == "\n"


def test_remove_SecretsFilter_after_disconnection():
connection = BaseConnection(
host="testhost", # Enter the hostname to pass initialization
auto_connect=False, # No need to connect for the test purposes
)
connection.disconnect()

assert not log.filters

0 comments on commit 6a0779c

Please sign in to comment.