How to filter stdout in python protocol

I use the "logging" library to log information and warning messages in my scripts, is there anyway I can filter passwords (I have several passwords and you want to replace them with asterisks) when printing in stdout

+4
source share
1 answer

To filter out specific words that are contained in your password list from the stream stdout(where the messages go logging.DEBUGand logging.INFO) and the stream stderr(where logging.WARNING, logging.ERRORand logging.CRITICAL), you can replace the original flows with a simple class that replaces critical words before they are written:

class PasswordFilter(object):
    def __init__(self, strings_to_filter, stream):
        self.stream = stream
        self.strings_to_filter = strings_to_filter

    def __getattr__(self, attr_name):
        return getattr(self.stream, attr_name)

    def write(self, data):
        for string in self.strings_to_filter:
            data = re.sub(r'\b{0}\b'.format(string), '*' * len(string), data)
        self.stream.write(data)
        self.stream.flush()

    def flush(self):
        self.stream.flush()

, :

top_secret_passwords = ['do not tell me', 'I am secret', 'important', 'foo',
                        'foobar']
sys.stdout = PasswordFilter(top_secret_passwords, sys.stdout)
sys.stderr = PasswordFilter(top_secret_passwords, sys.stderr)

:

# set up your logging after activating the filter, won't work otherwise
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug('You cannot see me anymore: {0}'.format(top_secret_passwords[0]))
logger.info('You cannot see me anymore: {0}'.format(top_secret_passwords[1]))
logger.warning('You cannot see me anymore: {0}'.format(top_secret_passwords[2]))
logger.error('You cannot see me anymore: {0}'.format(top_secret_passwords[3]))
logger.critical('You cannot see me anymore: {0}'.format(top_secret_passwords[4]))

:

DEBUG:__main__:You cannot see me anymore: **************
INFO:__main__:You cannot see me anymore: ***********
WARNING:__main__:You cannot see me anymore: *********
ERROR:__main__:You cannot see me anymore: ***
CRITICAL:__main__:You cannot see me anymore: ******
+1

Source: https://habr.com/ru/post/1625152/


All Articles