简体   繁体   中英

How can I get the pexpect's sendline('ls -l') print?

I use the pexpect to login the ssh server:

child = pexpect.spawn('ssh root@40.24.24.29')
child.expect('Password:')
child.sendline('admin123456#789')

child.sendline('ls -l')

there I want to receive the ls -l command's print.

how can I get the result to a variable?

pexpect has a special class for SSH sessions. See the docs

copy/paste below:

from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

If anyone runs into this issue and you're struggling to get any output at all, you can use echo to mark the end of output.

However, I've recently tried spawning the process as bash because someone on here supposed that its better when using multiple .sendline() during SSH sessions. Probably isn't critical but incase it is.

child = pexpect.spawn('bash')
#Now try to SSH using sendline()

Echo to mark the end

child.sendline('ls -l')
child.sendline('echo ENDSIGNALHERE')
child.expect_exact('ENDSIGNALHERE')
print(child.before)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM