我们的“共享”服务器上有一些奇怪的设置,在某些情况下我不会记住我的git密码。我努力解决真正的问题;但在某些时候我放弃并创建了这个python脚本:
#!/usr/bin/env python3
"""
pass4worder: a simply python script that runs a custom command; and "expects" that command to ask for a password.
The script will send a custom password - until the command comes back with EOF.
"""
import getpass
import pexpect
import sys
def main():
if len(sys.argv) == 1:
print("pass4worder.py ERROR: at least one argument (the command to run) is required!")
sys.exit(1)
command = " ".join(sys.argv[1:])
print('Command to run: <{}>'.format(command))
password = getpass.getpass("Enter the password to send: ")
child = pexpect.spawn(command)
print(child.readline)
counter = 0
while True:
try:
expectAndSendPassword(child, password)
counter = logAndIncreaseCounter(counter)
except pexpect.EOF:
print("Received EOF - exiting now!")
print(child.before)
sys.exit(0)
def expectAndSendPassword(child, password):
child.expect("Password .*")
print(child.before)
child.sendline(password)
def logAndIncreaseCounter(counter):
print("Sent password ... count: {}".format(counter))
return counter + 1
main()
这个解决方案完成了这项工作;但我对这些印刷品的样子并不满意;例如:
> pass4worder.py git pull
Command to run: <git pull>
Enter the password to send:
<bound method SpawnBase.readline of <pexpect.pty_spawn.spawn object at 0x7f6b0f5ed780>>
Received EOF - exiting now!
b'Already up-to-date.\r\n'
我更喜欢这样的东西:
Already up-to-date
Received EOF - exiting now!
换句话说:我正在寻找一种方法,以便pexect简单地将所有内容“按原样”打印到stdout ......同时仍在执行其工作。
这可能吗?
(欢迎任何有关我的脚本的其他提示)
答案 0 :(得分:2)
child.readline
是一个函数,因此我认为您确实需要print(child.readline() )
。print(child.before)
更改为print(child.before.decode() )
。 bytes.decode()
将bytes
(b'string'
)转换为str
。