您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

自動化產生 APNS PEM 檔案:用 expect 解決互動式密碼輸入

編輯:iOS 開發基礎

緣由

因為工作需要,我得大量產生 iOS 推送服務端使用的 PEM 檔案,一個個手動做實在煩死人了。梳理了一遍 PEM 的產生流程,發現牽涉到憑證匯出、產生與驗證,看似只能逐一手動處理。但仔細研究後發現,其中「把 P12 轉成 PEM」這一段其實很有自動化的空間。

這個轉換環節的難點在於需要互動式輸入密碼。如果寫成腳本,要怎麼讓它自動完成輸入?也就是把密碼寫進腳本,執行時自動填入。還真讓我找到了兩個好用的工具:expect 與 autoexpect。

先看 expect 的定位:Shell 雖然能寫簡單的控制流程,例如迴圈與條件判斷,但遇到需要互動的場合就必須人工介入。而當我們需要讓程式自動與 telnet 這類互動式程式溝通時,expect 就是為此而生。

那 autoexpect 又是什麼?手寫 expect 腳本其實挺累人的,autoexpect 能錄製並生成 expect 腳本,把自動化再往前推一層。

實作

Mac 本身內建 expect(用 expect -v 可以看到版本),但沒有 autoexpect。原因是系統附帶的這個 expect 比較精簡,用 brew install expect 安裝後就能拿到含 autoexpect 的完整版本。

本文 PEM 的產生流程主要參考〈iOS Push 憑證的重新生成〉一文,自動化對應的是「把兩個 .p12 轉成 .pem」之後的階段。

在 Terminal 下執行 autoexpect -p -f autoGeneratePEM.exp 即可開始錄製。錄製成功後產生的 autoGeneratePEM.exp 就是你需要的腳本,稍作修改就能使用。

以下是我錄下來的腳本,由於是錄製產物,難免有一些冗餘程式碼。

使用方式:

  1. 確認 cert.p12 與 key.p12 位於當前目錄
  2. 修改腳本中的 custompassword 為兩個 p12 的匯出密碼(這裡假設兩者相同),並把 customPemPassPhrase 改成自訂字串
  3. 執行時帶入 bundleid 參數,例如 ./autoGeneratePEM.exp com.test.123456,或 ./autoGeneratePEM.exp 123456
#!/usr/bin/expect -f
#
# This Expect script was generated by autoexpect
# Expect and autoexpect were both written by Don Libes, NIST.

set force_conservative 0  ;# set to 1 to force conservative mode

if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

set timeout -1
set bundleid [lindex $argv 0]
spawn $env(SHELL)
match_max 100000

expect -exact "bash-3.2$ "
send -- "openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12\r"
expect -exact "Enter Import Password:"
send -- "custompassword\r"

expect -exact "bash-3.2$ "
send -- "openssl pkcs12 -nocerts -out key.pem -in key.p12\r"
expect -exact "Enter Import Password:"
send -- "custompassword\r"
expect -exact "Enter PEM pass phrase:"
send -- "customPemPassPhrase\r"
expect -exact "Verifying - Enter PEM pass phrase:"
send -- "customPemPassPhrase\r"

expect -exact "bash-3.2$ "
send -- "openssl rsa -in key.pem -out key.unencrypted.pem\r"
expect -exact "Enter pass phrase for key.pem:"
send -- "customPemPassPhrase\r"

expect -exact "bash-3.2$ "
send -- "cat cert.pem key.unencrypted.pem > $bundleid.pem\r"

expect -exact "bash-3.2$ "
send -- "exit\r"
expect eof

參考資料

  • iOS Push 憑證的重新生成 — think12 的專欄
  • autoexpect 讓 expect 腳本更加簡單!
  • Where is the autoexpect command line tool on OSX Mountain Lion — Ask Different
  • Apple Push Notification Services in iOS 6 Tutorial: Part 1/2 — Ray Wenderlich
  • Shell 腳本學習之 expect 命令
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved