Pexpect:无法写入logfi

2024-06-28 19:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

无法将pexpect.spawn实例的输入/输出记录到日志文件和sys.stdout中。 我正在编写一个函数“connect()”来生成到linux服务器的ssh连接。 从另一个函数get\u build()调用connect()函数。在创建bld\u server\u socket实例之后,我尝试将子对象的o/p记录到文件和标准o/p中。我在标准和文件上都没有看到任何订单

def connect(dev_ip, user, password):
    child = pexpect.spawn('ssh {}@{}'.format(user, self.dev_ip))

    tries = 0

    while tries < 5:


        i = child.expect(['[pP]assword:', '\(yes/no\)', ">", "[#$]", pexpect.EOF, pexpect.TIMEOUT])

        if i == 0:
            child.sendline(password)
        if i == 1:
            child.sendline('yes')
        if i == 2:
            child.sendline('enable')
        if i == 3:
            child.sendline('\n')
            break

        tries += 1
    print type(child)

    return child


def get_build(version, build_server_ip, mod):


    bld_server_socket = connect(build_server_ip, 'root', 'password')
    file = open('sshlog.txt', 'a')
    bld_server_socket.logfile = file
    bld_server_socket.logfile = sys.stdout

    bld_server_socket.expect('$')
    bld_server_socket.sendline('ls')

Tags: 文件函数buildipchildifserverconnect