LoginSignup
16
22

More than 5 years have passed since last update.

Paramikoでコマンドの送信、結果の記録を自動で行う

Last updated at Posted at 2016-12-27

pythonでSSHやるならparamikoモジュールだと思いますが、なかなか使うのに苦労しました。

以下メモです。

ログの取り方

paramiko_log.py
import paramiko

#ログファイル名
LOG_FILE='log.txt'
R_HOST=''
R_HOST_USER=''
R_HOST_PASS=''

logger = paramiko.util.logging.getLogger()
paramiko.util.log_to_file(LOG_FILE)

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('R_HOST', username='R_HOST_USER', password='R_HOST_PASS', port=22, timeout=15.0,look_for_keys=False)
ssh.close()

リモートコマンドと結果の受け取り方(パスワード認証)

import paramiko

import time

R_HOST=''
R_HOST_USER=''
R_HOST_PASS=''
error_flg = False
msg = ''

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(R_HOST, username=R_HOST_USER, password=R_HOST_PASS, port=22, timeout=15.0,look_for_keys=False)

ssh_shell = ssh.invoke_shell()

time.sleep(3)

#データの受け取りができていなければエラーとして処理をする
if (ssh_shell.recv_ready()) and (not error_flg):
    msg += ssh_shell.recv(9999)
    msg += '\r\n'
else:
    print 'error'
    error_flg=True
    ssh.close()

#コマンドの送信
ssh_shell.send('ls \n')

time.sleep(3)

#データの受け取りができていなければエラーとして処理をする
if (ssh_shell.recv_ready()) and (not error_flg):
    msg += ssh_shell.recv(9999)
    msg += '\r\n'
else:
    print 'error'
    error_flg=True
    ssh.close()

#コマンドの送信
ssh_shell.send('last \n')

time.sleep(3)

#データの受け取りができていなければエラーとして処理をする
if (ssh_shell.recv_ready()) and (not error_flg):
    msg += ssh_shell.recv(9999)
    msg += '\r\n'
else:
    print 'error'
    error_flg=True
    ssh.close()

ssh.close()

説明程度なので簡単に書きましたが、エラー処理はちゃんとやるべきです。
途中のスリープも3秒待ちとかじゃなくて、プロンプトの入力待ち(’$’が末尾)で残りのデータが無いときに次の処理へ進むなどの処理をしてあげるといいと思います。あと、ssh.close()は必ず実行されるようにしたいですね。

16
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
22