python3:无法将控制台上的输出从程序从头到尾还原到文件。EOF问题



下面是我关于使用pexpect模块实现SSH登录功能的代码。

#!/usr/bin/env python
import pexpect
import sys
#use ssh to logon server
user="inteuser"           #username
host="146.11.85.xxx"      #host ip
password="xxxx"           #password
command="ls -l"           #list file on home/user directory
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
child.expect('password:')
child.sendline(password)
childlog = open('prompt.log',"ab")     # restore prompt log to file prompt.log
__console__ = sys.stdout               # make a backup of system output to console 
sys.stdout = childlog                  # print the system output to childlog
child.expect(pexpect.EOF)  
childlog.close() 
sys.stdout = __console__               # back to the original state of system output
print(child.before)                    # print the contents before match expect function

在我执行脚本后

[~/Liaohaifeng]$ python3 ssh_test.py
b' rntotal 69636rn-rw-rw-r-- 1 inteuser inteuser      949 Nov 28 02:01 
01_eITK_trtest01_CrNwid.logrn

[~/Liaohaifeng]$ cat prompt.log
total 69412
-rw-rw-r-- 1 inteuser inteuser      949 Nov 28 02:01 01_eITK_trtest01_CrNwid.log

当我删除脚本中的代码child.expect(pexpect.EOF)时,关于print(child.before)的输出可能是正确的(它应该在匹配之前打印内容password (

以下是我删除child.expect(pexpect.EOF)后的输出

[~/Liaohaifeng]$ python3 ssh_test.py
b"rn-------------------------------------------------------------------------------rn...
These computer resources are provided for authorized users only. For legal,
rn
security and cost reasons, utilization and access of resources are sxx, inrn
accordance with approved internal procedures, at any time if IF YOU ARE NOT AN AUTHORIZED USER; PLEASE EXIT IMMEDIATELY...rn "

我的目的是在执行脚本后将所有输出打印到一个文件中,但日志文件仍然只包含 list 目录的输出。那么为什么会这样呢?你能帮忙更新我的脚本吗?谢谢。

您可以使用

spawn().logfile_read .

[STEP 101] # cat example.py
import pexpect, sys
child = pexpect.spawn('bash --norc')
if sys.version_info[0] <= 2:
    # python2
    child.logfile_read = open('/tmp/pexpect.log', 'w')
else:
    # python3
    fp = open('/tmp/pexpect.log', 'w')
    child.logfile_read = fp.buffer
child.expect('bash-[.0-9]+[$#] ')
child.sendline('echo hello world')
child.expect('bash-[.0-9]+[$#] ')
child.sendline('exit')
child.expect(pexpect.EOF)
child.logfile_read.close()
[STEP 102] # python3 example.py
[STEP 103] # cat /tmp/pexpect.log
bash-4.4# echo hello world
hello world
bash-4.4# exit
exit
[STEP 104] #

这是一个简单的问题,只需调整代码顺序即可。

#!/usr/bin/env python
import pexpect
import sys
#use ssh to logon server
user="inteuser"           #username
host="146.11.85.xxx"      #host ip
password="xxxx"           #password
command="ls -l"           #list file on home/user directory   
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
childlog = open('prompt.log',"ab")
child.logfile = childlog
child.expect('password:')
child.sendline(password)                                  
child.expect(pexpect.EOF)  
childlog.close() 

最新更新