Python 2.7 : passing values to getpass

标签 python python-2.7

在Windows(特别是Win Server 2008 R2)上,我需要重复执行我们产品附带的现有Python脚本。该脚本的目的是偶尔被调用,并且输入预计是手动的。然而,我最终不得不调用这个脚本数百次。

因此,我尝试使用额外的 python 脚本自动调用此脚本(以及其他相关脚本)。我感到困惑的是,我调用的“开箱即用”脚本使用 getpass.getpass() 进行密码输入。

在我的自动化脚本中,我尝试使用 subrocess pipeline.communicate 将密码值传递给基本脚本。但我无法让它发挥作用。这是我的自动化脚本中的相关代码:

p = Popen(coreScriptCmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
x = p.stdout.readline().rstrip()
print x     #for debugging
x = p.communicate(args.pwd1+"\n"+args.pwd2)[0].rstrip()
print x     #for debugging

正如我所说,当被调用的子进程使用 getpass.getpass() 来请求输入时,这不起作用。这是核心代码中的 if 语句,我遇到了麻烦:

elif cmd == 'update-user':
if 'password1' not in globals():
    password1 = getpass.getpass(mgmtusername + " password:")
if 'dbpassword' not in globals():
    dbpassword = getpass.getpass(dbusername + " password:")
checkAccessDb(hostname, database, mgmtusername, password1, dbusername, dbpassword)

有人对如何以编程方式将值传递给下标中的 getpass() 有任何建议吗?

最佳答案

好吧,所以我不确定原始脚本是什么样的。但是,如果仍然需要从命令行使用它,我会推荐这样做。

我会修改原始脚本以接受参数。例如,假设 getpass 位于这样的函数内部......

def run_script():
    paswd = getpass.getpass("Please enter the password:")

尝试将其修改为如下内容:

def run_script(cmdlin = True):
    if cmdlin:
        paswd = getpass.getpass("Please enter the password:")
    else:
        # get password using another method

其他方法可以是您选择的任何方法,将其作为参数传递,从文件中获取它,等等......

一旦这样设置,只需将“cmdlin”参数传递为 false 即可调用它。

编辑:使用子流程模块,您应该能够使用 communicate将密码发送过来

另外,我找到了 pexpect可能对您的情况有所帮助的库

关于Python 2.7 : passing values to getpass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35612744/

相关文章:

python - 在 Python 3 中捕获 KeyError 消息

Python re.findall 正则表达式和文本处理

python - 使用Python启动WORD文档并直接跳转到特定部分

python - 如何查看python是否在控制台或shell中运行

python - numpy.where 与 like 运算符

python - 通过 Python 使用 Hadoop Streaming 中的文件

python - Python 3.x 中字符串的内部表示是什么

python-2.7 - 如何在Python中截取屏幕截图?

python-2.7 - Python ftplib 库不适用于 localhost

selenium - 位于 selenium 2.0 中检查 DOM 上元素是否存在的元素可见性的替代方案?