厂商新交付一批设备,给一个用户名密码,领导要求验证一下所有的机器是不是正常运行,用户名密码是不是正确,机房远在天边服务器数量又多,一个一个来肯定是不行的j_0004.gif



版本:Python2.7.9

模块:paramiko、multiprocessing

备注:默认使用root用户


#!/usr/bin/env python
# coding:utf-8

# 探测服务器存活率和密码
# 此脚本需要配合nmap使用,所以需要在linux环境下
# 运行结束后会在当前目录生成一个at_last文件里面记录列表中机器的探测信息


import os
import time
import  paramiko
import multiprocessing 

# 需要探测的服务器密码列表和ip地址列表
password = ['123456789', 'abcdefg', 'root111111', '111111', '123456']
ip_list = ['172.18.31.75', '172.18.31.76', '10.10.10.77', '10.10.31.80', '10.10.31.81', '172.18.31.82']
# ip地址列表可以使用循环生成,具体每个人的网段可能不一样,请自行修改代码

def file_write(filename, neirong):
    at = open(filename, 'a')
    at.write('%s \n' % neirong)
    at.close()


def network_test(ip):
    # 使用nmap测试网络的连通性
    sss = os.popen("nmap -sP %s|grep Host|grep up|awk '{print $3}'" % ip)
    sun = sss.read()
    if 'up' in sun:
        return True
    else:
        return False


def ssh_test(ip, password):
    # 测试当前密码是否可以连接服务器
    sun = False
    port = 22
    username = 'root'
    s = paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        s.connect(ip, port, username, password)
        s.close()
        sun = True
    except "Authentication":
        pass
    finally:
        return sun


def ssh_run(ip):  # 执行函数
    sun = 1
    if not network_test(ip):
        print "\033[1;31m%s\033[0m is no" % ip
        file_write("at_last", "%s ==>> no ==>> network" % ip)
    else:
        for i_in in password:
            if ssh_test(ip, i_in):
                print "%s is ok,password is %s" % (ip, i_in)
                file_write("at_last", "%s ==>> ok ==>> %s" % (ip, i_in))
                sun = 0
                break
        if sun == 1:
            file_write("at_last", "%s ==>> no ==>> password" % ip)
            print "\033[1;31m%s\033[0m is no" % ip


def sun_run(x):
    # 开启多线程运行 x代表最多开多少线程
    sun_pool = multiprocessing.Pool(processes=x)
    for i in ip_list:
        sun_pool.apply_async(ssh_run, (i,))
    sun_pool.close()
    sun_pool.join()


if "__main__" == __name__:
    sun_time_01 = int(time.time())
    sun_run(30)
    sun_time_02 = int(time.time())
    print "共耗时%s秒" % str(sun_time_02 - sun_time_01)