批量远程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()