Python3 實現自動SSH登錄,並記錄登錄結果

前段時間處理一個SSH登錄時隨機被拒的故障,測試時需要人工不斷的SSH登錄很是麻煩。故編寫如下腳本,用於自動多次SSH登錄,當登錄成功後在linux服務器執行data命令返回系統當前時間;並分別記錄其次數,代碼如下:

import paramiko
import time

#ssh登錄服務器 192.168.162.140 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
t = 0
bad = 0
for _ in range(1000):                                                     #登錄1000次
    t += 1
    time.sleep(0.5)                                                      #登錄間隔0.5S
    try:
        ssh.connect('192.168.162.140', username = 'root', password='test123',port='22') #輸入用戶名密碼及端口號
        cmd = 'date'                                                    #登錄成功後執行 date命令獲取服務器當前時間
        stdin,stdout,stderr = ssh.exec_command(cmd)
        print('Seq %d: linux time is: ' %t + str(stdout.read()) )
        ssh.close()                                                     #關閉當前ssh會話
    except:
        bad += 1
        print('error:         ',t,' ',datetime.datetime.now())          #如果登錄失則記錄客戶端當前時間和失敗序號
print('try %d times, fail times: %d, fail rate is %0.2f' %(t,bad,bad/t))

測試結果:

Seq 1: linux time is: b'Mon Feb 10 11:40:23 PST 2020\n'
Seq 2: linux time is: b'Mon Feb 10 11:40:24 PST 2020\n'
Seq 3: linux time is: b'Mon Feb 10 11:40:25 PST 2020\n'
Seq 4: linux time is: b'Mon Feb 10 11:40:25 PST 2020\n'
Seq 5: linux time is: b'Mon Feb 10 11:40:26 PST 2020\n'
Seq 6: linux time is: b'Mon Feb 10 11:40:27 PST 2020\n'
Seq 7: linux time is: b'Mon Feb 10 11:40:27 PST 2020\n'
Seq 8: linux time is: b'Mon Feb 10 11:40:28 PST 2020\n'
Seq 9: linux time is: b'Mon Feb 10 11:40:29 PST 2020\n'
Seq 10: linux time is: b'Mon Feb 10 11:40:30 PST 2020\n'
try 10 times, fail times: 0, fail rate is 0.00
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章