Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การประมวลผลไฟล์ netrc ด้วย Python


คลาส netrc ใน Python ใช้สำหรับอ่านข้อมูลจากไฟล์ .netrc ที่มีอยู่ในระบบ Unix ในไดเรกทอรี home ของผู้ใช้ ไฟล์เหล่านี้เป็นไฟล์ซ่อนที่มีรายละเอียดข้อมูลเข้าสู่ระบบของผู้ใช้ นี่เป็นประโยชน์สำหรับเครื่องมืออย่าง ftp, curl เป็นต้น เพื่ออ่านไฟล์ .netrc สำเร็จและใช้สำหรับการดำเนินการของพวกเขา

โปรแกรมด้านล่างแสดงวิธีที่เราสามารถอ่านไฟล์ .netrc โดยใช้โมดูล netrc ของ Python

ตัวอย่าง

import netrc
netrc = netrc.netrc()
remoteHostName = "hostname"
authTokens = netrc.authenticators(remoteHostName)
# Print the access tokens
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
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