8

我正在开发一个将在后台静默运行的备份守护进程。守护进程依赖于duplicity备份软件,备份时需要加密密钥。我不能通过控制台询问密码,因为很明显,守护进程无权访问。

我怎样才能轻松地创建一个提示,要求用户输入密码,并将其返回给应用程序(通过 Python 变量)?我正在使用Python 2.7

4

5 回答 5

31

因为您要求最简单的(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='*')
于 2014-12-16T22:01:21.770 回答
5
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
于 2013-03-30T23:43:04.240 回答
5

因为不是每个人都想使用 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
于 2015-07-16T13:31:47.720 回答
3

解决了@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
于 2016-03-08T04:41:53.023 回答
3

用一些最少的家务来扩展 Diego 的答案(没有这个,我在尝试使用他精美的简短示例时遇到了大量的崩溃):

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!

这将适用于其他只是终端/控制台应用程序的程序。

于 2016-09-15T02:46:17.747 回答