【问题标题】:Make python3 program press "enter" multiple times让python3程序按“回车”多次
【发布时间】:2019-03-11 18:33:48
【问题描述】:

我在我的公司使用 OpenVPN,并正在尝试自动化用户创建过程。我现在面临的证书生成步骤存在问题。当试图为用户构建一个密钥(所有参数都是预定义的)时,程序必须多次按 Enter,最后按“y”和“Enter”2 次。我尝试使用 Popen 和 PIPE,但到目前为止没有运气。希望有任何见解。

import sys, os
from subprocess import Popen, PIPE
# Generate an .ovpn file

try:
    username = sys.argv[1]
except:
    print "Error. Supply a username!"
    sys.exit()

print("Adding user")
os.system("useradd" + " -m" + " -s" + " /bin/bash" + username)
print("Sourcing vars")
os.system('source + /home/myuser/openvpn-ca/vars')
enter = Popen(['/home/myuser/openvpn-ca/build-key {}'.format(username)]), 
stdin=PIPE, shell=True)
enter.communicate(input='\n')

编辑:

这与它被标记为[重复]的不同。原因如下:

我不需要生成自定义证书,更改任何值等。它只需要多次按“Enter”并输入“yes”和“Enter”两次。

【问题讨论】:

  • 我自己没试过这个,但是如果你把time.sleep(x)放在enter.communicate(input='\n')s之间会发生什么,x是几秒钟的睡眠时间?
  • 它会引发错误。 ./pkitool 未找到,/home/myuser/whichopensslcnf:未找到。此外,子进程在通信和 _stdin_write 中引发错误。
  • 你的代码只提供一个换行符,如果你放两个会发生什么?这可能是另一个问题的重复,尽管此时我不愿意重新打开它,因为它还不清楚。你能否请edit你的问题指出如果你放两个换行符会发生什么,如果客户端程序需要它,它们之间会暂停?
  • 它返回:./pkitool: 293: can't shift that many waiting for the time of I provided and the exits

标签: python linux openvpn


【解决方案1】:

你不能source来自 Python 的 shell 脚本;或者更确切地说,你可以,但它只会启动一个新的子进程,sources 某事然后消失,而不会更改 Python 环境或后续子进程中的任何内容。

试试这样的:

import sys
import logging   # to get diagnostics on standard error instead
import subprocess

# Maybe switch to level=logging.WARNING once you are confident this works
logging.basicConfig(level=logging.INFO, format='%(module)s:%(asctime)s:%(message)s')

try:
    username = sys.argv[1]
except:
    logging.error("Error. Supply a username!")
    sys.exit()

logging.info("Adding user")
subprocess.run(["useradd", "-m", "-s", "/bin/bash", username],
    check=True, universal_newlines=True)
logging.info("Building key")
subprocess.run('''
        source /home/myuser/openvpn-ca/vars
        /home/myuser/openvpn-ca/build-key {}'''.format(username),
    shell=True, check=True, input='\n\n', universal_newlines=True)

切换到subprocess.run() 需要相当新的 Python 3 版本。在旧版本中,subprocess.check_call() 会做大致相同的事情,但没有 input= 参数,所以你确实必须使用基本的Popen()。

补充说明:

  • source 后面的加号明显是语法错误
  • 我们始终使用check=True 来确保 Python 检查命令是否成功完成。
  • 将os.system() 与subprocess 混合不是错误,但肯定是一种可疑的代码气味。

(更多)关于在 U*x 上使用 subprocess 的更多信息:https://stackoverflow.com/a/51950538/874188

【讨论】:

  • 感谢您的链接!我以前从未想过使用子进程。我看不到在签署证书提示时多次按“Enter”的部分。这就是我很好奇的一段代码。
  • input='\n\n' 将两个换行符作为标准输入传递给子进程。如果它不盲目接受标准输入,你需要pexpect之类的东西。
猜你喜欢
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多