Python how to read output from pexpect child?

后端 未结 6 1792
攒了一身酷
攒了一身酷 2020-12-29 22:51
child = pexpect.spawn (\'/bin/bash\')
child.sendline(\'ls\')
print(child.readline())
print child.before, child.after

All I get with this code in my

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 23:07

    #!/usr/bin/env python
    
    import pexpect
    child = pexpect.spawn("ssh root@172.16.0.120c -p 2222")
    child.logfile = open("/tmp/mylog", "w")
    child.expect(".*assword:")
    child.send("XXXXXXX\r")
    child.expect(".*\$ ")
    child.sendline("ls\r")
    child.expect(".*\$ ")
    

    go to open your logfile:- go to terminal

    $gedit /tmp/mylog
    

    As Per https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class

    # In Python 3, we'll use the ``encoding`` argument to decode data
    # from the subprocess and handle it as unicode:
     child = pexpect.spawn('some_command', encoding='utf-8')
     child.logfile = sys.stdout
    

提交回复
热议问题