![](/img/trans.png)
[英]How can I automate a python program that requires two inputs in a linux command line?
[英]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>
我想要我的功能做什么:
pass insert --force {entry_name}
問題:
我被困在第2步。子進程無限期掛起,錯誤超時或不產生任何輸出。
嘗試次數:
代碼 :
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.