通过python收集内网资产地址

批量远程H3C交换机查询arp表,记录arp表中的IP地址,以此来收集内网资产IP。
交换机SSH账号密码文件命名py_sshinfo.xls,A列为IP,B列为账号,C列为密码,从第二行开始读取

import paramiko
import time
import xlwings
import re
import os

app = xlwings.App(visible=False)
current_dir = os.path.dirname(os.path.abspath(__file__))
sshinfo_path = os.path.join(current_dir, 'py_sshinfo.xls')
sshinfo = app.books.open(sshinfo_path)
sshinfo_sheet = sshinfo.sheets[0]
sshinfo_rows = sshinfo_sheet.used_range.last_cell.row

try:
    for a in range(1,sshinfo_rows):
        ip = sshinfo_sheet.range('A'+str(a+1)).value
        username = sshinfo_sheet.range('B'+str(a+1)).value
        password = sshinfo_sheet.range('C'+str(a+1)).value

        if a+1 == sshinfo_rows:
            sshinfo.save()
            sshinfo.close()

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            ssh.connect(hostname=ip,port=22,username=username,password=password)
        except BaseException:
            if a+1 == 2:
                print(f"[warn] 网络连接异常 或 {sshinfo_path} 文件第{a+1}行错误\n")
            else:
                print(f"[warn] {sshinfo_path} 文件第{a+1}行错误\n")
            sshinfo.save()
            sshinfo.close()

        command = ssh.invoke_shell()
        print(f"ssh {ip} ...")
        command.send("screen-length disable\n")
        command.send("dis arp\n")
        
        while not command.recv_ready():
            pass

        time.sleep(3)
        output=''

        while command.recv_ready():
            output += command.recv(65535).decode().strip()
            match = re.findall(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', output)

        try:
            excel_path = os.path.join(current_dir, 'py_ssh.xls')

            if not os.path.exists(excel_path):
                wb = app.books.add()
                wb.save(excel_path)
                wb.close()
                print('已新建Excel:\n', excel_path,'\n')

            wt = app.books.open(excel_path)
            sheet = wt.sheets[0]
            rows = sheet.used_range.last_cell.row
            print("results:")
            print(f'old_data_rows={rows}')
            old_data=[]
            old_data=sheet.range(f'A1:A{rows}').value

            if(old_data):
                full_data = old_data + match
                data=list(set(full_data))
            else:
                data=match

            print(f'new_data_rows={len(data)}\n')
            for i in range(0,len(data)):
                sheet.range('A'+str(i+1)).value = data[i]
        
        finally:
            wt.save()
            wt.close()

        ssh.close()

finally:
    app.quit()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值