簡體   English   中英

如何使用Unix pass命令行程序使用Python自動設置密碼

[英]How can I use Python to automate setting a password using the Unix pass command line program

我正在嘗試使用Unix pass程序自動設置新密碼。 我知道有一個Python庫pexpect可能會有所幫助,但我想避免使用第三方庫。

使用終端時,流程如下所示:

$ pass insert --force gmail
>> Enter password for gmail: <type in password using masked prompt>
>> Retype password for gmail: <reenter password>

我想要我的功能做什么:

  1. 運行命令pass insert --force {entry_name}
  2. 捕獲輸出(並回顯以進行測試)
  3. 檢查輸出中是否存在“ gmail密碼”,如果為True
    • 在標准輸入上寫“ {password} \\ n”
    • 再次將'{password} \\ n'寫入標准輸入
  4. 回顯任何錯誤或消息以進行測試

問題:

我被困在第2步。子進程無限期掛起,錯誤超時或不產生任何輸出。

嘗試次數:

  • 我已經嘗試使用stdin.write()和communication()來配置Popen()。
  • 我在各個點設置了wait()調用。
  • 我已經嘗試了shell = True和shell = False選項(出於安全原因,最好選擇False)

代碼

def set_pass_password(entry_name, password):
    from subprocess import Popen, PIPE

    command = ['pass', 'insert', '--force', entry_name]

    sub = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)

    # At this point I assume that the command has run, and that there is an "Enter password..." message
    message = sub.stdout.read()  # also tried readline() and readlines()
    print(message) # never happens, because process hangs on stdout.read()

    if 'password for {}'.format(entry_name) in message:
        err, msg = sub.communicate(input='{p}\n{p}\n'.format(p=password))
        print('errors: {}\nmessage: {}'.format(err, msg))

編輯:最初的答案是關於passwd ,它是用來設置密碼的。 后來我注意到您使用pass ,這是一個密鑰庫(實際上並沒有更改Unix密碼)。 如果stdin不是tty, pass程序的工作方式有所不同,並且不會顯示提示。 因此,以下非常簡單的程序可以工作:

def set_pass_password(entry_name, password):
    from subprocess import Popen, PIPE

    command = ['pass', 'insert', '--force', entry_name]

    sub = Popen(command, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE)

    err, msg = sub.communicate(input='{p}\n{p}\n'.format(p=password))
    print('errors: {}\nmessage: {}'.format(err, msg))

if __name__ == "__main__":
    set_pass_password("ttt", "ttt123asdqwe")

(如果命令成功,您將看到stderr和stdout均為空)。

對於passwd命令:

僅供參考: passwd命令將提示輸出到stderr ,而不是stdout

注意:您可能需要等待第二個提示,然后才能再次發送密碼,而不是在同一“寫”中兩次發送密碼。

對於這種簡單的情況,與您的代碼相似的代碼應該可以工作,但是通常您應該在所有管道上使用select並在另一側准備好時發送/接收數據,因此不會出現死鎖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM