Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python netrc 모듈로 .netrc 파일 읽는 방법

Python의 netrc 클래스는 Unix 시스템에서 사용자 홈 디렉터리에 위치한 .netrc 파일을 읽어오는 데 사용됩니다. 이 파일은 숨김 파일로, 사용자의 로그인 자격 증명(호스트별 계정 이름과 비밀번호)이 담겨 있으며, ftp나 curl 같은 네트워크 도구들이 별도의 입력 없이 자동으로 인증을 수행할 수 있도록 도와줍니다.

netrc.authenticators() 메서드는 지정한 원격 호스트에 대한 인증 정보를 튜플 형태로 반환합니다. 반환되는 튜플은 순서대로 (로그인 이름, 계정 비밀번호, 사용자 비밀번호) 세 가지 값을 담고 있으며, 해당 호스트에 대한 항목이 존재하지 않으면 None을 반환합니다.

아래 예제는 Python의 netrc 모듈을 사용해 .netrc 파일을 읽고 저장된 인증 정보를 출력하는 방법을 보여줍니다.

예제 코드

import netrc

netrc = netrc.netrc()
remoteHostName = "hostname"
authTokens = netrc.authenticators(remoteHostName)

# 접근 토큰 출력
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]))

# 매크로 사전 출력
macroDictionary = netrc.macros
print(macroDictionary)

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

실행 결과

Remote Host Name:hostname
User Name at remote host:xxx
Account Password: XXX
Password for the user name at remote host:XXXXXX

참고 사항

netrc.macros 속성은 매크로 정의를 담는 사전(dictionary)으로, 일반적으로 .netrc 파일에 매크로가 정의되어 있지 않으면 빈 사전이 반환됩니다. 또한 보안상의 이유로 .netrc 파일은 소유자만 읽고 쓸 수 있도록 권한을 설정하는 것이 좋습니다.