首页 > 其他分享 >streamlit 网络批量ping和snmp检查

streamlit 网络批量ping和snmp检查

时间:2023-12-17 22:47:15浏览次数:29  
标签:name ping self cmd snmp st list result streamlit

import time
import netaddr
from netaddr import *
import pandas as pd
import streamlit as st
from concurrent.futures import ThreadPoolExecutor
import subprocess
import shlex
from threading import Lock
import re

class compute(object):

def __init__(self):
st.title(':red[Welcome] :sunglasses:') # 创建title,可以链接
st.sidebar.header(":red[IP计算器]")
#self.cmd = st.text_input("请输入要执行的命令")
self.net_iput = st.sidebar.text_input("请输入ip地址", help="示例:1.1.1.1/24") # 输入要划分的网段
self.subnet_list = [] # subnet列表

def subnet(self):
try:
net = IPNetwork(self.net_iput) # 输入要划分的网段
choose = st.sidebar.checkbox("是否进行子网划分",key="key123")
if choose == True:
cidr = st.sidebar.number_input("请选择划分的子网", min_value=1, max_value=128)
if int(cidr) - int(net.prefixlen) <20:
self.subnet_list = [str(snet) for snet in net.subnet(cidr)] # 获取子网list
#st.write(":red[子网详情如下:]")
with st.sidebar.expander(":red[查看子网详情]"):
df_subnet = pd.DataFrame(data=self.subnet_list, columns=["子网详情"])
st.dataframe(df_subnet,width=1000)
else:
st.sidebar.warning("子网数量过多,请重新输入")
except netaddr.core.AddrFormatError:
pass

def ip_info(self):
tab1,tab2,tab3 = st.sidebar.tabs([":red[可用地址]",":red[反掩码]",":red[掩码]"])
try:
ip = IPNetwork(self.net_iput)
with tab1:
st.write(str(ip[1]) + str("---") + str(ip[-2]))
with tab2:
st.write(str(ip.hostmask))
with tab3:
st.write(str(ip.netmask))
except netaddr.core.AddrFormatError:
pass


class mult_ping(object):

def __init__(self):
self.log_list = []
self.log_list_name = []
self.success_list = []
self.success_list_name = []
self.failed_list = []
self.failed_list_name = []

self.log_list_1 = []
self.log_list_name_1 = []
self.success_list_1 = []
self.success_list_name_1 = []
self.failed_list_1 = []
self.failed_list_name_1 = []

def ping(self,name,ip):
lock = Lock()
cmd_tmp = shlex.split("ping -c 2 %s" % str(ip))
cmd = subprocess.run(cmd_tmp, stdout=subprocess.PIPE)
result = (cmd.stdout.decode("gbk"))
self.log_list.append(result)
self.log_list_name.append(str(name))
if cmd.returncode == 0:
result = "正常"
self.success_list.append(result)
self.success_list_name.append(str(name))
else:
result = "不通"
#result = str(name) + " ping不通"
self.failed_list.append(result)
self.failed_list_name.append(str(name))

def snmp(self,name, ip):
lock = Lock()
cmd_snmp = shlex.split("snmpwalk -a sha -A muS7kKrZTAFbzPa4Uu56 -v 3 -l authPriv -x aes -X muS7kKrZTAFbzPa4Uu56 -u yunqiao %s ifindex" % str(ip))
cmd = subprocess.run(cmd_snmp, stdout=subprocess.PIPE)

if cmd.returncode == 0:
lock.acquire()
result = "snmpv3正常"
self.success_list_1.append(result)
self.success_list_name_1.append(str(name))
cmd_result = (cmd.stdout.decode("gbk"))
self.log_list_1.append(cmd_result)
self.log_list_name_1.append(str(name))
lock.release()
elif cmd.returncode == 1:
cmd_snmp = shlex.split("snmpwalk -v 2c -c AXQfPuJs %s ifindex" % str(ip))
tmp_cmd = subprocess.run(cmd_snmp,stdout=subprocess.PIPE)
if tmp_cmd.returncode == 0:
lock.acquire()
result = "snmpv2正常"
self.success_list_1.append(result)
self.success_list_name_1.append(str(name))
cmd_result = (tmp_cmd.stdout.decode("gbk"))
self.log_list_1.append(cmd_result)
self.log_list_name_1.append(str(name))
lock.release()
else:
lock.acquire()
result = "认证失败或超时"
self.failed_list_1.append(result)
self.failed_list_name_1.append(str(name))
cmd_result = (cmd.stdout.decode("gbk"))
self.log_list_1.append(cmd_result)
self.log_list_name_1.append(str(name))
lock.release()
elif cmd.returncode == 2:
lock.acquire()
result = "终端禁止接入"
self.failed_list_1.append(result)
self.failed_list_name_1.append(str(name))
cmd_result = (cmd.stdout.decode("gbk"))
self.log_list_1.append(cmd_result)
self.log_list_name_1.append(str(name))
lock.release()
else:
lock.acquire()
result = "其他问题"
self.failed_list_1.append(result)
self.failed_list_name_1.append(str(name))
cmd_result = (cmd.stdout.decode("gbk"))
self.log_list_1.append(cmd_result)
self.log_list_name_1.append(str(name))
lock.acquire()


def all_function(self):
upload_file = st.file_uploader(label="请上传要进行批量ping的文件",
type="xlsx",
accept_multiple_files=False)
if upload_file == None:
st.stop()
else:
with st.expander(":red[操作栏]"):
df = pd.read_excel(upload_file,None)
sheet = df.keys() # 获取所有sheet页
tabs = st.tabs(sheet)
for tab ,sheet_name,num in zip (tabs,sheet,list(range(1,10000))):
with tab:
df_sheet = df[sheet_name]
st.write(df_sheet)
col1, col2 = st.columns(2)
with col1:
result_name = st.selectbox("请选择设备名称列",df_sheet.keys(),key=10+num) # 选择最后保存的名字
if result_name == None:
st.stop()
df_result_name = df_sheet[result_name] # 获取设备名称的Dataframe
st.write(df_result_name)
dev_name_list = df_result_name.to_list()
#st.write(self.dev_name_list)
with col2:
ip_info = st.selectbox("请选择ip地址列",df_sheet.keys(),key=2+num) # 选择ping的地址
if ip_info == None:
st.stop()
df_ip_info = df_sheet[ip_info] # 获取IP的dataframe
st.write(df_ip_info)
ip_host_list = df_ip_info.to_list()
zip_list = zip(dev_name_list,ip_host_list) # 将选择的数据进行zip打包成元组
# 功能选项
ping_tab1, snmp_tab2 = st.tabs(["ping检查", "snmp检查"])
with ping_tab1:
choose_ping = st.checkbox("是否执行ping",key=20+num) # 是否执行CMD命令
if choose_ping ==True:
pool = ThreadPoolExecutor(8)
with st.spinner("wait for it"):
for i in zip_list:
name = i[0]
ip = i[1]
#st.write(i)
pool.submit(yc.ping, name, ip)
pool.shutdown()
#st.balloons()
st.snow()
tab1, tab2, tab3 = st.tabs([":red[succeed]", ":red[failed]", ":red[log]"])
with tab1:
dic = {"name": self.success_list_name, "result": self.success_list}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
with tab2:
dic = {"name": self.failed_list_name, "result": self.failed_list}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
with tab3:
dic = {"name": self.log_list_name, "result": self.log_list}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
else:
pass
with snmp_tab2:
choose_snmp = st.checkbox("是否执行snmp_walk",key=30+num) #是否执行snmp命令
if choose_snmp ==True:
pool = ThreadPoolExecutor(8)
with st.spinner("wait for it"):
for i in zip_list:
name = i[0]
ip = i[1]
#st.write(i)
pool.submit(yc.snmp, name, ip)
pool.shutdown()
#st.balloons()
st.snow()
tab1, tab2, tab3 = st.tabs([":red[succeed]", ":red[failed]", ":red[log]"])
with tab1:
dic = {"name": self.success_list_name_1, "result": self.success_list_1}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
with tab2:
dic = {"name": self.failed_list_name_1, "result": self.failed_list_1}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
with tab3:
dic = {"name": self.log_list_name_1, "result": self.log_list_1}
df_result = pd.DataFrame(data=dic)
st.write(df_result)
else:
pass


if __name__ == '__main__':
yc = compute()
yc.ip_info()
yc.subnet()

yc= mult_ping()
yc.all_function()




















标签:name,ping,self,cmd,snmp,st,list,result,streamlit
From: https://www.cnblogs.com/yc-tec/p/17910003.html

相关文章

  • 在 Windows 11 中为 WSL2 启用 Systemd 以及修复ping不通和DNS无法解析等的问题
    前言今天使用WSL2(Ubuntu22.04.1LTS)的时候,遇到了ping不通的问题,提示:ping:connect:Networkisunreachable以及执行sudoaptupdate命令出现错误:Failedtofetchhttp://archive.ubuntu.com/ubuntu/dists/focal/InReleaseTemporaryfailureresolving'archive.ubunt......
  • offline RL | Pessimistic Bootstrapping (PBRL):在 Q 更新中惩罚 uncertainty,拉低 OOD
    论文题目:PessimisticBootstrappingforUncertainty-DrivenOfflineReinforcementLearning,ICLR2022,6688spotlight。pdf版本:https://arxiv.org/abs/2202.11566html版本:https://ar5iv.labs.arxiv.org/html/2202.11566openreview:https://openreview.net/forum?id=Y4c......
  • 最新Spring 6手写实现Sping IOC保姆级教程
    Java全能学习+面试指南:https://javaxiaobear.cn我们都知道,Spring框架的IOC是基于Java反射机制实现的,下面我们先回顾一下java反射。1、回顾Java反射Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种......
  • zabbix接收snmptrap并触发告警
    1、配置陷阱处理脚本#在zabbix服务器或者代理服务器上,复制源码目录中的Perl脚本到/usr/bin目录下并赋予执行权限cpzabbix-6.0.2/misc/snmptrap/zabbix_trap_receiver.pl/usr/bin/chmoda+x/usr/bin/zabbix_trap_receiver.pl2、安装snmp相关软件包yum-yinstallnet-s......
  • 在Python的类型提示中,你不能直接使用​​or​​​来表示一个参数可以是多种类型中的一
    在Python的类型提示中,你不能直接使用or来表示一个参数可以是多种类型中的一种。你应该使用typing.Union来表示这种情况¹²。所以,你的函数应该这样写:fromtypingimportUnion,Listdefquery_coilNum(self,coilNum:Union[str,List[str]]):pass在这个例子中,Union[str,Li......
  • python之typing
    typing介绍Python是一门动态语言,很多时候我们可能不清楚函数参数类型或者返回值类型,很有可能导致一些类型没有指定方法,在写完代码一段时间后回过头看代码,很可能忘记了自己写的函数需要传什么参数,返回什么类型的结果,就不得不去阅读代码的具体内容,降低了阅读的速度,typing模块可以很......
  • 在思岚A1上复现gmapping
    文章目录软硬件条件laser_scan_matcher通过源码安装rplidar_ros通过源码安装设置参数启动效果预览软硬件条件软件:Ubuntu20.04,ROSnoetic硬件:RPLidarA1.laser_scan_matcher通过源码安装mkdir-p~/catkin_ws/srccd~/catkin_ws/srcgitclonehttps://github.com/ccny-ros-pk......
  • day21 atm项目 shopping_car
    shopping_car()fromatm.lib_common.file_handleimport*fromatm.core.shoppingimportgoods_showfromatm.lib_common.money_enquiryimport*defcompute_money_total(username):"""计算购物车总价返回购物车总价和购物车字典"""......
  • 分析网络路由的工具 pathping 和 mtr
    结合了ping和tracert/traceroute的工具有PathPing(Windows)和MTR(MyTraceroute,在Unix/Linux上)PathPing(Windows)PathPing:这个工具结合了ping和tracert的功能,它会发送多个数据包到每个跳点,并统计丢包率和延迟。这对于识别链路中的问题节点非常有用。如何使用PathPing打开......
  • TypingLearn解决了我在学习英语中的一大痛点
    上一次在博客园发贴还是在上一次(2021年),那个时候博客园就遇到了危机(被罚款)。彼时在疫情期间,我个人生活也受到了影响,先后去了多个城市,最终在上海找到了.NETWeb开发的岗位,还是比较幸运的,因为这就是我感兴趣的。TypingLearn解决了我在学习英语中的一大痛点一些背景我是一个开......