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

你可能感兴趣的:(Python,python,linux,ssh)