なんかてきとうに

わりと個人的な忘備録的ですよ。

paramikoで対話型処理をしたい

python使ってNW機器のコンフィグバックアップとか、
いろんなデータ拾ったりとかを自動化できると便利ですよねぇ。

そんなわけで、やってみる。

環境 * Python 3.5.1 * paramiko 1.16.0

import paramiko

host='somehost'
username='someuser'
password='password'
password_e='password_e'

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host,username=username,password=password,look_for_keys=False,allow_agent=False)

stdin,stdout,stderr = client.exec_command('show arp\n')
for line in stdout:
    print(line)

こういうのは問題なくできますね。
最後3行の部分を

stdin,stdout,stderr = client.exec_command('enable\n')
for line in stdout:
    print(line)

みたいな。enable送ってpasswordが来たら……みたいなexpectでやるようなことをしようとしたら、 できない。
exec_commandが、コネクション開いて、メッセージ送信して、その結果をもらって、コネクションを閉じる。
という一連の作業をやってコネクション閉じちゃうからなんですよねぇ

コネクション開いてそのコネクション自体をもらう
invoke_shell()
というのが用意されていますが、これを使うと……

shell = client.invoke_shell()
shell.recv(1000)
shell.send('enable\n')
output=''
while True:
    output = output + shell.recv(1000).decode('utf-8')
    if(re.search('[Pp]assword',output)):
        output=''
        break
shell.send(passwd_e+'\n')
while True:
    output = output + shell.recv(1000).decode('utf-8')
    if(re.search('#',output)):
        output=''
        break
shell.send('term len 0\n')
while True:
    output = output + shell.recv(1000).decode('utf-8')
    if(re.search('#',output)):
        output=''
        break
shell.send('show start\n')
while True:
    output = output + shell.recv(1000).decode('utf-8')
    if(re.search('\nend',output)):
        print(output)
        output=''
        break

こういう、データ自分で待ち受けたりとかする作業が必要に。

これならParamikoあきらめてPexpectとかPexpectのpxssh使いたくなりますね。

もともとopensshクライアントではないものを使ってみたくて(速度とかどうなんだろう?と思って) Paramiko使ってるのになぁ

何かいい感じの方法ないんですかねえ