Bash

使用 .netrc 文件的 CURL 請求

  • October 28, 2021

我正在嘗試編寫一個腳本,它將憑據保存到 .netrc 文件中,然後從文件中讀取,以便將它們傳遞給 curl 命令並保存返回的 cookie 文件以供將來使用。我很感興趣,如果這是傳遞使用者名和密碼的安全方式,如果中間有人攻擊,如果我試圖訪問的伺服器是通過 HTTP 訪問的,他們是否能夠嗅探憑據。

#!/bin/bash

IP="192.168.0.1"
user="Administrator"
pass="Password1234"

function credentials {
   mkdir "${HOME}"/.netrc
   rm "${HOME}"/.netrc/credentials.txt
   touch "${HOME}"/.netrc/credentials.txt
   { echo "machine ${IP}"; echo "login ${user}"; echo "password ${pass}"; } >> "${HOME}"/.netrc/credentials.txt
   chmod 600 "${HOME}"/.netrc/credentials.txt
}

function cookie {
   curl -v -c cookie.txt -n "${HOME}"/.netrc/credentials.txt http://"${IP}"/setup.php
}

credentials
cookie

我檢查了credentials.txt文件正確保存在相應的目錄中,並且憑據具有正確的權限,但是當我嘗試執行cookie函式時,出現以下錯誤:Couldn't find host 192.168.0.1 in the .netrc file; using defaults. 為什麼 curl 無法從 credentials.txt 文件中獲取配置的使用者名和密碼?

據我了解(curl 的)手冊頁,該選項-n僅啟用查找.netrc文件,但它不期望該文件的文件路徑。這是選項--netrc-file。從手冊頁:

--netrc-file
  This option is similar to --netrc, except that you provide the 
  path (absolute or relative) to the netrc file that Curl should use. 
  You can  only  specify one netrc file per invocation. If several 
  --netrc-file options are provided, only the last one will be used.       
  (Added in 7.21.5)

  This option overrides any use of --netrc as they are mutually 
  exclusive.  It will also abide by --netrc-optional if specified.

引用自:https://unix.stackexchange.com/questions/428260