记录使用Python监控服务器日志。

后续直接使用了宏,因此这个Python脚本没用了,但是还是觉得有意义,所以记下来。

#!/usr/bin/env python3
#encoding=utf-8
import os
import socket
from pyzabbix import ZabbixAPI, ZabbixAPIException
import sys
import warnings
import time

ServerName=”ServerNameHere”
Username=’usernamehere’
Passwd=’passwdhere’
Url=’https://zabbix.mytlu.cn’
FileDir=’/var/log/’
MonitorFilename=’/log’

def CheckHostip(filedir):
output = os.popen(‘find ‘+filedir+’* -maxdepth 0 -type d’)
hostip = str(output.read())
hostip = hostip[:hostip.find(‘\r’)]
hostdirlist = hostip.split(‘\n’)
return (hostdirlist)

def CheckZabbixItems(LogDir):
warnings.filterwarnings(‘ignore’)
ZABBIX_SERVER = Url
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.session.verify = False
zapi.login(Username, Passwd)
hostid=zapi.host.get(
filter={
“host”:ServerName
}
)
hostid=hostid[0][‘hostid’]
pre_interfaceid = zapi.hostinterface.get(
hostids=hostid
)
interfaceid = pre_interfaceid[0][‘interfaceid’]
try:
itemget = zapi.item.get(
hostid=hostid,
search={
“key_”: “vfs.file.md5sum[“+LogDir+MonitorFilename+”]”
},
sortfield=”name”
)
print(itemget)
if itemget == []:
print(‘zabbix里没有该监控项,添加中监控项和触发器中…’)
CreateItems(LogDir, interfaceid, hostid)
CreateTrigger(LogDir)
return 1
else:
print(‘zabbix里有该监控项,尝试添加中触发器中…’)
try:
CreateTrigger(LogDir)
except:
return 0
return 1
except Exception as e:
print(‘zabbix里没有该监控项,添加中监控项和触发器中…’)
CreateItems(LogDir,interfaceid,hostid)
CreateTrigger(LogDir)
return 1

def CreateItems(LogDir,interfaceid,hostid):
warnings.filterwarnings(‘ignore’)
ZABBIX_SERVER = Url
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.session.verify = False
zapi.login(Username,Passwd)
item = zapi.item.create(name=”Monitor_Log:”+LogDir+MonitorFilename,
key_=”vfs.file.md5sum[“+LogDir+MonitorFilename+”]”,
hostid=hostid,
type=0,
value_type=1,
delay=”10s”,
interfaceid=interfaceid
)
print(item)
return 1

def CreateTrigger(LogDir):
warnings.filterwarnings(‘ignore’)
ZABBIX_SERVER = Url
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.session.verify = False
zapi.login(Username, Passwd)
trigger = zapi.trigger.create(
description=”[“+LogDir+MonitorFilename+”]:Log not changed in 1s”,
expression=”{“+ServerName+”:vfs.file.md5sum[“+LogDir+MonitorFilename+”].change()}=0″,
priority=’4′,
manual_close=’1′

)
print(trigger)
return 1

if __name__==’__main__’:
hostdirlist=CheckHostip(FileDir)
print(hostdirlist)
for i in hostdirlist:
CheckZabbixItems(i)

Centos 7 添加Systemct任务 配置开机自启

[Unit]
Description=Simple-Drive.mytlu.python
After=network-online.target
[Service]
User=root
Type=simple
#Environment=”PATH=/simpledrive-demo”
WorkingDirectory=/simpledrive-demo
ExecStart=/usr/local/bin/python3 -u /simpledrive-demo/main.py > /simpledrive-demo/main.log 2>&1
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
KillMode=process
Restart=no
[Install]
WantedBy=multi-user.target
WantedBy=graphical.target

注意,Environment以及WorkingDirectory都在配置文件里。WorkingDirectory对于Python运行比较重要。另外,该文件存于/usr/lib/systemd/system/simpledrive-demo.mytlu.python.service。另外运行完记得systemctl daemon-reload来刷新。

以下*代替相关服务。

systemctl start * 开启service

systemctl enable * 开启开机自启

systemctl status * -l 查看服务状态。

Zabbix 监控Mysql Slave

  1. userparameter_mysql_slave_status.conf 放置到 /etc/zabbix/zabbix_agent.d/下。

详细配置内容:

# For all the following commands HOME should be set to the directory that has .my.cnf file with password information.

# Flexible parameter to grab global variables. On the frontend side, use keys like mysql.status[Com_insert].
# Key syntax is mysql.status[variable].
UserParameter=mysql.slave.status[*], echo ‘show slave status\G;’ | mysql | awk ‘$$1 ~ /$1/ {print $$2}’

# Flexible parameter to determine database or table size. On the frontend side, use keys like mysql.size[zabbix,history,data].
# Key syntax is mysql.size[,

,].
# Database may be a database name or “all”. Default is “all”.
# Table may be a table name or “all”. Default is “all”.
# Type may be “data”, “index”, “free” or “both”. Both is a sum of data and index. Default is “both”.
# Database is mandatory if a table is specified. Type may be specified always.
# Returns value in bytes.
# ‘sum’ on data_length or index_length alone needed when we are getting this information for whole database instead of a single table

2. 修改上述配置文件中 UserParameter=mysql.slave.status[*], echo ‘show slave status\G;’ | mysql | awk ‘$$1 ~ /$1/ {print $$2}’

具体来说,如果.my.cnf在 /etc/zabbix下。那么改为:

UserParameter=mysql.slave.status[*], echo ‘show slave status\G;’ |HOME=/etc/zabbix mysql | awk ‘$$1 ~ /$1/ {print $$2}’

参考文档

如何解决服务器访问/加载过慢

最近发现本站点服务器访问缓慢,检查发现以下问题:

  1. 架构:云服务器代理>SSH打洞>本地树莓派服务器。云代理服务器每次接收到请求后,都需要通过SSH打洞转发到本地树莓派服务器,本地服务器与云服务器的延迟被反复放大。
  2. 服务器TCP连接卡在TIME_W上的进程特别多。查看服务器连接数:
[root@localhost etc]# netstat -ant | grep $ip:80 | grep TIME_W | wc -l
421
[root@localhost etc]# netstat -ant|awk '/^tcp/ {++S[$NF]} END {for(a in S) print (a,S[a])}'
LISTEN 23
SYN_RECV 14
CLOSE_WAIT 61
ESTABLISHED 32
FIN_WAIT2 57
TIME_WAIT 430
[root@localhost etc]# netstat -ant | grep $ip:80 |wc -l
578
[root@localhost etc]# netstat -ant | grep $ip:80 | grep TIME_W | wc -l
450
[root@localhost etc]#  netstat -ant | grep $ip:80 | grep ESTABLISHED | wc -l
6
[root@localhost etc]# 

3. 云服务器带宽过低,1M带宽。

初步解决方案:

  1. 暂时没什么好的办法。
  2. 参考 这篇文章,尝试优化服务器TCP连接,没卵用,已回退。而且这里面的”net.ipv4.tcp_tw_recycle “,Centos7已弃用。
  3. 掏钱,升级云服务器带宽,效果拔群。

总结:花钱是最快的办法。

Mysql数据库备份与恢复

1.数据库备份

mysqldump -u用户名 -p密码  --opt --skip-lock-tables 数据库名 > /备份文件夹/文件名.sql

注意:-p密码可以省略,密码明文出现,会在history中留记录,不安全。skip-lock-tables选项,不锁数据库备份,加速备份速度。

2. 数据库备份文件还原

mysql -u用户名 -p密码 < /备份文件夹/文件名.sql

注意,同样不建议明文密码。

树莓派检测CPU温度

代码是Python2代码,适当修改为长输出。可自行改为python3.

代码附赠了CPU负载和内存使用情况

代码引用地址:
https://gist.github.com/582033/b94dc1d4941f63bb28d837fa9c72f08d

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
显示树莓派cpu温度、使用率及内存使用率
'''

import os
import time

def show_temp():
    file = open("/sys/class/thermal/thermal_zone0/temp")
    temp = float(file.read()) / 1000
    file.close()
    print "Temp: %.1f ℃" %temp


def show_mem():
    mem_cmd = "free -m | grep Mem | awk '{print ($4+$6)/$2}'"
    mem_sur = round(float(os.popen(mem_cmd).read()), 2) * 100
    print "Mem avail: %d%%" % mem_sur


def show_cpu():
    cpu_cmd = "uptime | awk '{print $8,$9,$10,$11,$12}'"
    cpu_used = os.popen(cpu_cmd).read()
    print "Cpu Used: %s" % cpu_used.replace('\n', '')


if __name__ == '__main__':

    while 1:
        show_temp()
        show_cpu()
        show_mem()
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        time.sleep(2)

树莓派SSH打洞再探

详细打洞方案请参考
https://blog.mytlu.cn/?p=6

目前,将云端的俩个Python Flask WEB服务迁移到本地树莓派上,并SSH打洞发布。添加Systemctl开机自启。

将本地树莓派Centos7 22端口映射到公网服务器某端口。测试可用

本地树莓派状态可以通过之前写的SimpleDrive-demo的调试页面看到。

网址:
https://simpledrive-demo.mytlu.cn/serverstatus

复制状态信息如下:

有新版本103可更新
以下是系统信息(每隔5秒自动刷新):
操作系统:Linux
(‘内存已使用:’, 336.015625, ‘M’, ‘总内存:’, 924.9921875, ‘M’, ‘内存占比:’, 38.8, ‘cpu个数:’, 4)
守护进程信息:
待添加
以下是磁盘信息/单位(G)
总计:13.839794158935547 已用:4.8215179443359375 剩余: 8.988677978515625 已用比例:34.9

树莓派SSH打洞初探

前几天跟某位大佬聊天的时候,我说我为了能把本地网站发布到网上,使用Openvpn,云服务器开启Openvpn主机,本地连接过去,然后云服务器nginx代理发布到网上。大佬说,你这样挺麻烦的,你试试ssh打洞。

今天在家实在想找点事做(主要是心情不爽),就折腾起树莓派,结果给我折腾成功了,以下是方案总结:

  1. 方案为:树莓派安装wordpress,通过ssh打洞,云主机nginx代理到公网。
  2. 在树莓派上执行以下命令,安装wordpress

yum install httpd mariadb-server -y

3. 初始化Mariadb以及添加数据库,安装wordpress不再赘述。可以自行百度。这里提供mariadb的一个初始化教程,以便后续遗忘。
https://www.cnblogs.com/dxxblog/p/10243057.html

4. 本地服务器生成ssh key

ssh-keygen

5. 拷贝本地ssh key到远程云主机,目的:免密登录。-p参数:如果远程主机ssh端口默认不是22,需要该参数,本人不是22端口

ssh-copy-id -p 端口号 username@host

6. 安装autossh。一般centos直接输入命令 yum install autossh -y即可。博主是Centos 7 arm架构的树莓派,yum里没有autossh,采用以下办法编译安装:

#wget https://armv7.dev.centos.org/repodir/epel-pass-1/autossh/1.4g-1.el7/armv7hl/autossh-1.4g-1.el7.armv7hl.rpm

可以使用自建mirror啦>>

wget https://mirror.fastspeedgo.xyz/raspberryMirror/autossh-1.4g-1.el7.armv7hl.rpm

yum install autossh-1.4g-1.el7.armv7hl.rpm

7. Systemctl中添加服务

vi /lib/systemd/system/autossh.service

填入以下内容,请注意,User=,填入使用 ssh-keygen的用户,它影响ExecStart那行中的’
/root/.ssh/id_rsa ‘,是否是‘ /root/.ssh/id_rsa ’得看你是使用什么用户生成,如果不太明白,请百度”ssh-keygen “。

另,ExecStart这行, -M 5678主要是用于监控ssh是否需要重连,具体参考
https://www.cnblogs.com/itech/p/4572275.html

[Unit]
Description=Auto SSH Tunnel
After=network-online.target
[Service]
User=root
Type=simple
ExecStart=/usr/bin/autossh -M 5678 -NR 远程服务器端口:localhost:本地端口 -i /root/.ssh/id_rsa username@host -p 端口号 >> /dev/null 2>&1
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
KillMode=process
Restart=no
[Install]
WantedBy=multi-user.target
WantedBy=graphical.target

8. 设置autossh开机自启,启动服务

systemctl enable autossh

systemctl start autossh

(注意,此时默认远程服务器监听127.0.0.1地址,如需要监听0.0.0.0,请更改/etc/ssh/sshd_config中的GatewayPorts为yes。参考
http://www.mamicode.com/info-detail-1030313.html

9 在云服务器上测试是否成功打通:(端口号是第七步里命令行里的远程服务器端口 )

wget http://localhost:端口号

10. 快速配置nginx代理。不多赘述,这里贴个conf文件样例。

server {
listen 80;
listen [::]:80;
server_name blog.mytlu.cn;
# enforce https
return 301 https://blog.mytlu.cn;
}

server
{
listen 443 ssl http2;
#listen [::]:443 ssl http2;
server_name blog.mytlu.cn;
index index.html index.htm index.php default.html default.htm default.php;
access_log /var/log/nginx/sample;

    ssl_certificate /*.crt;
    ssl_certificate_key /*.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
    ssl_session_cache builtin:1000 shared:SSL:10m;
            proxy_redirect http:// $scheme://;
    port_in_redirect on;
    location ~ ^/ {
proxy_buffering off;
       proxy_pass http://localhost:端口号;
       proxy_http_version 1.1;
               proxy_set_header  Host $host:$server_port;
      # proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header User-Agent;
#proxy_pass_header X-Forwarded-Proto;
proxy_set_header X-Forwarded-Proto $scheme;
       client_max_body_size 10240M;
       client_body_timeout 5m;

      }

}

10. 部分参考网站链接:

https://www.cnblogs.com/itech/p/4572275.html

http://imhuchao.com/872.html