Introduction to .netrc file
A .netrc file is used in Unix like operating systems primarily for two purposes:
To Define login credentials that can be used by commands and tools like ftp, curl and so on.
To Define macros that automates the file uploads
The .netrc is a hidden file and the default location of the .Netrc file is the $HOME directory.
.netrc file Introduction
Login Credentials
Login credentials to a host is specified in the format given below:
machine <HostName> login <UserName> password <password>
HostName - Name of the remote host
UserName - The user name of the login
password - Password of the user
e.g., machine mymacmachine.com login john password accessplease
Macro Definitions
macdef macro_upload cd /repository bin put todaysbuild.gz quit
Once login is complete, the above line will, change the directory to /repository and copy the file todaysbuild.gz into the directory.
Processing .netrc file using Python
As mentioned in the Introduction, the .netrc file is used by tools like ftp, curl and others.
Python provides a parser implementation to help parse the .netrc file through the netrc class.
.netrc file reader Example using Python
#import the netrc module
import netrc
netrc = netrc.netrc()
remoteHostName = "mymacmachine.com"
authTokens = netrc.authenticators(remoteHostName)
# Print the access tokens for a specific account
print("Remote Host Name:%s"%(remoteHostName))
print("User Name at remote host:%s"%(authTokens[0]))
print("Account Password:%s"%(authTokens[1]))
print("Password for the user name at remote host:%s"%(authTokens[2]))
# print the macros present in the .netrc file
macroDictionary = netrc.macros
print(macroDictionary)Output of the .netrc file reader Example
Remote Host Name:mymacmachine.com
User Name at remote host:john
Account Password:None
Password for the user name at remote host:accessplease
{'macro_upload': ['cd /repository bin put todaysbuild.gz quit\n']}