简体   繁体   English

Python Pexpect pxssh获取退出状态

[英]Python Pexpect pxssh Getting the Exit Status

I am using pexpect to run a series of commands to a remote machine and would like to get the exit status of each command. 我正在使用pexpect对远程计算机运行一系列命令,并希望获取每个命令的退出状态。 However, when I try to retrieve the exit status I am getting the incorrect value. 但是,当我尝试检索退出状态时,我得到的值不正确。 Is there a way to get the correct exit status using pxssh from Pexpect? 有没有办法使用Pexpect的pxssh获取正确的退出状态? Here is the code I have tried along with the output. 这是我尝试与输出一起的代码。 The command was successful but the exit status given was 255 instead of 0. 命令已成功执行,但给出的退出状态为255,而不是0。

from pexpect import pxssh

try:
    s = pxssh.pxssh(timeout=30, maxread=2000000, options={
                    "StrictHostKeyChecking": "no",
                    "UserKnownHostsFile": "/dev/null"})
    hostname = 'my_hostname'
    username = 'username'
    password = 'my_pass'
    s.login (hostname, username, password, port=22, auto_prompt_reset=False)
    s.PROMPT = '*$'

    s.sendline('uptime')
    s.prompt()
    print(s.before.decode('utf-8'))
    s.close()
    print('s exitstatus=', s.exitstatus)

except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

Output: 输出:

 uptime
 09:10:39 up 10 days, 17:35,  4 users,  load average: 0.12, 0.18, 0.16

s exitstatus= 255

.exitstatus is the exit status of the ssh process. .exitstatusssh进程的退出状态。 See following example to see how to get the exit status of a command run in the ssh session: 请参见以下示例,以了解如何获取在ssh会话中运行的命令的退出状态:

>>> ssh = pxssh.pxssh()
>>> ssh.login('127.0.0.1', 'root', 'passwd')
True
>>> ssh.sendline('ls not-found')
13
>>> ssh.prompt()
True
>>> ssh.before
'ls not-found\r\nls: cannot access not-found: No such file or directory\r\n'
>>> ssh.sendline('echo $?')
8
>>> ssh.prompt()
True
>>> ssh.before
'echo $?\r\n2\r\n'
>>> ssh.before.split('\r\n')[1]
'2'        <-- This is the ls command's exit status
>>>

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

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