gpt4 book ai didi

python - 如何在Python中获取实际的shell提示符字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:48 26 4
gpt4 key购买 nike

我有一个 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 等。

最佳答案

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

PS1='end1>'; command1

然后您将阅读各行,直到看到“end1>”(为了更加方便,请在 PS1 末尾添加换行符)。

关于python - 如何在Python中获取实际的shell提示符字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19097012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com