Difference between revisions of "Python/netrc"

From mn/geo/geoit
Jump to: navigation, search
Line 1: Line 1:
The netrc module can be a nice way to store credentials securely:
+
The netrc module is a nice way to store credentials securely:
  
 +
First create a <code>~/.netrc </code> file in your home directory. Include the following:
  
 
<source lang='py'>
 
<source lang='py'>
  
import netrc
+
machine smtp.gmail.com
 
+
        username your_username
HOST = 'smtp.gmail.com'
+
        password your_password
secrets = netrc.netrc()
 
username, account, password = secrets.authenticators( HOST )
 
 
</source>
 
</source>
  
 +
Make sure that the file is properly protected with the appropriate permissions.
  
Then in your ~/.netrc file include the following:
+
Then in your python script, to access the username and password simply:
  
 
<source lang='py'>
 
<source lang='py'>
  
machine smtp.gmail.com
+
import netrc
        username your_username
+
 
        password your_password
+
HOST = 'smtp.gmail.com'
 +
secrets = netrc.netrc()
 +
username, account, password = secrets.authenticators( HOST )
 
</source>
 
</source>
  
 
+
and you're set! You can easily call the netrc settings from any python script.
Make sure the mode is safe on the .netrc file, and you're set! You can easily call the netrc settings from any python script.
 

Revision as of 16:25, 7 June 2012

The netrc module is a nice way to store credentials securely:

First create a ~/.netrc file in your home directory. Include the following:

machine smtp.gmail.com
        username your_username
        password your_password

Make sure that the file is properly protected with the appropriate permissions.

Then in your python script, to access the username and password simply:

import netrc

HOST = 'smtp.gmail.com'
secrets = netrc.netrc()
username, account, password = secrets.authenticators( HOST )

and you're set! You can easily call the netrc settings from any python script.