简体   繁体   English

我怎样才能得到 pexpect 的 sendline('ls -l') 打印?

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

I use the pexpect to login the ssh server:我使用pexpect登录 ssh 服务器:

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.在那里我想接收ls -l命令的打印。

how can I get the result to a variable?我怎样才能得到一个变量的结果?

pexpect has a special class for SSH sessions. pexpect有一个特殊的 SSH 会话类。 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.如果有人遇到此问题并且您根本无法获得任何输出,则可以使用 echo 来标记输出的结束。

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.但是,我最近尝试将进程生成为 bash,因为这里有人认为在 SSH 会话期间使用多个.sendline()会更好。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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