Difference between revisions of "Python/netrc"

From mn/geo/geoit
Jump to: navigation, search
Line 3: Line 3:
 
First create a <code>~/.netrc </code> file in your home directory. Include the following:
 
First create a <code>~/.netrc </code> file in your home directory. Include the following:
  
<source lang='py'>
+
<source lang="py">
  
 
machine smtp.gmail.com
 
machine smtp.gmail.com
        username your_username
+
username your_username
        password your_password
+
password your_password
 
</source>
 
</source>
  
Line 14: Line 14:
 
Then in your python script, to access the username and password simply:
 
Then in your python script, to access the username and password simply:
  
<source lang='py'>
+
<source lang="py">
  
 
import netrc
 
import netrc
Line 25: Line 25:
 
and you're set! You can easily call the netrc settings from any python script.
 
and you're set! You can easily call the netrc settings from any python script.
  
Here's a helpful example of using the [smtp](http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/) tools in python.
+
Here's a helpful example of using the [smtp]([http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/ http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/]) tools in python.

Revision as of 10:24, 11 February 2015

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.

Here's a helpful example of using the [smtp](http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/) tools in python.