我正在开发一个备份守护进程,它将在后台静默运行。守护进程依赖于duplicity
备份软件,备份时需要加密密钥。我不能通过控制台询问密码,因为很明显,守护进程无法访问密码。
如何轻松创建一个提示,要求用户输入密码,并将其返回给应用程序(通过Python变量)?我正在使用 Python 2.7 。
答案 0 :(得分:21)
因为您要求最简单(Python 2.7):
import Tkinter, tkSimpleDialog
tkSimpleDialog.askstring("Password", "Enter password:", show='*')
对于Python 3.3:
import tkinter
tkinter.simpledialog.askstring("Password", "Enter password:", show='*')
对于Python 3.6 +:
import tkinter as tk
import tkinter.simpledialog
tk.Tk().withdraw()
tkinter.simpledialog.askstring("Password", "Enter password:", show='*')
答案 1 :(得分:4)
from Tkinter import *
def getpwd():
password = ''
root = Tk()
pwdbox = Entry(root, show = '*')
def onpwdentry(evt):
password = pwdbox.get()
root.destroy()
def onokclick():
password = pwdbox.get()
root.destroy()
Label(root, text = 'Password').pack(side = 'top')
pwdbox.pack(side = 'top')
pwdbox.bind('<Return>', onpwdentry)
Button(root, command=onokclick, text = 'OK').pack(side = 'top')
root.mainloop()
return password
答案 2 :(得分:3)
因为不是每个人都想使用TK,所以这里是使用PyQt的脚本:
from PyQt5.QtWidgets import QApplication, QInputDialog, QLineEdit
import sys
app = QApplication(sys.argv)
qd = QInputDialog()
qd.setTextEchoMode(QLineEdit.Password)
qd.show()
app.exec()
而且,因为你通常不会只是为了问一个用户输入密码:
#!/bin/env python3
#passwordPrompt.py
from PyQt5.QtWidgets import QApplication, QInputDialog
import sys, time
def succFunc():
sys.stdout.write(qd.textValue())
sys.stdout.flush()
exit(0)
def failFunc():
exit(1)
app = QApplication(sys.argv)
qd = QInputDialog()
#QLineEdit.Password
qd.setTextEchoMode(2)
qd.rejected.connect(failFunc)
qd.accepted.connect(succFunc)
qd.show()
app.exec()
相应的bash函数:
#!/bin/bash
passwordPrompt.py | tee
答案 3 :(得分:2)
解决了@ pycoder112358帖子的范围问题:
from tkinter import *
PASSWORD = ''
def get_passwd():
global PASSWORD
root = Tk()
pwdbox = Entry(root, show = '*')
def onpwdentry(evt):
global PASSWORD
PASSWORD = pwdbox.get()
root.destroy()
def onokclick():
global PASSWORD
PASSWORD = pwdbox.get()
root.destroy()
Label(root, text = 'Password').pack(side = 'top')
pwdbox.pack(side = 'top')
pwdbox.bind('<Return>', onpwdentry)
Button(root, command=onokclick, text = 'OK').pack(side = 'top')
root.mainloop()
return PASSWORD
答案 4 :(得分:2)
通过一些最小的内务管理来扩展迭戈的答案(没有这个,我试图使用他精美的简短例子让我崩溃):
import Tkinter, tkSimpleDialog
root = Tkinter.Tk() # dialog needs a root window, or will create an "ugly" one for you
root.withdraw() # hide the root window
password = tkSimpleDialog.askstring("Password", "Enter password:", show='*', parent=root)
root.destroy() # clean up after yourself!
这对于一个只是终端/控制台应用程序的程序来说效果很好。