ある種の CLI (telnet など) を呼び出してコマンドを実行する Python ルーチンがあります。問題は、CLI が接続を拒否し、コマンドがホスト シェルで実行されて、さまざまなエラーが発生する場合があることです。私の考えは、CLI を呼び出した後にシェル プロンプトが変更されるかどうかを確認することです。
問題は、Python でシェル プロンプト文字列を取得するにはどうすればよいかということです。
一部の CLI では実行できず、実際のプロンプトではなく表記のような文字列が返されるため、PS1 をエコーすることは解決策ではありません。
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() インスタンスです。このコードを使用してサーバーにログインし、そこから SSH、telnet などの別の CLI を呼び出します。