簡體   English   中英

從 pexpect sendline 讀取輸出

[英]reading output from pexpect sendline

我有 pexpect 工作,但我在打印輸出時遇到問題。 在我下面的測試腳本中,它創建 ssh 連接,然后發送一個 sudo su -,然后是我的密碼,然后發送需要 sudo 訪問權限的行(我還添加了幾次 p.interact() 以確保它在根目錄下)。 我遇到的問題是返回我運行的命令的輸出。 最后,我想運行一些頂級命令、一些 du -h 和其他(更復雜的)空間命令。 但是目前當它嘗試打印 p.before 時,我得到:

Traceback (most recent call last):
File "./ssh.py", line 37, in <module>
print p.before()
TypeError: 'str' object is not callable

這是我正在使用的腳本(編輯以刪除我的通行證等)

#!/usr/bin/env python

import pexpect
import struct, fcntl, os, sys, signal

def sigwinch_passthrough (sig, data):
    # Check for buggy platforms (see pexpect.setwinsize()).
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # assume
    s = struct.pack ("HHHH", 0, 0, 0, 0)
    a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
    global global_pexpect_instance
    global_pexpect_instance.setwinsize(a[0],a[1])

ssh_newkey = 'Are you sure you want to continue connecting'
p=pexpect.spawn('ssh user@localhost')
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
    print "I say yes"
    p.sendline('yes')
    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
    print "I give password",
    p.sendline("mypassword")
elif i==2:
    print "I either got key or connection timeout"
    pass
elif i==3: #timeout
    pass
global global_pexpect_instance
global_pexpect_instance = p
p.sendline("sudo su -")
p.sendline("mypasswd")
p.sendline("mkdir /home/user/test")
print p.before

我正在使用此鏈接: http : //linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/

任何幫助深表感謝。

編輯:正如 Armin Rigo 在下面指出的那樣。 我正在調用 p.before 作為像 p.before() 這樣的函數。 我犯了一個愚蠢的錯誤,因為這解釋了為什么我今天遇到這個錯誤,而不是昨天我嘗試這個時。 在對我的腳本進行更改並修改正在發送的命令后,打印 p.before,並且不會返回任何輸出。 還有其他方法可以從 sendline() 命令返回輸出嗎?

使用日志文件,該日志文件將所有輸出存儲在終端中。使用該示例代碼:-

child = pexpect.spawn("ssh user@localhost")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("guest\r")
child.expect(".*\$ ")
child.sendline("python -V\r")

打開日志文件並查看終端事件中的所有內容

要在發送后使用child.read()獲取完整的輸出

例如

cmd_resp = pexpect.spawnu(cmd)    # for execution of the command
str_to_search = 'Please Enter The Password'
cmd_resp.sendline('yes')       # for sending the input 'yes'
resp = cmd_resp.expect([str_to_search, 'password:', EOF], timeout=30) # fetch the output status
if resp == 1:
   cmd_resp.sendline(password) 
   resp = cmd_resp.expect([str_to_search, 'outputString:', EOF], timeout=30)
   print(cmd_resp.read()) # to fetch the complete output log

p.before是一個字符串 - 不是一個函數。 要查看輸出,您必須編寫print p.before 希望這可以幫助你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM