Fork me on GitHub

python 简单示例

快速启动一个本地服务 可临时充当文件下载服务 # python2 python -m SimpleHTTPServer 8888 # python3 python3 -m http.server 8888 flask 服务 from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): result = find_result() return result @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': pass else: pass if __name__ == '__main__': app.run(host='0.0.0.0',port='8000') python app.py gunicorn -w 1 -b 127.0.0.1:4000 app:app 操作PG数据库 import psycopg2 import time conn = None try: conn = psycopg2.connect(database="postgres", user="postgres", host="192.168.*.*", port="5432",password='*****') print("Opened database successfully") cur = conn.cursor() cur.execute("select * from api") rows = cur.fetchall() result = '' all_field = cur.description for filed in all_field: print(filed[0]) for row in rows: result += str(row[0]) result += "\n" print(result) print("Operation done successfully") conn.close() except Exception as e:……

阅读全文

长轮询

长轮询 实现原理: 与传统的轮询方式不同的是,当服务端接收到客户端的请求的时候,如果没有最新消息时不是立刻返回请求,而是等待一个最大超时时间。如果等待期间有最新消息则立刻返回。 相对于暴力的轮询,长轮询能够很大程度的减少客户端与服务端的连接进而缓解服务端的压力。 利用长轮询模拟推送服务,……

阅读全文

联想搜索

Redis 联想搜索实现 基于redis ZSET 例子: 当输入n时显示所有n开头的数据,当输入nb时显示所有nb开头的数据。 # 数据录入 127.0.0.1:6379> ZADD ss 0 'n' (integer) 1 127.0.0.1:6379> ZADD ss 0 'nb' (integer) 1 127.0.0.1:6379> ZADD ss 0 'nba' (integer) 1 # 搜索n 127.0.0.1:6379> ZRANK ss 'n' (integer) 0 127.0.0.1:6379> ZRANGE ss 0 -1 1) "n" 2) "nb" 3) "nba" # 搜索nb 127.0.0.1:6379> ZRANK ss 'nb' (integer) 1 127.0.0.1:6379> ZRANGE ss 1 -1 1) "nb" 2) "nba"……

阅读全文

消息推送

基于jango channel 实现推送 在官方demo 的基础上自定义推送 Consumer 。 由于只是服务端到客户端单方向推送信息。类中只实现如下3个方法即可 """ connect 建立连接 disconnet 断开连接 push_messages 推送消息 """ from channels.generic.websocket import AsyncWebsocketConsumer # # 推送consumer class PushConsumer(AsyncWebsocketConsumer): async def connect(self): # 将username名称设定为 group 名 # self.group_name = self.scope['url_route']['kwargs']['username'] self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code):……

阅读全文

数据库日志分析

数据库日志分析 整体架构 filebeat -> logstash -> elasticseach -> kibana filebeat 收集日志 logstash 中转及日志规则匹配过滤 elasticsearch 日志存储检索库 kibana 查看界面 postgresql log_destination = 'csvlog' logging_collector = 'on' log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' log_rotation_age = '1d' log_rotation_size = '100MB' log_min_messages = 'info' log_min_duration_statement = '1000' log_statement = 'ddl' filebeat filebeat.inputs: - type: log enabled: true paths: - /var/lib/pgsql/***/postgresql-*.csv fields: log_topics: postgresql multiline.pattern: '^[[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} [A-Z]{3}' multiline.negate: true multiline.match: after filebeat.config.modules: path: ${path.config}/modules.d/*.yml reload.enabled: false setup.template.settings: index.number_of_shards: 1 tags: ["postgesql"] setup.kibana: output.logstash: hosts: ["*.*.*.*:5044"] processors: - add_host_metadata: ~ - add_cloud_metadata: ~ logstash # # this config is use for version logstash 7.3.1 # input { beats { port => 5044 } #sdtin{ # #} } #……

阅读全文

Linux 找出隐藏进程

原理 在top ps 等命令被改写时,利用Linux一切皆文件。找出被隐藏的进程。 以下为python脚本 #!/usr/bin/env python # -*- coding: utf-8 -*- import os def get_max_pid(): out = os.popen('cat /proc/sys/kernel/pid_max') content = out.readline().strip('\n') if content.isdigit(): return int(content) def get_ps_proc_list(): pid_list = [] out = os.popen('ps -e --no-header') lines = out.readlines() for line in lines: parts = line.split(' ') for part in parts: if part == '': parts.remove(part) pid = int(parts[0]) pid_list.append(pid) return pid_list def get_ps_lwp_list(): lwp_list = [] out = os.popen('ps --no-header -eL o lwp') lines = out.readlines() for line in lines: tid = int(line) lwp_list.append(tid) return lwp_list def print_badpid_info(pid): out = os.popen('ls -l /proc/%d/exe' % pid)……

阅读全文

Wazuh 功能简介

日志收集 客户端配置,指定需要收集系统日志及日志格式。默认如下 <ossec_config> <localfile> <log_format>audit</log_format> <location>/var/log/audit/audit.log</location> </localfile> <localfile> <log_format>syslog</log_format> <location>/var/ossec/logs/active-responses.log</location> </localfile> <localfile> <log_format>syslog</log_format> <location>/var/log/messages</location> </localfile> <localfile> <log_format>syslog</log_format> <location>/var/log/secure</location> </localfile> <localfile> <log_format>syslog</log_format> <location>/var/log/maillog</location> </localfile> 系统命令 客户端配置,设置系统监控执行命令及频率。默认如下 # 系统文件 <localfile> <log_format>command</log_format> <command>df -P</command> <frequency>360</frequency> </localfile> # 端口 <localfile> <log_format>full_command</log_format> <command>netstat -tulpn | sed 's/\([[:alnum:]]\+\)\ \+[[:digit:]]\+\ \+[[:digit:]]\+\ \+\(.*\):\([[:digit:]]*\)\ \+\([0-9\.\:\*]\+\).\+\ \([[:digit:]]*\/[[:alnum:]\-]*\).*/\1 \2 == \3 = = \4 \5/' | sort -k 4 -g | sed 's/ == \(.*\) ==/:\1/' | sed 1,2d</command> <alias>netstat listening ports</alias> <frequency>360</frequency> </localfile> # 登陆日志 <localfile> <log_format>full_command</log_format> <command>last -n……

阅读全文

Linux 系统登陆记录

背景 登陆系统时,尤其是具有外网ip的主机时经常会看到类似如下信息。 There were 12039 failed login attempts since the last successful login. 说明你的系统被尝试登陆破解。 大部分的破解基本都是自动机器扫描,配合自己的数据字典暴力破解。 系统登陆成功记录 查看命令 last 原理 读取解析 /var/log/wtmp 例如: 查看最近十次登陆记录 last -10 查看某个时间段的登陆记录 last -s 2021-10-10 -t……

阅读全文

Ubuntu20.04 装机后

关闭cloud init systemctl stop cloud-init-local cloud-init cloud-config cloud-final systemctl disable cloud-init-local cloud-init cloud-config cloud-final……

阅读全文