Even after 25 years of working in tech, I still occasionally do an oops. In this case, I was working on a python script that communicated with Slack and I accidentally committed the Slack token to my repository(I had hard coded it into my app as a variable). Since I use a .netrc file for a few other things, I decided to see how difficult it would be to use it in my python script. Turns out, it is extremely easy.
The netrc module is included in the standard library, so no need to install it. Just import it like any other module.
import netrc
Since I have some scripts that use multiple secrets, I wrote a quick little function that will get the credentials based on the hostname (since it was for web APIs, I just put the name of the service as the hostname i.e. slack).
def get_credentials(hostname):
"""
Reads the .netrc file and returns the credentials
:param hostname: Hostname of the requested credentials
:return: Credentials
"""
n = netrc.netrc()
return n.authenticators(hostname)
Then I could set the host credentials as a list and then reference the variable when I need it in my script.
host_credentials = get_gredentials("slack")
host_credentials[0] # username
host_credentials[2] # password
Now I won’t have to worry so much about doing an oops.
Comments