【问题标题】:How to get the actual shell prompt string in Python?如何在 Python 中获取实际的 shell 提示字符串?
【发布时间】:2013-09-30 14:38:11
【问题描述】:

我有一个 Python 例程,它调用某种 CLI(例如 telnet),然后在其中执行命令。问题是有时 CLI 拒绝连接并且在主机 shell 中执行命令会导致各种错误。我的想法是在调用 CLI 后检查 shell 提示符是否改变。

问题是:如何在Python中获取shell提示字符串?

回显 PS1 不是一个解决方案,因为某些 CLI 无法运行它并且它返回一个类似符号的字符串而不是实际提示:

SC-2-1:~ # echo $PS1
\[\]\h:\w # \[\]

编辑

我的日常:

def run_cli_command(self, ssh, cli, commands, timeout = 10):
    ''' Sends one or more commands to some cli and returns answer. '''
    try:
        channel = ssh.invoke_shell()
        channel.settimeout(timeout)
        channel.send('%s\n' % (cli))
        if 'telnet' in cli:
            time.sleep(1)
        time.sleep(1)
        # I need to check the prompt here
        w = 0
        while (channel.recv_ready() == False) and (w < timeout):
            w += 1
            time.sleep(1)
        channel.recv(9999)
        if type(commands) is not list:
            commands = [commands]
        ret = ''
        for command in commands:
            channel.send("%s\r\n" % (command))
            w = 0
            while (channel.recv_ready() == False) and (w < timeout):
                w += 1
                time.sleep(1)
            ret += channel.recv(9999) ### The size of read buffer can be a bottleneck...
    except Exception, e:
        #print str(e) ### for debugging
        return None
    channel.close()
    return ret

这里需要解释一下:ssh 参数是一个 paramiko.SSHClient() 实例。我使用此代码登录服务器,然后从那里调用另一个 CLI,它可以是 SSH、telnet 等。

【问题讨论】:

    标签: python shell prompt paramiko


    【解决方案1】:

    我建议发送将 PS1 更改为已知字符串的命令。当我使用 Korn shell 脚本中的 Oracle sqlplus 作为协进程时,我已经这样做了,以知道何时结束从我发出的最后一条语句读取数据/输出。所以基本上,你会发送:

    PS1='end1>'; command1
    

    然后你会阅读行,直到你看到“end1>”(为了更加方便,在 PS1 的末尾添加一个换行符)。

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 2014-06-15
      • 2016-02-22
      • 1970-01-01
      相关资源
      最近更新 更多