需要pexpect模块的帮助
我编写了一个简单的代码,可以使用ssh从服务器克隆git存储库。 我面临几个问题。
密码以纯文本显示。
我不知道下载后退出程序的正确方法。它抛出了以下错误......
Traceback (most recent call last):
File "ToDelete3.py", line 65, in <module>
# # if i == 1:
File "ToDelete3.py", line 36, in getRepository
i = p.expect([ssh_key,'password:',pexpect.EOF])
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1492, in interact
self.__interact_copy(escape_character, input_filter, output_filter)
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1520, in __interact_copy
data = self.__interact_read(self.child_fd)
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1510, in __interact_read
return os.read(fd, 1000)
OSError: [Errno 5] Input/output error
我到目前为止编写的代码是:
command = 'git clone ssh://username@someserver/something.git'
ssh_key = 'Are you sure you want to continue connecting'
def gracefulExit():
print 'Password Incorrect !!!'
os._exit(1)
def getRepository():
p = pexpect.spawn(command,maxread=10000,timeout = 100)
p.logfile = sys.stdout # logs out the command
i = p.expect([ssh_key,'password:',pexpect.EOF])
if i == 0:
print 'Inside sshkey'
p.sendline('yes')
i = p.expect([ssh_key,'password:',pexpect.EOF])
if i == 1:
try:
p.sendline('mypassword') # this mypassword is shown in clear text on the console
p.interact()
p.logfile = sys.stdout
p.expect(pexpect.EOF)
except Exception,e:
print str(e)
gracefulExit()
if i == 2:
print 'Inside EOF block'
if p.isalive():
print '******************************************************'
print ' Closing the process of Download !!! '
print '******************************************************\n\n'
p.close()
任何投入都受到高度赞赏..
感谢。 -Vijay
答案 0 :(得分:3)
程序中的错误很少:
p.interact()
当我们想要在使用pexpect模块自动提供密码后取回控件时使用。您不需要使用它,因为您正在自动化整个存储库检出。
在传递密码后,还可以改进一些事情,设置无限超时,因为复制git存储库可能需要一段时间。
p.expect(pexpect.EOF, timeout=None)
之后,您可以使用以下命令
读取所有执行输出output_lines = p.before
output_lines_list = output_lines.split('\r\n')
for line in output_lines: print line
您也可以使用以上内容将输出记录到文件中
使用p.logifile = sys.stdout
并不好,因为它会从开始记录pexpect操作,包括传递密码。
此后无需关闭,您没有运行交互式程序。删除所有这些行:
if i == 2:
print 'Inside EOF block'
if p.isalive():
print '******************************************************'
print ' Closing the process of Download !!! '
print '******************************************************\n\n'
p.close()
问题在于您必须存储密码并将其与p.sendline一起使用。但是,如果存储密码,它将是不安全的。您也可以在开始时输入密码输入,这样您就不会在程序中存储密码,但这会使自动化失败。我没有看到出路,但是为了输入密码,你可以这样做:
import getpass
getpass.getpass("please provide your password")
答案 1 :(得分:0)
要删除对stdout回显的密码,请在重定向输出时使用以下命令 -
p.logfile_read = sys.stdout # logs out the command
我自己尝试了这个并且似乎正在工作。 Here是这个启示的参考。