如何屏蔽用户密码输入并将其另存为输出,以替换另一个文件中的默认密码

时间:2019-01-24 10:43:36

标签: python python-3.x

我是python的新手,真的不知道如何正确地提出问题,请原谅我。

真正需要指导的是,我想让用户使用输入输入密码,而输出却被屏蔽为星号,并且用户输入将用于更改另一个文件信息(我在Windows上使用python 3 10)。

我知道我可以使用getpass.getpass()并将密码显示为星号是有风险的,因为它可以让其他人读取并计算密码的长度,但是由于我想让这个小应用看起来像“专业”,并允许用户感到安全,然后我看到需要屏蔽密码了。

最后,应保存输出以替换另一个文件基本信息,例如电子邮件,用户名和密码。

我成功替换了所有密码(密码除外),因为它仅将输入的密码(mynewpassword12345)更改为“”。

下面是我从SO获得的一些链接,据说与我的问题有关:

Masking user input in python with asterisks 接受的答案没有说明如何提供示例。

Getting paths as user input Python 3 这个公认的答案与我的问题无关。

Input only 3 characters and 3 asterisk 这个公认的答案也与我的问题无关。

Change EditText password mask character to asterisk (*) 这个接受的答案也与我的问题无关。

Partial Password Masking on Input Field 再次接受这个答案与我的问题无关。

Masking user input in python with asterisks 这个公认的答案与我的问题有关,但在Windows以外的平台上。

String to asterisk, masking password 同样,这些答案与我的问题无关。

word (password) displays in asterisks - Console application 再次接受这个答案与我的问题无关。

下面是示例代码示例,我是从SO答案中获得的,以将用户密码屏蔽为星号(但对不起,我忘记保存链接了。)。

它可以在python exe上运行(但不能在空闲状态下运行),并且将用户密码输入屏蔽为星号,但不允许我将打印的密码保存为用户输出。

到目前为止,这是我正在尝试做的事情,从certin文件夹中的某个路径中提取一个zip文件,提示用户输入并添加以更改默认信息,例如电子邮件,id等。

from zipfile import ZipFile
from selenium.webdriver.support.ui import WebDriverWait
import fileinput
import os
import py_compile
import shutil, glob
import textwrap
import datetime
import msvcrt
import time
import sys

script_dir = os.path.dirname(__file__)
file_path2 = os.path.join(script_dir, ' alert ' , 'temp' , 'temp folder' , 'temp' , 'myapp.zip')
##print(file_path2)
NameFile2 = file_path2

with ZipFile(NameFile2, 'r') as zf:
    zf.extractall(os.path.join(script_dir, 'alert' , 'temp' , 'temp folder' , 'temp' ) , pwd=b'mypassword' )

file_path = os.path.join(script_dir, ' alert ' , 'temp' , 'temp folder' , 'temp' , 'myapp.py')
##print(file_path)
NameFile = file_path


email = "emailaddress"
password = "userpassword"
userID = "userID"
id1 = "id1"
id2 = "id2"
id3 = "id3"
id4 = "id4"
id5 = "id5"
id6 = "id6"
id7 = "id7"
id8 = "id8"
id9 = "id9"
idlast = "idlast"

level = 3
##
x = datetime.datetime.now()
text1 = '''hi, welcome to my app.
'''
#print('\t' * level, text1 )
#print(textwrap.fill(text1, 60))

print(" ")


print((x.strftime("%c")).center(80))
print(" ")
for line in textwrap.wrap(text1, width=50):
    print(line.center(80))


print(" ")



newemail = input ("  email : " )

#newpassword = input ("  password : ")


list1 = []
def getPASS():
    print("Input password")
    list1 = []
    while True:
        char = msvcrt.getch()
        char =str(char)
        char = char[2:-1]
        if char == "\\n'" or char == "\\r":
            break
        elif char == "\\x08":
            del list1[-1]
            os.system("cls")
            print("Input password:")
            sys.stdout.write("*" * len(list1))
            sys.stdout.flush()
            continue
        else:
            list1.append(char)
            sys.stdout.write("*")
            sys.stdout.flush()
print("\n")
psw = "".join(list1)
print(psw)
invalid = ' ,:;/?"\}]{[-=+!@#$%^&*()|'
for x in psw:
    if x in invalid:
        print("Character %r is not allowed in password" % x)
        getPASS()
    else:
        pass

getPASS()

newpassword = psw

newuserID = input ("  userID : ")
newid1 = input ("  ID seefirst1 : ")
newid2 = input ("  ID seefirst2 : ")
newid3 = input ("  ID seefirst3 : ")
newid4 = input ("  ID seefirst4 : ")
newid5 = input ("  ID seefirst5 : ")
newid6 = input ("  ID seefirst6 : ")
newid7 = input ("  ID seefirst7 : ")
newid8 = input ("  ID seefirst8 : ")
newid9 = input ("  ID seefirst9 : ")
newidlast = input ("  ID seefirst10 : ")


with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(email, newemail), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(password, newpassword), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(userID, newuserID), end='')


with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id1, newid1), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id2, newid2), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id3, newid3), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id4, newid4), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id5, newid5), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id6, newid6), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id7, newid7), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id8, newid8), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(id9, newid9), end='')

with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(idlast, newidlast), end='')



#wait = WebDriverWait(driver, 10)

file_path3 = os.path.join(script_dir, ' alert ' , 'temp' , 'temp folder' , 'temp' , 'myapp.py')
#print(file_path3)
script = file_path3
py_compile.compile(script)




from pathlib import Path

# ...

#pathtofile = Path(__file__).parent.parent.parent.parent.parent  # Path to Folder myapp
pathtoduplicate = os.path.join(script_dir ,'myapp.cpython-37.pyc')
#print(pathtoduplicate)

if os.path.exists(pathtoduplicate):
  os.remove(pathtoduplicate)
else:
  print("The file does not exist")

##print(pathtofile) 

source_dir = os.path.join(script_dir, ' alert ' , 'temp' , 'temp folder' , 'temp' , '__pycache__') #Path to Pycache 
dst = os.path.join(script_dir) # Path to myapp
files = glob.iglob(os.path.join(source_dir, "*.pyc"))
for file in files:
    if os.path.isfile(file):
        shutil.move(file, dst)



raise SystemExit()

我得到了我希望输入显示为星号的结果,但是它没有改变输出,只显示“”,而不是实际密码。

想要的结果: 屏蔽的输入密码已替换为默认密码。

email = "mynewemail@gmail.com"  
password = "mynewpassword12345"          
user = "mynewnewid1"
seefirst1 = "newid1" 
seefirst2 = "newid2"  
seefirst3 = "newid3"  
seefirst4 = "newid4" 
seefirst5 = "newid5" 
seefirst6 = "newid6"  
seefirst7 = "newid7"  
seefirst8 = "newid8" 
seefirst9 = "newid9"  
seefirst10 = "newid10"  

不需要的结果: 屏蔽的输入密码未替换默认密码。

email = "mynewemail@gmail.com"  
password = ""          
user = "mynewnewid1"
seefirst1 = "newid1" 
seefirst2 = "newid2"  
seefirst3 = "newid3"  
seefirst4 = "newid4" 
seefirst5 = "newid5" 
seefirst6 = "newid6"  
seefirst7 = "newid7"  
seefirst8 = "newid8" 
seefirst9 = "newid9"  
seefirst10 = "newid10"

请帮助我解决此问题。我是菜鸟,对python真的很陌生。

2 个答案:

答案 0 :(得分:1)

不考虑您的方法的其他问题,我将集中讨论您的“不良结果:屏蔽的输入密码未替换默认密码。”

  1. 您有一个全局list1,并且在list1函数中也定义了一个getPASS(),您想在从函数返回后使用它。这无法按原样工作,因为函数中的list1是本地函数,与全局list1不同。我建议从函数e中返回一个适当的值。 g。:

    def getPASS():
        print("Input password")
        list1 = []
        while True:
            …
        return "".join(list1)
    
    …
    psw = getPASS()
    
  2. 密码输入和验证的逻辑在这里混杂在一起:

    psw = "".join(list1)
    print(psw)
    invalid = ' ,:;/?"\}]{[-=+!@#$%^&*()|'
    for x in psw:
        if x in invalid:
            print("Character %r is not allowed in password" % x)
            getPASS()
        else:
            pass
    
    getPASS()
    

    您甚至在致电getPASS()进行输入之前都尝试分配和验证密码,因此psw为空。重新排列,例如。 G。 (假设高于1.,请更改为getPASS()):

    while True:
        psw = getPASS()
        print(psw)  # only for debugging
        invalid = ' ,:;/?"\}]{[-=+!@#$%^&*()|'
        for x in psw:
            if x in invalid:
                print("Character %r is not allowed in password" % x)
                break   # from for x in psw
        else:
            break   # from while True
    

答案 1 :(得分:1)

感谢阿玛利爵士,在没有他的指导下无法解决这个问题。

下面是Armali爵士在他接受的答案上建议的我编辑的脚本的结果。(并且我不会接受我的回答被接受,仅供参考,以供对此部分感兴趣的人参考。)

var result = 5;
res.send({result}); //Iquivalent to { result: 5 }