首页
统计信息
友情链接
壁纸
Search
1
【更新】CommentToMail typecho2017&v4.1& Mailer三版本,支持php5.6/7,插件详解
158,109 阅读
2
【90APT开源免费】第三代哈弗H6、哈弗大狗、H6经典版车机开启无线ADB、升级地图、安装软件全流程
15,043 阅读
3
CentOS 7安装bbr教程
12,863 阅读
4
纯小白10分钟变身linux建站高手?宝塔linux面板全体验
12,454 阅读
5
深信服超融合架构测试介绍
11,823 阅读
技术相关
ACG相关
胡言乱语
数码杂烩
登录
Search
标签搜索
进击的巨人
漫画
宝塔
php
typecho
diy
vps
折腾
动漫
优酷路由宝
ubuntu
路由器
QQ
KMS
王忘杰
累计撰写
274
篇文章
累计收到
179
条评论
首页
栏目
技术相关
ACG相关
胡言乱语
数码杂烩
页面
统计信息
友情链接
壁纸
搜索到
242
篇与
的结果
2023-08-04
VLAN非常规实验,给你带来一个不一样的VLAN2
查看本文前请先查看第一篇VLAN非常规实验,给你带来一个不一样的VLAN1https://90apt.com/2901本期为大家带来两个VLAN非常规实验1、傻瓜网络网管改造2、VLAN串联一、傻瓜网络网管改造 1、项目需求此需求来源真实,监控网络全部为傻瓜式连接交换机,需求逐步进行网管改造,改造应减小对监控网络的影响,监控网络可临时中断数分钟,不允许完全停机进行改造。2、改造前简化拓扑交换机均无配置,硬盘录像机与摄像头互通3、改造思路监控网络配置为vlan10,监控交换机管理网络配置为vlan20SW1 SW2 SW3 IP配置为192.168.20.1 192.168.20.2 192.168.20.3为保证监控不完全停机,需要用到trunk与pvid技术4、监控汇聚交换机改造将1-24口划入vlan10,将25-28划入trunk,配置vlan1 10 20通过,配置pvid10,为vlan20配置ip,最后测试硬盘录像机与摄像头是否互通[SW1]vlan 10 [SW1-vlan10]vlan 20 [SW1-vlan20]qu [SW1]int range g1/0/1 to g1/0/24 [SW1-if-range]port access vlan 10 [SW1-if-range]qu [SW1]int range g1/0/25 to g1/0/28 [SW1-if-range]port link-type trunk [SW1-if-range]port trunk permit vlan 1 10 20 [SW1-if-range]port trunk pvid vlan 10 [SW1]int vlan 20 [SW1-Vlan-interface20]ip add 192.168.20.1 24使用硬盘录像机ping摄像头[H3C]ping 192.168.1.2 Ping 192.168.1.2 (192.168.1.2): 56 data bytes, press CTRL_C to break 56 bytes from 192.168.1.2: icmp_seq=0 ttl=255 time=1.658 ms 56 bytes from 192.168.1.2: icmp_seq=1 ttl=255 time=2.110 ms5、技术解析在此改造中,为什么可以使用trunk接口对接无配置交换机并且不影响监控网络运行?此配置重点在于对vlan的理解,access接口为出撕标签入打标签,trunk接口默认不处理标签,当trunk接口配置pvid时,trunk接口对于此pvid的vlan同样具备access的作用,即出撕标签入打标签,因此trunk pvid vlan10可以与傻瓜交换机的access接口通讯,保证监控网络运行。6、其他监控交换机改造,测试监控交换机之间是否互通,测试硬盘录像机与摄像头是否互通[SW2]vlan 10 [SW2-vlan10]vlan 20 [SW2]int range g1/0/1 to g1/0/24 [SW2-if-range]port access vlan 10 [SW2-if-range]int range g1/0/25 to g1/0/28 [SW2-if-range]port link-type trunk [SW2-if-range]port trunk permit vlan 1 10 20 [SW2-if-range]port trunk pvid vlan 10 [SW2-if-range]qu [SW2]int vlan 20 [SW2-Vlan-interface20]ip add 192.168.20.2 24[SW3]vlan 10 [SW3-vlan10]vlan 20 [SW3-vlan20]qu [SW3]int range g1/0/1 to g1/0/24 [SW3-if-range]port access vlan 10 [SW3-if-range]int range g1/0/25 to g1/0/28 [SW3-if-range]port link-type trunk [SW3-if-range]port trunk permit vlan 1 10 20 [SW3-if-range]port trunk pvid vlan 10 [SW3-if-range]qu [SW3]int vlan 20 [SW3-Vlan-interface20]ip add 192.168.20.3 24硬盘录像机ping摄像头[H3C]ping 192.168.1.2 Ping 192.168.1.2 (192.168.1.2): 56 data bytes, press CTRL_C to break 56 bytes from 192.168.1.2: icmp_seq=0 ttl=255 time=1.230 ms 56 bytes from 192.168.1.2: icmp_seq=1 ttl=255 time=2.140 ms监控汇聚ping监控交换机3<SW1>ping 192.168.20.3 Ping 192.168.20.3 (192.168.20.3): 56 data bytes, press CTRL_C to break 56 bytes from 192.168.20.3: icmp_seq=0 ttl=255 time=1.000 ms 56 bytes from 192.168.20.3: icmp_seq=1 ttl=255 time=1.000 ms改造完成二、VLAN串联 1、项目需求此需求来源真实,SW1、SW2均为网管交换机,SW1 g1-g24为accessVLAN5 g25-g28为trunkALL,SW2 g1-g24为accessVLAN1 g25-g28为trunkALL,此时SW2所在区域已经封闭无法进入,请通过SW1的调整使服务器与读卡器互通。2、现状测试服务器无法ping通读卡器<H3C>ping 192.168.1.2 Ping 192.168.1.2 (192.168.1.2): 56 data bytes, press CTRL_C to break Request time out Request time out3、技术解析由于SW2无法操作,因此要在SW1上将VLAN5与VLAN1互联,通过VLAN1穿过trunk接口将数据送达读卡器,我们在SW1上创建一个VLAN1接口,将VLAN1与VLAN5接口通过网线串联。注意:我们是无法直接为端口配置VLAN1的,但可以通过default使接口恢复为VLAN1.[SW1-GigabitEthernet1/0/4]dis th # interface GigabitEthernet1/0/4 port link-mode bridge port access vlan 5 combo enable fiber # return [SW1-GigabitEthernet1/0/4]default This command will restore the default settings. Continue? [Y/N]:y [SW1-GigabitEthernet1/0/4]dis th # interface GigabitEthernet1/0/4 port link-mode bridge combo enable fiber # return [SW1-GigabitEthernet1/0/4]dis interface brief GE1/0/1 UP 1G(a) F(a) A 5 GE1/0/2 DOWN auto A A 5 GE1/0/3 DOWN auto A A 5 GE1/0/4 DOWN auto A A 1 GE1/0/5 DOWN auto A A 54、测试发现仍无法ping通ping 192.168.1.2 Ping 192.168.1.2 (192.168.1.2): 56 data bytes, press CTRL_C to break Request time out Request time out5、技术分析在同一台交换机上串联接口,我们首先要考虑STP防环协议是否阻止了接口,查看STP接口状态,发现g4接口被屏蔽[SW1]dis stp brief MST ID Port Role STP State Protection 0 GigabitEthernet1/0/1 DESI FORWARDING NONE 0 GigabitEthernet1/0/3 DESI FORWARDING NONE 0 GigabitEthernet1/0/4 BACK DISCARDING NONE 0 GigabitEthernet1/0/28 DESI FORWARDING NONE关闭stp协议[SW1]un stp global en检查服务器与读卡器是否互通<H3C>ping 192.168.1.2 Ping 192.168.1.2 (192.168.1.2): 56 data bytes, press CTRL_C to break 56 bytes from 192.168.1.2: icmp_seq=0 ttl=255 time=1.227 ms 56 bytes from 192.168.1.2: icmp_seq=1 ttl=255 time=1.665 ms测试通过注意:此方法仅用于特殊情况下的紧急处理,请勿实施于正常网络中。
2023年08月04日
412 阅读
0 评论
0 点赞
2023-08-03
almalinux8安装tomcat9
从yum源直接安装tomcat9yum install tomcat tomcat-webapps tomcat-admin-webapps启动服务systemctl enable --now tomcat访问tomcat正常http://IP:8080/配置Manager App访问范围/usr/share/tomcat/webapps/manager/META-INF/context.xml原内容 <Context antiResourceLocking="false" privileged="true" > <CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor" sameSiteCookies="strict" /> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/> </Context> 增加任意IP访问 \d+\.\d+\.\d+\.\d+ 修改后 <Context antiResourceLocking="false" privileged="true" > <CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor" sameSiteCookies="strict" /> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|\d+\.\d+\.\d+\.\d+" /> <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/> </Context> 配置Manager App用户名密码/usr/share/tomcat/conf/tomcat-users.xml在倒数第二行添加 <role rolename="manager-gui"/> <user username="admin" password="admin" roles="manager-gui"/>重启服务systemctl restart tomcat完毕
2023年08月03日
205 阅读
0 评论
0 点赞
2023-07-27
0基础上手python3编程,本地文件存活监控
架构图 判断文件是否存在;如果文件不存在,判断check.config是否为1,如果为1程序退出,如果不存在或为0,生成或写入1并发送企业微信告警;如果文件存在,判断check.config是否为0,如果为0程序退出,如果不存在或为1,生成或写入0并发送企业微信告警;预览 系统组成 由两个文件组成 check.py check.conf,其中 check.conf为自动生成代码 check.pyimport os,requests #企业微信机器人 def post_weixin(stats): url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的' body = { "msgtype": "news", "news": { "articles": [ { "title": "文件监控", "description": stats, "url": "90apt.com", "picurl": "用自己的" } ] }} response = requests.post(url, json=body) print(response.text) print(response.status_code) if os.path.exists("D:\hello.txt") == False: #判断文件是否存在 f1 = open("D:\check.config", 'r') #读取文件 config = f1.read() if config == "1": f1.close() else: f1.close() f1 = open("D:\check.config", 'w+') f1.write("1") #写入文件 post_weixin("监控到文件丢失") f1.close() else: f1 = open("D:\check.config", 'r') config = f1.read() if config == "0": f1.close() else: f1 = open("D:\check.config", 'w+') f1.write("0") post_weixin("监控到文件已生成") f1.close()总结 简单
2023年07月27日
241 阅读
0 评论
0 点赞
2023-07-27
0基础上手python3编程,单线程监控摄像头巡检平台
架构图 读取配置文件;通过rtsp连接摄像头,保存一张截图;发送企业微信通知;记录log日志;预览 系统组成 rtsp.py rtsp.json代码 由于代码在windows平台运行,因此使用绝对路径C:\\jiankong\,文件放置在此目录下。rtsp.pyimport cv2,os,json,time,requests,codecs from func_timeout import func_set_timeout from multiprocessing import Process @func_set_timeout(5) def dayin(): video1 = "rtsp://"+rtspconfig['name']+":"+rtspconfig['password']+"@"+rtspconfig['ip']+rtsp_config[rtspconfig['brand']] cap = cv2.VideoCapture(video1) # 使用整数,此处打开的本地摄像头 while 1: ret, frame = cap.read() if ret == False: # 若没有帧返回,则重新刷新rtsp视频流 continue else: break; # cv2.imshow("capture",frame) cv2.imwrite(nowdir+"\\"+rtspconfig['ip']+".jpeg", frame) cap.release() return rtspconfig['hostname']+"保存成功" def get_config(): config = json.loads(open("C:\\jiankong\\rtsp.json", encoding='utf-8').read()) return config def post_weixin(stats): url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的' body = { "msgtype": "news", "news": { "articles": [ { "title": "监控摄像头自动巡检", "description": stats, "url": "90apt.com", "picurl": "https://www.hikvision.com/content/dam/hikvision/cn/product/network-camera/fixed-ipc/%E7%BB%8F%E9%94%80%E7%B3%BB%E5%88%97/%E7%BB%8F%E9%94%80%E7%B3%BB%E5%88%97%E5%AF%BC%E8%88%AA%E7%9B%AE%E5%BD%95.jpg" } ] }} response = requests.post(url, json=body) print(response.text) print(response.status_code) total = 0 fail = 0 weixindata = "" rtsp_config = get_config() print(rtsp_config) #path1=os.path.abspath('.') path1=("C:\\jiankong\\") nowtime = time.strftime("%Y%m%d", time.localtime()) try: os.mkdir(path1 + "\\" + nowtime) except: None nowdir = (path1 + "\\" + nowtime) for rtspconfig in rtsp_config['rtsp']: total = total + 1 try: dayin() except: weixindata = weixindata + (rtspconfig['hostname']+" "+rtspconfig['ip']+" 网络或账号密码错误\n") fail = fail + 1 weixinpost = "总计巡检:"+str(total)+"台"+",故障摄像头:"+str(fail)+"台\n"+weixindata post_weixin(weixinpost) flog = codecs.open(nowdir+"\\"+nowtime+".log", 'w',encoding='utf-8') flog.write(weixinpost) flog.close() rtsp.json yushi指宇视品牌摄像头,haikang指海康威视{ "haikang" : ":554/h264/ch1/main/av_stream", "yushi" : ":554/video1", "rtsp" : [ {"ip" : "172.16.1.1","hostname" : "摄像头1","brand" : "yushi","name": "admin","password": "admin"}, {"ip" : "172.16.1.2","hostname" : "摄像头2","brand" : "yushi","name": "admin","password": "admin"}, {"ip" : "172.16.1.3","hostname" : "摄像头3","brand" : "haikang","name": "admin","password": "admin"} ] }总结 简单
2023年07月27日
216 阅读
0 评论
1 点赞
2023-07-20
python编译exe可执行文件
安装pyinstaller模块在终端运行pyinstaller -F -w 自己的py名字.py -F 打包为1个文件 -w 隐藏窗口模式
2023年07月20日
213 阅读
0 评论
0 点赞
2023-07-12
RHEL8+Graylog5.1日志监控系统快速部署接入
本教程适用于RHEL8/Oracle linux8/ALMA Linux8操作系统,当前组件版本信息为:java-17-openjdk-17.0.7.0.7-3.0.1.el8.x86_64 opensearch-2.8.0-1.x86_64 mongodb-org-database-6.0.8-1.el8.x86_64 graylog-server-5.1.3-1.x86_64建议 装一台Alma8服务器,安装graylog,关闭selinux,保持系统更新。全部采用yum源安装,方便快速更新我防火墙仅开放了9000/TCP 1514/UDP 和 SSH端口官方安装教程 https://go2docs.graylog.org/5-1/downloading_and_installing_graylog/red_hat_installation.htm安装OpenJdk17yum install java-17-openjdk安装MongoDB 创建yum源文件/etc/yum.repos.d/mongodb-org.repo[mongodb-org-6.0] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc安装并启动sudo yum install -y mongodb-org sudo systemctl daemon-reload sudo systemctl enable mongod sudo systemctl start mongod sudo systemctl status mongod安装OpenSearchsudo curl -SL https://artifacts.opensearch.org/releases/bundle/opensearch/2.x/opensearch-2.x.repo -o /etc/yum.repos.d/opensearch-2.x.repo sudo yum install -y opensearch配置OpenSearch端口监听/etc/opensearch/opensearch.ymlcluster.name: graylog node.name: ${HOSTNAME} path.data: /var/lib/opensearch path.logs: /var/log/opensearch discovery.type: single-node network.host: 0.0.0.0 action.auto_create_index: false plugins.security.disabled: true修改内存占用/etc/opensearch/jvm.options-Xms6g -Xmx8g修改内核参数sudo sysctl -w vm.max_map_count=262144 sudo echo 'vm.max_map_count=262144' >> /etc/sysctl.conf启动程序sudo systemctl daemon-reload sudo systemctl enable opensearch sudo systemctl start opensearch sudo systemctl status opensearch安装Graylogsudo rpm -Uvh https://packages.graylog2.org/repo/packages/graylog-5.1-repository_latest.rpm sudo yum install graylog-server修改配置/etc/graylog/server/server.conf增加password_secret和root_password_sha2选项,不增加这两项不允许访问,配置http_bind_address,默认只监听127.0.0.1,修改为0.0.0.0取得root_password_sha2值echo -n "Enter Password: " && head -1 </dev/stdin | tr -d '\n' | sha256sum | cut -d" " -f1取得password_secret值< /dev/urandom tr -dc A-Z-a-z-0-9 | head -c${1:-96};echo;启动程序sudo systemctl daemon-reload sudo systemctl enable graylog-server.service sudo systemctl start graylog-server.service sudo systemctl --type=service --state=active | grep graylog登录系统 默认为http://IP:9000/用户名和密码均在server.conf中定义启动Syslog UDP监听器 注意:graylog无法监听1024以内端口,因此Syslog将使用1514UDP端口 graylog - system -inputsH3C交换机快速接入info-center loghost 172.16.0.1 port 1514浪潮BMC快速接入 群晖快速接入 预览 问题处理 时间不对,修改时区 server.confroot_timezone = Asia/Shanghai总结 为什么不用ELK? 你研究ELK? 等你研究出来马斯克都上火星了! 人生苦短,我用Graylog!
2023年07月12日
641 阅读
0 评论
3 点赞
2023-07-10
0基础上手python3编程,通用Mysql数据库字段监控,企业微信告警
架构图 通过redis缓存mysql数据库字段进行对比,当发现内容变动时,进行企业微信告警预览 系统组成 由两部分组成 check.py和redis数据库,从mysql中读取指定字段存储到redis中代码import requests,redis import mysql.connector def post_weixin(data): url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的' body = { "msgtype": "news", "news": { "articles": [ { "title": "卡号监控机器人", "description": data, "url": "90apt.com", "picurl": "https://www.zkteco.com/cn/uploads/image/20210301/3e1adaa2dce94812e658c5d42afc1525.png" } ] } } headers = {"Content-Type": "application/json"} response = requests.post(url, json=body) print(response.text) print(response.status_code) def sqlread(): mqdb = mysql.connector.connect( host="127.0.0.1", user="admin", passwd="password", database="mysqldata" ) mqcursor = mqdb.cursor() getconfig_sql = "SELECT number,card,name FROM userinfo where ifnull(name, '') <> ''" mqcursor.execute(getconfig_sql) mqconfig = mqcursor.fetchall() global cardchange cardchange = "" readredis = redis.Redis(connection_pool=redis.ConnectionPool(host="127.0.0.1", port="6379", password="password",decode_responses=True)) for i in mqconfig: if readredis.get(i[0]) == str(i[1]): None else: cardchange = cardchange + i[2]+readredis.get(i[0])+"变为"+str(i[1])+"\n" readredis.set(i[0], str(i[1])) sqlread() post_weixin(cardchange)总结 简单
2023年07月10日
257 阅读
0 评论
3 点赞
2023-07-07
ALMA Linux 8飞速搭建zabbix6LTS、微信邮箱短信报警、windows、linux、交换机、vCenter监控、grafana面板、modbus动环采集、ZbxTable分析系统、Mysql、MSsql数据库监控、分组报警
一、环境 zabbix所在服务器系统为alma8,zabbix6要求的mariadb版本为10.5-10.6,同时zabbix提供了zabbix-selinux-policy来配置selinux,所以安装中也不再要求关闭selinux。二、安装zabbix 官方安装帮助页面,安装方法随版本更新,官方更新更快https://www.zabbix.com/cn/download1、配置zabbix 软件源rpm -Uvh https://repo.zabbix.com/zabbix/6.0/rhel/8/x86_64/zabbix-release-6.0-4.el8.noarch.rpm dnf clean all2、安装zabbix-server和zabbix-agent2dnf install zabbix-server-mysql zabbix-web-mysql zabbix-apache-conf zabbix-sql-scripts zabbix-selinux-policy zabbix-agent23、安装数据库配置mariabd源 /etc/yum.repos.d/MariaDB.repo# MariaDB 10.6 CentOS repository list - created 2023-02-02 03:14 UTC # https://mariadb.org/download/ [mariadb] name = MariaDB baseurl = https://mirrors.aliyun.com/mariadb/yum/10.6/centos8-amd64 module_hotfixes=1 gpgkey=https://mirrors.aliyun.com/mariadb/yum/RPM-GPG-KEY-MariaDB gpgcheck=1安装数据库、启动、并设置开机启动dnf clean all dnf install mariadb-server systemctl enable --now mariadb4、进行MariaDB数据库初始化mariadb-secure-installation首先是设置密码,会提示先输入密码 Enter current password for root (enter for none):<–初次运行直接回车 Set root password? [Y/n] <– 是否设置root用户密码,输入y并回车 New password: <– 设置root用户的密码 Re-enter new password: <– 再输入一次你设置的密码 Remove anonymous users? [Y/n] <– 是否删除匿名用户 Disallow root login remotely? [Y/n] <–是否禁止root远程登录 Remove test database and access to it? [Y/n] <– 是否删除test数据库 Reload privilege tables now? [Y/n] <– 是否重新加载权限表5、初始化并导入zabbix数据库 mysql -uroot -p登录mariadb> create database zabbix character set utf8mb4 collate utf8mb4_bin; mariadb> create user zabbix@localhost identified by 'password123'; mariadb> grant all privileges on zabbix.* to zabbix@localhost; mariadb> set global log_bin_trust_function_creators = 1; mariadb> quit;导入初始架构和数据,系统将提示您输入新创建的密码zcat /usr/share/zabbix-sql-scripts/mysql/server.sql.gz | mysql --default-character-set=utf8mb4 -uzabbix -p zabbix导入数据库架构后禁用log_bin_trust_function_creators选项mysql -uroot -p mariadb> set global log_bin_trust_function_creators = 0; mariadb> quit;6、配置数据库密码编辑配置文件 /etc/zabbix/zabbix_server.confDBPassword=password1237、配置PHP时区编辑配置文件 /etc/php-fpm.d/zabbix.confphp_value[date.timezone] = Asia/Shanghai8、启动并设置开机启动systemctl enable --now zabbix-server zabbix-agent2 httpd php-fpm9、查看是否有错误信息 cat /var/log/zabbix/zabbix_server.log10、防火墙开放端口firewall-cmd --add-port=80/tcp --permanent firewall-cmd --permanent --add-port=10050-10051/tcp firewall-cmd --reload firewall-cmd --list-ports firewall-cmd --list-services11、替换zabbix自带字体,解决中文乱码百度下载Noto Sans S Chinese字体替换掉默认使用的DejaVuSanscp NotoSansSC-Regular.otf /usr/share/fonts/dejavu/DejaVuSans.ttf12、调整zabbix缓存/etc/zabbix/zabbix_server.confCacheSize=1G13、调整ping进程数/etc/zabbix/zabbix_server.confStartPingers=16三、服务端配置 1、连接到新安装的Zabbix前端: http://server_ip/zabbix注意,mariadb也属于mysql数据库类型2、登录zabbix账号Admin 密码zabbix前端配置完成请务必修改密码四、企业微信消息推送 注意:为了企业的数据安全,从2022年6月20号20点之后,新开启的通讯录同步助手与新创建的自建应用必须在管理端配置可信IP,仅配置的可信IP能调用接口。当前时间2023年6月,企业微信应用验证必须与企业名相同,请考虑使用企业微信机器人推送。1、在企业微信 - 我的企业 - 企业信息 - 企业ID 2、创建zabbix机器人应用企业微信后台 - 应用管理 - 应用 - 创建应用 先进行网页授权及JS-SDK可信域名下的网页可使用网页授权及JS-SDK可信IP位于自行创建的应用-开发接口-企业可信IP 可信IP即服务器所在网络的外网IP,可打开https://ifconfig.me/快速查看,如果企业机房接入多条外网宽带,把外网宽带的IP全都写上3、查看Agentld和Secret 4、准备zabbix机器人脚本环境dnf -y install epel-release dnf -y install python2-pip pip2 install requests查询脚本存放位置cat /etc/zabbix/zabbix_server.conf | grep AlertScript可以看到脚本存放在/usr/lib/zabbix/alertscripts目录中编写脚本 weixin.py并放入上面的目录 ,填入上面获得的三个值#!/usr/bin/env python2 #-*- coding: utf-8 -*- import requests import sys import os import json import logging logging . basicConfig ( level = logging . DEBUG , format = ' %(asctime)s , %(filename)s , %(levelname)s , %(message)s ' , datefmt = ' %a , %d %b %Y %H:%M:%S' , filename = os . path . join ( '/tmp' , 'weixin.log' ), filemode = 'a' ) corpid = 'ww36e' appsecret = '5yFNqeTjrr3I' agentid = 1000002 token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + appsecret req = requests . get ( token_url ) accesstoken = req . json ()[ 'access_token' ] msgsend_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken touser = sys . argv [ 1 ] subject = sys . argv [ 2 ] #toparty='3|4|5|6' message = sys . argv [ 2 ] + " \n\n " + sys . argv [ 3 ] params ={ "touser" : touser , # "toparty": toparty, "msgtype" : "text" , "agentid" : agentid , "text" : { "content" : message }, "safe" : 0 } req = requests . post ( msgsend_url , data = json . dumps ( params )) logging . info ( 'sendto:' + touser + ';;subject:' + subject + ';;message:' + message )赋予执行权限chmod +x /usr/lib/zabbix/alertscripts/weixin.py创建日志文件touch /tmp/weixin.log chown zabbix:zabbix /tmp/weixin.log测试脚本,用户名为企业微信通讯录中的用户名,一般为拼音全拼,严格区分大小写!/usr/lib/zabbix/alertscripts/weixin.py 用户名 '标题' '测试成功'此时企业微信可以收到zaabix应用发来的信息。5、添加报警媒介zabbix后台 - 管理 - 报警媒介类型名称 weixin类型 脚本脚本名称 weixin.py脚本参数:{ALERT.SENDTO} {ALERT.SUBJECT} {ALERT.MESSAGE} 6、配置Trigger actions触发动作,启用消息推送管理员,填写要发送的信息配置 - 动作 Trigger actions - 创建动作 在 动作 中填写名称在 操作 中编辑操作和恢复操作操作发送消息zabbix管理员组仅发送到微信custom message主题:服务器报警消息:告警主机:{HOST.NAME} 告警地址:{HOST.IP} 监控项目:{ITEM.NAME} 监控取值:{ITEM.LASTVALUE} 告警等级:{TRIGGER.SEVERITY} 当前状态:{TRIGGER.STATUS} 告警信息:{TRIGGER.NAME} 告警时间:{EVENT.DATE} {EVENT.TIME} 事件ID:{EVENT.ID}恢复操作通知所有参与者custom message主题:服务器已恢复消息:告警主机:{HOST.NAME} 告警地址:{HOST.IP} 监控项目:{ITEM.NAME} 监控取值:{ITEM.LASTVALUE} 告警等级:{TRIGGER.SEVERITY} 当前状态:{TRIGGER.STATUS} 告警信息:{TRIGGER.NAME} 告警时间:{EVENT.DATE} {EVENT.TIME} 事件ID:{EVENT.ID} 7、配置Autoregistration actions自动注册,填写要发送的信息在Autoregistration actions自动注册中注意:自动注册的其他内容在下方linux、windows部分发送消息zabbix管理员组仅送到weixinCustom message主题:Linux主机自动注册到zabbix服务器消息:主机名:{HOST.HOST} 主机IP:{HOST.IP} Agent端口:{HOST.PORT} 8、接收微信推送人员管理-用户-报警媒介邮箱推送、微信推送 可以理解为仅配置脚本不同,其他配置参数基本一致邮箱 1、安装mailxyum install mailx -y2、修改mailx配置vim /etc/mail.rc最后添加 set from=xx@qq.com set smtp=smtp.qq.com set smtp-auth-user=xx@qq.com set smtp-auth-password=邮箱密码 set smtp-auth=login3、测试邮箱echo “hello world” | mail -s “testmail” xx@qq.com4、编写邮箱脚本cd /usr/lib/zabbix/alertscripts/vim mailx.sh#!/bin/bash #send mail messages=`echo $3 | tr '\r\n' '\n'` subject=`echo $2 | tr '\r\n' '\n'` echo "${messages}" | mail -s "${subject}" $1 >>/tmp/mailx.log 2>&15、创建日志,添加权限touch /tmp/mailx.logchown -R zabbix.zabbix /tmp/mailx.logchmod +x /usr/lib/zabbix/alertscripts/mailx.shchown -R zabbix.zabbix /usr/lib/zabbix/6、添加使用其他添加过程与微信相同微信推送 1、查看短信平台文档编写短信脚本,注意不通用我用的短信平台采用http get通讯cd /usr/lib/zabbix/alertscripts/cat sendSMS.sh#!/bin/bash #手机号码 MOBILE_NUMBER=$1 #短信主题 MESSAGE_SUBJECT=$2 #短信内容 MESSAGE_UTF8=$3 #调用短信接口 /usr/bin/curl -s -G --data-urlencode userid=用户ID --data-urlencode account=用户名 --data-urlencode password=用户密码 --data-urlencode mobile=${MOBILE_NUMBER} --data-urlencode content="${MESSAGE_SUBJECT}-${MESSAGE_UTF8}" http://www.短信平台接口.com/xx?action=send >> /tmp/sendSMS.log2、添加使用其他添加过程与微信相同五、自动注册windows主机 平台 - 配置 - 动作 - Autoregistration actions自动注册 创建动作元数据中的 Linux 为下方脚本里的 HostMetadata=windows 严格区分大小写操作添加主机添加主机群组关联模板下载安装agent2客户端https://www.zabbix.com/cn/download_agents最新版本为 Zabbix agent 2 v6.0.5修改配置 HostMetadata=windowsC:\Program Files\Zabbix Agent 2\zabbix_agent2.conf重启服务收到自动注册提示六、自动注册linux主机 zabbix平台自动注册linux与windows方法基本相同,元数据修改为linux在linux客户端上可以使用自动化脚本安装zabbix agent2客户端我这里仅放一个centos7/8的安装脚本,内容为卸载agent1安装agent2#/bin/bash echo "关闭selinux" sed -i '/SELINUX/s/enforcing/disabled/' /etc/selinux/config setenforce 0 echo "下载zabbix-agent2,卸载agent1" OSVERSION=`cat /etc/redhat-release |awk -F "release " '{print $2}'|awk -F "." '{print $1}'` rpm -Uvh https://repo.zabbix.com/zabbix/6.0/rhel/$OSVERSION/x86_64/zabbix-release-6.0-1.el$OSVERSION.noarch.rpm yum clean all yum remove zabbix-agent -y yum install zabbix-agent2 -y echo "修改zabbix-agent2配置文件" ipaddr=$(ip a show |grep ens|grep inet |awk '{print $2}'|awk -F '/' '{print $1}') zabbix_server='192.168.1.110' hostname=$(hostname) sed -i "s/^Server=127.0.0.1/Server=${zabbix_server}/g" /etc/zabbix/zabbix_agent2.conf sed -i "s/^ServerActive=127.0.0.1/ServerActive=${zabbix_server}/g" /etc/zabbix/zabbix_agent2.conf sed -i "s/Hostname=Zabbix server/Hostname=${hostname}/g" /etc/zabbix/zabbix_agent2.conf sed -i "s/# HostMetadata=/HostMetadata=linux/g" /etc/zabbix/zabbix_agent2.conf echo "防火墙放行zabbix-agent端口" firewall-cmd --permanent --add-port=10050-10051/tcp firewall-cmd --reload echo "启动zabbix-agent服务" systemctl enable --now zabbix-agent2 zabbixagentpid=`ps -ef |grep zabbix_agent2|grep -w 'zabbix_agent2'|grep -v 'grep'|awk '{print $2}'` if [ "$zabbixagentpid" ];then echo "zabbix agent2 正在运行 " else echo "zabbix agent2 安装失败!!!" fi七、通过SNMP监控交换机 1、为zabbix添加SNMPv2模板SNMPv2模板下载https://share.zabbix.com/templates/network-devices-fortigate-template-fortinet-all-discovery/#body2、交换机配置snmpv2snmp-agent sys-info version v2c snmp-agent community read public snmp-agent community write private snmp-agent trap enable snmp-agent target-host trap address udp-domain 192.168.1.110 params securityname public v2c snmp-agent3、查找MIBH3C常用MIBhttps://www.h3c.com/cn/Service/Document_Software/TechnicalInfo/PorductMaintanInfo/Switches/DailyMainten/MIBList/4、安装snmp调试工具并进行测试dnf -y install net-snmp-utilssnmpwalk为模糊测试snmpwalk -v 2c -c public 192.168.237.50 .1.3.6.1.4.1.2021.10.1.3snmpget是zabbix的精准获取方式snmpget -v 2c -c public 192.168.237.50 .1.3.6.1.4.1.2021.10.1.35、举例如S5130 CPU使用率,查询H3C手册为 1.3.6.1.4.1.25506.8.35.18.1.3使用snmpwalk -v 2c -c public 192.168.237.50 1.3.6.1.4.1.25506.8.35.18.1.3后返回SNMPv2-SMI::enterprises.25506.8.35.18.1.3.0 = INTEGER: 16得知最后多一位.0使用snmpget -v 2c -c public 192.168.237.50 1.3.6.1.4.1.25506.8.35.18.1.3.0得到结果相同,则此项为s5130型号的CPU使用率在zabbix新建监控项,即可实现CPU使用率记录新建触发器,即可实现CPU使用率报警前5次报警值均超过80时进行CPU使用率过高报警最终效果其他参数:CPU使用率 1.3.6.1.4.1.25506.8.35.18.4.3.1.4.0.1 内存使用率 1.3.6.1.4.1.25506.8.35.18.1.16.0 固件版本 1.3.6.1.2.1.1.1.0 开机时间 1.3.6.1.2.1.1.3.0 SN 1.3.6.1.4.1.25506.2.6.1.2.1.1.2.2 温度 1.3.6.1.4.1.25506.2.6.1.1.1.1.12.212八、添加vsphere vCenter监控 1、开启VMware支持并重启zabbix-server服务/etc/zabbix/zabbix_server.conf ### Option: StartVMwareCollectors StartVMwareCollectors=52、检查vCenter sdk接口返回500代码代表接口在工作curl -i -k --data "" https://172.16.0.1/sdk HTTP/2 500 cache-control: no-cache content-type: text/xml; charset=utf-8 date: Tue, 28 Jun 2022 01:36:00 GMT x-envoy-upstream-service-time: 0 server: envoy3、登录每台ESXi主机开启MOB服务系统高级设置,搜索Config.HostAgent.plugins.solo.enableMob,确定值改为true4、zabbix创建主机注意是修改继承的宏 https://172.16.0.1/sdk5、查看数据一段时间后,zabbix可以获取到所有的vCenter、ESXi和虚拟机的信息九、grafana面板 1、安装当前最新版本grafana-10.0.1sudo yum install -y https://dl.grafana.com/oss/release/grafana-10.0.1-1.x86_64.rpm注意配置开机启动并配置防火墙,默认使用3000端口2、安装grafana zabbix插件grafana-cli plugins list-remote grafana-cli plugins install alexanderzobnin-zabbix-app systemctl restart grafana-server3、登录grafana接入zabbix源http://IP:3000/ 打开grafana界面,打开后输入admin/admin登录,登陆后按提示更改admin密码。启用zabbix插件配置数据源http://ip/zabbix/api_jsonrpc.php保存并测试成功新建面板即可十、首页图表监控 首页添加构件十一、modbus动环采集 https://90apt.com/3387十二、ZbxTable分析系统 十三、数据库监控 (一)微软MSSQL数据库监控安装完SQLServer数据库,开启数据库远程访问配置对IP的监听配置防火墙端口开放测试端口RHEL8系统安装ODBC驱动https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver16&tabs=redhat18-install%2Calpine17-install%2Cdebian8-install%2Credhat7-13-install%2Crhel7-offlinesudo su #Download appropriate package for the OS version #Choose only ONE of the following, corresponding to your OS version #RHEL 7 and Oracle Linux 7 curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo #RHEL 8 and Oracle Linux 8 curl https://packages.microsoft.com/config/rhel/8/prod.repo > /etc/yum.repos.d/mssql-release.repo #RHEL 9 curl https://packages.microsoft.com/config/rhel/9.0/prod.repo > /etc/yum.repos.d/mssql-release.repo exit sudo yum remove unixODBC-utf16 unixODBC-utf16-devel #to avoid conflicts sudo ACCEPT_EULA=Y yum install -y msodbcsql18 # optional: for bcp and sqlcmd sudo ACCEPT_EULA=Y yum install -y mssql-tools18 echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc source ~/.bashrc # optional: for unixODBC development headers sudo yum install -y unixODBC-devel配置/etc/odbc.inihttps://learn.microsoft.com/zh-cn/sql/connect/odbc/linux-mac/connection-string-keywords-and-data-source-names-dsns?view=sql-server-ver16[TEST] Driver = ODBC Driver 18 for SQL Server # Server = [protocol:]server[,port] Server = tcp:172.16.10.102,1433 TrustServerCertificate=YES # # Note: # Port isn't a valid keyword in the odbc.ini file # for the Microsoft ODBC driver on Linux or macOS 测试,连接成功isql -v TEST user passwd +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | echo [string] | | quit | | | +---------------------------------------+ SQL> 配置zabbix模板,为目标主机配置一个MSSQL by ODBC在继承以及主机 宏中修改值{$MSSQL.DSN}即上方odbc.ini中定义的[TEST]{$MSSQL.USER}和{$MSSQL.PASSWORD}是自定义的账号密码注意右侧可以选择密文模式保存(二)MYSQL数据库监控为目标主机关联MySQL by Zabbix agent 2模板为MYSQL创建监控专用用户并配置宏mysql -uroot -p use mysql; CREATE USER 'zbx_monitor'@'%' IDENTIFIED BY '<password>'; GRANT REPLICATION CLIENT,PROCESS,SHOW DATABASES,SHOW VIEW ON *.* TO 'zbx_monitor'@'%';{$MYSQL.USER}和{$MYSQL.PASSWORD}是自定义的账号密码注意右侧可以选择密文模式保存十三、分组报警 1、将不同主机的告警发送给不同用户创建主机群组,并将主机添加至主机组,如动环告警 2、为主机添加群组3、创建用户群组动环报警组4、创建用户加入群组创建用户donghuanyonghu,加入动环报警组5、为用户创建报警媒介我这里用企业微信报警6、触发器操作发送报告的触发器7、操作发送群组配置完成十四、总结 功能强大、简单方便、干净卫生
2023年07月07日
1,564 阅读
0 评论
23 点赞
2023-07-07
RHEL8通过ODBC链接SQL Server数据库
安装完SQLServer数据库,开启数据库远程访问配置对IP的监听配置防火墙端口开放测试端口RHEL8系统安装ODBC驱动https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver16&tabs=redhat18-install%2Calpine17-install%2Cdebian8-install%2Credhat7-13-install%2Crhel7-offlinesudo su #Download appropriate package for the OS version #Choose only ONE of the following, corresponding to your OS version #RHEL 7 and Oracle Linux 7 curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo #RHEL 8 and Oracle Linux 8 curl https://packages.microsoft.com/config/rhel/8/prod.repo > /etc/yum.repos.d/mssql-release.repo #RHEL 9 curl https://packages.microsoft.com/config/rhel/9.0/prod.repo > /etc/yum.repos.d/mssql-release.repo exit sudo yum remove unixODBC-utf16 unixODBC-utf16-devel #to avoid conflicts sudo ACCEPT_EULA=Y yum install -y msodbcsql18 # optional: for bcp and sqlcmd sudo ACCEPT_EULA=Y yum install -y mssql-tools18 echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc source ~/.bashrc # optional: for unixODBC development headers sudo yum install -y unixODBC-devel配置/etc/odbc.inihttps://learn.microsoft.com/zh-cn/sql/connect/odbc/linux-mac/connection-string-keywords-and-data-source-names-dsns?view=sql-server-ver16[TEST] Driver = ODBC Driver 18 for SQL Server # Server = [protocol:]server[,port] Server = tcp:172.16.10.102,1433 TrustServerCertificate=YES # # Note: # Port isn't a valid keyword in the odbc.ini file # for the Microsoft ODBC driver on Linux or macOS 测试,连接成功isql -v TEST user passwd +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | echo [string] | | quit | | | +---------------------------------------+ SQL>
2023年07月07日
275 阅读
0 评论
0 点赞
2023-06-28
0基础上手python3编程,批量自动备份交换机配置并进行企业微信通知
架构图 架构图懒得画了,通过telnet备份交换机配置并通知备份结果,展示失败列表;根据命令不同,可以自定义修改用于任意品牌交换机的配置备份。预览 系统组成 由两个文件组成 swtelnet.py config.json代码 由于代码在Windows平台编写,如果在linux平台运行,请把路径中的\换成/swtelnet.pyimport os.path,telnetlib,time,requests,json,codecs def get_config(): config = json.loads(open(path1+"\config.json", encoding='utf-8').read()) return config def gettelnet_config(): nowtime = time.strftime("%Y%m%d", time.localtime()) try: os.mkdir(path1 + "\\" +nowtime) except: None nowdir = (path1 + "\\" +nowtime) for host in config['ip']: try: tn = telnetlib.Telnet(host['host'], timeout=5) tn.write(config['user'].encode('ascii') + b'\n') time.sleep(3) tn.write(config['passwd'].encode('ascii') + b'\n') time.sleep(3) tn.write(b'screen-length disable\n') time.sleep(1) tn.write(b'dis cur\n') time.sleep(1) tn.write(b'undo screen-length disable\n') time.sleep(1) tn.write(b'quit\n') mac1 = tn.read_all() f1 = open(nowdir+"\\"+host['host']+".conf", 'wb') f1.write(mac1) f1.close() flog.write("finish " + host['hostname'] + " " + host['host']+"\n") except: flog.write("fail " + host['hostname'] + " " + host['host']+"\n") def count_sw(): lines = open(path1 + "\\backup.log", "r", encoding='utf-8').readlines() finish = 0 fail = 0 total = 0 failprint = "" for line in lines: line1 = line.split() total = total + 1 if line1[0] == "fail": failprint = failprint + str(line) fail = fail + 1 else: finish = finish + 1 return "交换机备份报告\n总计"+str(total)+" 完成"+str(finish)+" 失败"+str(fail)+"\n备份失败清单:\n"+failprint class network: def yiyan(): try: url = 'https://v1.hitokoto.cn/?c=d&c=k' response = requests.get(url) res = json.loads(response.text) text1 = res['hitokoto'] if res['from'] == None: text2 = "" else: text2 = res['from'] if res['from_who'] == None: text3 = "" else: text3 = res['from_who'] return text1 + " " + text2 + " " + text3 + "\n\n" except: return "一言API故障\n\n" def tianqi(): try: response2 = requests.get(config['weatherapi']) data1 = json.loads(response2.text) data2 = json.dumps(data1['now']) data2 = json.loads(data2) data3 = "环境温度" + data2['temp'] + " 体感温度" + data2['feelsLike'] + " 天气状况 " + data2[ 'text'] + "\n风向 " + data2['windDir'] + " 风力等级" + data2['windScale'] + " 风速" + data2[ 'windSpeed'] + " 湿度" + data2['humidity'] + " 能见度" + data2['vis'] + "公里\n\n" return data3 except: return "天气API故障\n\n" def post_weixin(stats): url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的' body = { "msgtype": "news", "news": { "articles": [ { "title": "AI智慧运维", "description": network.tianqi()+network.yiyan()+stats, "url": "90apt.com", "picurl": "用自己的" } ] } } response = requests.post(url, json=body) print(response.text) print(response.status_code) path1=os.path.abspath('.') config = get_config() flog = codecs.open(path1+"\\backup.log", 'w',encoding='utf-8') gettelnet_config() flog.close() network.post_weixin(count_sw())config.json{ "user" : "用自己的账号", "passwd" : "用自己的密码", "weatherapi" : "https://devapi.qweather.com/用自己的API", "ip" : [ {"host" : "172.16.1.6","hostname" : "仓库6"}, {"host" : "172.16.1.5","hostname" : "仓库5"} ] }总结 简单
2023年06月28日
441 阅读
0 评论
3 点赞
2023-06-25
一种通过DHCP+DNS服务器对内网DHCP客户端进行定向柔性非侵入式劫持的方法
架构图 在我的环境中,由于没有实施严格的网络准入配置,且前期没有全面覆盖EDR,导致出现了一种神奇的现象,态势感知系统检测到某IP中毒,查找主机名资产中查不到,并且主机只在晚上上线,无法定位物理机的实际位置;如果直接断网,可能会引起客户投诉,那么有没有一种柔性的方法解决这个非技术问题呢?有的;在本方法中,可以通过DHCP绑定,固定目标客户端请求的IP,固定后单独设置DNS服务器地址,并且自行架设DNS服务器,将所有请求进行重定向;当目标客户端上网时,任意网站请求均会重定向至拦截页面,拦截页面为http服务器+自定义html页面,方便用户联系处理。预览 目标客户端访问任意网站,均出现拦截提醒。配置 配置DNS服务器https://90apt.com/4048配置DHCP服务器1、为目标保留指定IP2、为目标保留的IP配置独立DNS,目标再次DHCP续约时,DNS地址将被替换3、配置HTTP服务器,监听*域名,同时监听https端口总结 简单实用,用户抵触度低。
2023年06月25日
391 阅读
0 评论
4 点赞
2023-06-25
Python 实现DNS服务器(Python域名解析服务器)
版权声明:本文为CSDN博主「RobinTang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/trbbadboy/article/details/8093256''' Created on 2012-10-15 @author: RobinTang ''' import socketserver import struct # DNS Query class SinDNSQuery: def __init__(self, data): i = 1 self.name = '' while True: d = data[i] if d == 0: break; if d < 32: self.name = self.name + '.' else: self.name = self.name + chr(d) i = i + 1 self.querybytes = data[0:i + 1] (self.type, self.classify) = struct.unpack('>HH', data[i + 1:i + 5]) self.len = i + 5 def getbytes(self): return self.querybytes + struct.pack('>HH', self.type, self.classify) # DNS Answer RRS # this class is also can be use as Authority RRS or Additional RRS class SinDNSAnswer: def __init__(self, ip): self.name = 49164 self.type = 1 self.classify = 1 self.timetolive = 190 self.datalength = 4 self.ip = ip def getbytes(self): res = struct.pack('>HHHLH', self.name, self.type, self.classify, self.timetolive, self.datalength) s = self.ip.split('.') res = res + struct.pack('BBBB', int(s[0]), int(s[1]), int(s[2]), int(s[3])) return res # DNS frame # must initialized by a DNS query frame class SinDNSFrame: def __init__(self, data): (self.id, self.flags, self.quests, self.answers, self.author, self.addition) = struct.unpack('>HHHHHH', data[0:12]) self.query = SinDNSQuery(data[12:]) def getname(self): return self.query.name def setip(self, ip): self.answer = SinDNSAnswer(ip) self.answers = 1 self.flags = 33152 def getbytes(self): res = struct.pack('>HHHHHH', self.id, self.flags, self.quests, self.answers, self.author, self.addition) res = res + self.query.getbytes() if self.answers != 0: res = res + self.answer.getbytes() return res # A UDPHandler to handle DNS query class SinDNSUDPHandler(socketserver.BaseRequestHandler): def handle(self): data = self.request[0].strip() dns = SinDNSFrame(data) socket = self.request[1] namemap = SinDNSServer.namemap if(dns.query.type==1): # If this is query a A record, then response it name = dns.getname(); if namemap.__contains__(name): # If have record, response it dns.setip(namemap[name]) socket.sendto(dns.getbytes(), self.client_address) elif namemap.__contains__('*'): # Response default address dns.setip(namemap['*']) socket.sendto(dns.getbytes(), self.client_address) else: # ignore it socket.sendto(data, self.client_address) else: # If this is not query a A record, ignore it socket.sendto(data, self.client_address) # DNS Server # It only support A record query # user it, U can create a simple DNS server class SinDNSServer: def __init__(self, port=53): SinDNSServer.namemap = {} self.port = port def addname(self, name, ip): SinDNSServer.namemap[name] = ip def start(self): HOST, PORT = "0.0.0.0", self.port server = socketserver.UDPServer((HOST, PORT), SinDNSUDPHandler) server.serve_forever() # Now, test it if __name__ == "__main__": sev = SinDNSServer() sev.addname('www.aa.com', '192.168.0.1') # add a A record sev.addname('www.bb.com', '192.168.0.2') # add a A record sev.addname('*', '0.0.0.0') # default address sev.start() # start DNS server # Now, U can use "nslookup" command to test it # Such as "nslookup www.aa.com"
2023年06月25日
348 阅读
0 评论
1 点赞
1
...
7
8
9
...
21