Python - 与另一个脚本共享 getpass() 输入?

标签 python linux

我正在尝试制作一个由多个模块组成的脚本,这些脚本需要 su/sudo,但我不想让用户每次都输入他们的密码,我只想询问一次并完成它。 (我也不想以明文形式存储密码,因为它旨在用于具有不同用户/密码的不同机器)

好的,这就是我到目前为止所做的,但我不断收到错误。我不确定它是否正确,我是 python 的新手。

在我的文件 main.py 中:

import getpass 
import subprocess

suStart = getpass.getpass("please enter your password")
suPass = suStart
subprocess.Popen(['python', 'test.py'])

在 test.py 中:

from manager import suPass
print suPass

当 main 调用 test 时,它尝试再次运行 getpass,我得到 IOError Errno 5。

我想我需要的是如何将 suStart 保存为它自己的字符串?我认为使用 suPass 可以做到这一点,但事实并非如此。

谢谢!

最佳答案

suPass 没有定义在test.py 的范围内,只有main.py。为了让 test.py 知道变量 suPass 你需要在初始化子进程时将它作为参数传入,因此,将它与 args 一起传入并更改 test.py 以反射(reflect)这一点:

from sys import argv

suPass = argv[1]    # we use the second index of argv, as the first index
                    # is actually the name of the script, test.py

print suPass

现在,在您的子进程调用中,将 suPass 添加到您的参数中:

subprocess.Popen(['python', 'test.py', suPass])

现在,如果您想以某种方式安全地存储此密码,您可以使用 hashlibbinasciios.urandom 生成一个密码哈希:

import hashlib
import binascii
from os import urandom
import getpass

salt = os.urandom(64) # where 64 can be any number of bytes, this is just
                      # a random bytes object for making the hash more secure
                      # make sure to keep it when checking a user's password input
                      # or the generated hash will not match!
# get a new password, and convert it to the bytes type to make it easier later
new_password = bytes(getpass.getpass('Enter a password: '), encoding='UTF-8')

# this code generates a bytes object using hashlib.pbkdf2_hmac and
# converts it to hexadecimal format with binascii.hexlify
new_hash = binascii.hexlify(hashlib.pbkdf2_hmac('sha512', new_password, salt, 100000)

print(new_hash)

new_hashsalt 可以保存到一个文件(或数据库,或其他存储介质),你可以在以后的某个时间加密用户的密码输入新程序,然后将哈希值与文件中存储的内容进行比较。

这是 Python Docs Example .

关于Python - 与另一个脚本共享 getpass() 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36625871/

相关文章:

python - 如何在Python中使用最大方差旋转?

python - 如果一个 python 模块说它依赖于 debhelper 和 cdbs,是否没有办法让它在非 debian linux 上运行?

python - EmailMultiAlternatives 的 Celery 错误

python - 正在为电影预告片搜寻IMDB?

python - 将 NULL 值插入 double 据类型 MySQL Python

java - 在 Linux (Servicemix) 下运行时在工作表上调用 autoSizeColumn 时崩溃

linux - bash 中的参数检查未正确测试

c - 使用虚拟地址读取Proc/[pid]/mem

linux - 使用 Mercurial 必须使用 Mercurial Server 吗?

python - 简单的正则表达式来查找两个单词