探測服務器存活率和密碼


廠商新交付一批設備,給一個用戶名密碼,領導要求驗證一下所有的機器是不是正常運行,用戶名密碼是不是正確,機房遠在天邊服務器數量又多,一個一個來肯定是不行的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)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章