5

使用auth-source库读取Netrc文件中的用户名和密码

 3 years ago
source link: https://www.lujun9972.win/blog/2017/05/25/%E4%BD%BF%E7%94%A8auth-source%E5%BA%93%E8%AF%BB%E5%8F%96netrc%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用auth-source库读取Netrc文件中的用户名和密码

Netrc文件

Netrc文件常用于存储登陆主机时的用户名和密码,它的格式是这样的:

machine MYMACHINE login MYLOGINNAME password MYPASSWORD port MYPORT

可以看出,Netrc文件一共包含了4个域,其中:

  • MYMACHINE指明了登陆的主机IP或域名
  • MYLOGINNAME指明了登陆时用的用户名
  • MYPASSWORD指明了登陆时的密码
  • MYPORT则是连接时的端口号或者是协议名称

需要指出的是,所有这些域都是可选的,例如,你可以只写:

password MYPASSWORD

表示在任何情况下都使用 MYPASSWORD 作为密码.

Netrc文件一般是保存为 ~/.authinfo 或者 ~/.netrc 文件的。不过现在一般以 ~/.authinfo 居多。

最后,由于Netrc文件中是以明文的方式存储密码的,因此请一定确保Netrc文件的属性为600.

auth-source库

auth-source是一款Emacs自带的用于解析Netrc文件的库.

在使用auth-source之前,请确保要解析的Netrc文件的路径存在于变量 auth-sources 中。

auth-sources 是一个列表,里面存储了Netrc文件可能存在的各个路径,auth-source会一个个地尝试这些路径并解析第一个实际存在的Netrc. 它的默认值是 ("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")

设置好auth-source之后,就可以使用 (auth-source-user-and-password HOST &optional USER) 来获取登陆指定主机(和指定用户)所需要的用户名和密码了。 其返回一个list,其中第一个元素为登陆用户名,第二个元素为登陆密码。

若需要更灵活的查询,可以使用函数 auth-source-search, 不过一般情况下是不会直接用到这个函数的了,有兴趣的同学可以自己看一下它的doc-string。

下面是网络上的一个例子:

(use-package org2blog
  :ensure t
  :config
  ;; Experiments
  (require 'auth-source) ;; or nothing if already in the load-path

  (let (credentials)
    ;; only required if your auth file is not already in the list of auth-sources
    ;; Always keep config and username/password separated
    (add-to-list 'auth-sources "~/.authinfo")
    (setq credentials (auth-source-user-and-password "buildfunthings.com"))
    (setq org2blog/wp-blog-alist
          `(("bft"
             :url "https://www.buildfunthings.com/xmlrpc.php"
             :username ,(car credentials)
             :password ,(cadr credentials))))))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK