欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python通過nmap掃描在線設(shè)備并嘗試AAA登錄(實(shí)例代碼)

 更新時(shí)間:2019年12月30日 09:16:45   作者:曹世宏  
這篇文章主要介紹了python通過nmap掃描在線設(shè)備并嘗試AAA登錄,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

如果管理網(wǎng)絡(luò)設(shè)備很多,不可能靠人力每天去登錄設(shè)備去查看是否在線。所以,可以利用python腳本通過每天掃描網(wǎng)絡(luò)中的在線設(shè)備??梢圆渴鹪诜?wù)器上做成定時(shí)任務(wù),每天發(fā)送AAA巡檢報(bào)告。

下面是我寫的一個(gè)python練手小程序。用來掃描一個(gè)網(wǎng)段中的在線主機(jī),并嘗試AAA去登錄。統(tǒng)計(jì)一個(gè)大網(wǎng)段內(nèi)可以成功aaa登錄的主機(jī)。

注意:

該程序只是測試小程序,還有些小bug需要解決。不是通用的程序。主要提供一個(gè)大致思路。

主要用到了python-nmap, paramiko庫。

程序大概思路:

  • 利用nmap掃描一個(gè)指定網(wǎng)段,只做ping掃描,所以前提所管理的設(shè)備中ping必須開啟。獲取存活設(shè)備IP列表。
  • 利用paramiko庫模擬ssh去登錄個(gè)IP,如果登錄成功,返回設(shè)備名稱,并及將設(shè)備名稱和對(duì)應(yīng)ip寫入文件。

代碼示例:

# -*- coding: utf-8 -*-

import nmap 
import datetime
import paramiko
import re

def get_name(host, user, password, port=22):
  client = paramiko.SSHClient()
  client.load_system_host_keys()
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  #client.connect(host, port, user, password, allow_agent=False, look_for_keys=False, timeout=5)
  try:
    client.connect(ip, port, user, password, allow_agent=False, look_for_keys=False, timeout=3)
  except Exception as err:
    return 0, str(err)
  #get shell
  ssh_shell = client.invoke_shell()

  dev_name = ''
  while True:
    line = ssh_shell.recv(1024)
    if line.endswith(b'>'):#華為 華三
      dev_name = re.findall(r'<(.*)>', str(line))[0]
      #dev_name = str(line)[3:-2]
      break
    if line.endswith(b'# ') | line.endswith(b'#'): #思科
      dev_name = re.findall(r'[\\r\\n|\\r]+(.*)#', str(line))[0]
      break
    if line.endswith(b'> '): 
      if 'ConnetOS' in str(line):#分流器
        dev_name =re.findall(r'[\\r\\n|\\r]+(.*)>', str(line))[0].strip()
      if '@' in str(line): #junpier防火墻
        dev_name =re.findall(r'@(.*)>', str(line))[0].strip()
      break
  #怎么跳出recv阻塞
  ssh_shell.close()
  return 1, dev_name


#print('掃描時(shí)間:'+res['nmap']['scanstats']['timestr']+'\n命令參數(shù):'+res['nmap']['command_line'])

def get_ip_list(hosts):
  nm = nmap.PortScanner()
  #nmap填入?yún)?shù)列表可以填很多
  res = nm.scan(hosts=hosts, arguments='-sn -PE')
  #count = res['nmap']['scanstats']['uphosts'] #存活的主機(jī)數(shù)
  return list(res['scan'].keys()) #存活主機(jī)IP地址

    
if __name__ == '__main__':
  start = datetime.datetime.now()
  user = 'user'
  password = 'password'
  hosts = '10.0.0.0/24'
  dev = {} #存放AAA登錄成功的主機(jī)
  f = open('ip_list.txt', 'w') #存放能ping通的IP
  ip_list = get_ip_list(hosts) 
  end = datetime.datetime.now()
  #f.write("存活的IP地址有:" + str(len(ip_list)) + "\n")
  #f.write("程序運(yùn)行時(shí)間:" + str(end-start) + '\n')
  for ip in ip_list:
    f.write(ip + '\n')
  f.close()
  #print(ip_list)
  login_failed_count = 0
  f1 = open('login_succeed.txt', 'w', encoding='utf-8')
  f2 = open('login_failed.txt', 'w', encoding='utf-8')
  f3 = open('mtil_add.txt', 'w', encoding='utf-8')
  #ip_list = ip_list.split('\n')
  for ip in ip_list:
    ok, dev_name = get_name(ip, user, password)
    if ok == 1:
      if dev_name not in dev.keys():
        vendor = '' 
        print(dev_name + "\t\t" + ip)
        if 'h' in dev_name[-12:]:
          vendor = 'h3c'
        elif 'c' in dev_name[-12:]:
          vendor = 'cisco'
        elif 'w' in dev_name[-12:]:
          vendor = 'huawei'
        else:
          vendor = 'unknow'
        f1.write(dev_name + '\t\t' + ip + '\t' + vendor + '\n')
        f1.flush()
        dev.update({dev_name : ip})
      else:
        f3.write(dev_name + '\t\t' + str(dev[dev_name]) + ' ' + ip +'\n')
        print(dev_name + '\t\t' + str(dev[dev_name]) + ' ' + ip +'\n')
        dev.update({dev_name: [dev[dev_name] , ip]})
        f3.flush()
    else:
      login_failed_count += 1
      print(dev_name)
      f2.write(dev_name + '\t\t' + ip + '\n')
      f2.flush()
  end = datetime.datetime.now()
  f1.write('AAA登錄成功' + str(len(dev)) +'臺(tái)\n' )
  f1.write('AAA登錄失敗' + str(login_failed_count) +'臺(tái)\n' )
  f1.write("程序運(yùn)行時(shí)間:" + str(end-start) +'\n')
  f1.close()
  f2.close()
  f3.close()
  
  print("程序運(yùn)行時(shí)間:" + str(end-start) +'\n')
  print("存活的IP地址有:" + str(len(ip_list)) + "\n")
  print("AAA登錄成功:" + str(len(dev)) + "\n")
  print('AAA登錄失敗' + str(login_failed_count) +'臺(tái)\n')

這個(gè)小程序例子,只是一個(gè)大概思路。

可以添加或則改善的思路:

  • 比想要獲取設(shè)備名,可以通過snmp,知道ip地址和snmp讀團(tuán)體名就可以直接獲取。
  • 可以將獲取到的數(shù)據(jù)存入數(shù)據(jù)庫中,從而可以做更的事情。
  • 通過類似代碼,也可以實(shí)現(xiàn)每天去設(shè)備上備份網(wǎng)絡(luò)配置等功能。
  • 可以將利用掃描結(jié)果,添加更多處理邏輯,生成每日巡檢日?qǐng)?bào),通過郵件或者短信發(fā)送。

nmap庫使用:

nmap工具使用可參考:nmap掃描工具學(xué)習(xí)筆記)

如果在windows上寫nmap庫,有兩個(gè)事要解決。

第一步:安裝nmap軟件

因?yàn)樵趐ython程序中,nmap包所調(diào)用的是nmap可執(zhí)行程序,所以必須先安裝nmap軟件。nmap下載地址: https://nmap.org/download.html

第二步: 需要在nmap庫中文件的init方法中添加的nmap.exe的路徑。

不然會(huì)報(bào)錯(cuò),提示找不到nmap。

在nmap.py的class PortScanner()中的__init__()中更改:

def __init__(self, nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap',r"D:\software\nmap-7.80\nmap.exe")):

主要添加了‘r”D:\software\nmap-7.80\nmap.exe”, nmap.exe可執(zhí)行文件路徑。

import nmap
nm = nmap.PortScanner()
#nmap填入?yún)?shù)列表可以填很多
res = nm.scan(hosts=hosts, arguments='-sn -PE')

其他使用示例:

#!/usr/bin/env python
import nmap # import nmap.py module
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
nm.scan('127.0.0.1', '22-443') # scan host 127.0.0.1, ports from 22 to 443
nm.command_line() # get command line used for the scan : nmap -oX - -p 22-443 127.0.0.1
nm.scaninfo() # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts() # get all hosts that were scanned
nm['127.0.0.1'].hostname() # get one hostname for host 127.0.0.1, usualy the user record
nm['127.0.0.1'].hostnames() # get list of hostnames for host 127.0.0.1 as a list of dict
# [{'name':'hostname1', 'type':'PTR'}, {'name':'hostname2', 'type':'user'}]
nm['127.0.0.1'].hostname() # get hostname for host 127.0.0.1
nm['127.0.0.1'].state() # get state of host 127.0.0.1 (up|down|unknown|skipped)
nm['127.0.0.1'].all_protocols() # get all scanned protocols ['tcp', 'udp'] in (ip|tcp|udp|sctp)
nm['127.0.0.1']['tcp'].keys() # get all ports for tcp protocol
nm['127.0.0.1'].all_tcp() # get all ports for tcp protocol (sorted version)
nm['127.0.0.1'].all_udp() # get all ports for udp protocol (sorted version)
nm['127.0.0.1'].all_ip() # get all ports for ip protocol (sorted version)
nm['127.0.0.1'].all_sctp() # get all ports for sctp protocol (sorted version)
nm['127.0.0.1'].has_tcp(22) # is there any information for port 22/tcp on host 127.0.0.1
nm['127.0.0.1']['tcp'][22] # get infos about port 22 in tcp on host 127.0.0.1
nm['127.0.0.1'].tcp(22) # get infos about port 22 in tcp on host 127.0.0.1
nm['127.0.0.1']['tcp'][22]['state'] # get state of port 22/tcp on host 127.0.0.1 (open

參考文檔:

https://pypi.org/project/python-nmap/

總結(jié)

以上所述是小編給大家介紹的python通過nmap掃描在線設(shè)備并嘗試AAA登錄,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • python提取頁面內(nèi)url列表的方法

    python提取頁面內(nèi)url列表的方法

    這篇文章主要介紹了python提取頁面內(nèi)url列表的方法,涉及Python操作頁面元素的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • 為什么黑客都用python(123個(gè)黑客必備的Python工具)

    為什么黑客都用python(123個(gè)黑客必備的Python工具)

    python支持功能強(qiáng)大的黑客攻擊模塊,而且Python提供多種庫,用于支持黑客攻擊,Python提供了ctypes庫, 借助它, 黑客可以訪問Windows、OS X、Linux等系統(tǒng)提供 DLL與共享庫,還有Python語言易學(xué)易用,這對(duì)黑客攻擊而言是個(gè)巨大的優(yōu)勢。
    2020-01-01
  • Python不同格式打印九九乘法表示例

    Python不同格式打印九九乘法表示例

    大家好,本篇文章主要講的是Python不同格式打印九九乘法表示例,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下哦,方便下次瀏覽
    2021-12-12
  • python中的split()函數(shù)和os.path.split()函數(shù)使用詳解

    python中的split()函數(shù)和os.path.split()函數(shù)使用詳解

    今天小編就為大家分享一篇python中的split()函數(shù)和os.path.split()函數(shù)使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 通過實(shí)例解析Python return運(yùn)行原理

    通過實(shí)例解析Python return運(yùn)行原理

    這篇文章主要介紹了通過實(shí)例解析Python return運(yùn)行原理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • Python 序列化和反序列化庫 MarshMallow 的用法實(shí)例代碼

    Python 序列化和反序列化庫 MarshMallow 的用法實(shí)例代碼

    marshmallow(Object serialization and deserialization, lightweight and fluffy.)用于對(duì)對(duì)象進(jìn)行序列化和反序列化,并同步進(jìn)行數(shù)據(jù)驗(yàn)證。這篇文章主要介紹了Python 序列化和反序列化庫 MarshMallow 的用法實(shí)例代碼,需要的朋友可以參考下
    2020-02-02
  • Python中使用Lambda函數(shù)的5種用法

    Python中使用Lambda函數(shù)的5種用法

    這篇文章主要介紹了Python中使用Lambda函數(shù)的5種用法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • Python?編程操作連載之字符串,列表,字典和集合處理

    Python?編程操作連載之字符串,列表,字典和集合處理

    這篇文章主要介紹了Python?編程操作連載之字符串,列表,字典和集合處理,文章圍繞主題相關(guān)資料展開詳細(xì)的內(nèi)容介紹,需要的朋友可參考一下下面文章內(nèi)容
    2022-06-06
  • 在Django同1個(gè)頁面中的多表單處理詳解

    在Django同1個(gè)頁面中的多表單處理詳解

    這篇文章主要給大家介紹了在Django同1個(gè)頁面中的多表單處理的相關(guān)資料,文章先給大家介紹了如何快速上手Django實(shí)現(xiàn)項(xiàng)目的方法,方便讓大家理解和學(xué)習(xí),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-01-01
  • 關(guān)于python的bottle框架跨域請(qǐng)求報(bào)錯(cuò)問題的處理方法

    關(guān)于python的bottle框架跨域請(qǐng)求報(bào)錯(cuò)問題的處理方法

    這篇文章主要介紹了關(guān)于python的bottle框架跨域請(qǐng)求報(bào)錯(cuò)問題的處理方法,需要的朋友可以參考下
    2017-03-03

最新評(píng)論