zoukankan      html  css  js  c++  java
  • zabbix4.0监控Nginx1.15.8配置记录

    Last login: Sun Mar 17 20:20:35 2019 from 10.0.0.3
    [root@vmhzpnginx ~]# cd /etc/zabbix
    [root@vmhzpnginx zabbix]# ls
    zabbix_agentd.conf zabbix_agentd.d
    [root@vmhzpnginx zabbix]# cp zabbix_agentd.conf zabbix_agentd.conf.bak
    [root@vmhzpnginx zabbix]# ls
    zabbix_agentd.conf zabbix_agentd.conf.bak zabbix_agentd.d
    [root@vmhzpnginx zabbix]# cd /etc/nginx
    [root@vmhzpnginx nginx]# ls
    client_body_temp fastcgi_temp logs sbin uwsgi_temp
    conf html proxy_temp scgi_temp
    [root@vmhzpnginx nginx]# cd conf
    [root@vmhzpnginx conf]# ls
    fastcgi.conf mime.types scgi_params.default
    fastcgi.conf.default mime.types.default uwsgi_params
    fastcgi_params nginx.conf uwsgi_params.default
    fastcgi_params.default nginx.conf.bak win-utf
    koi-utf nginx.conf.default
    koi-win scgi_params
    [root@vmhzpnginx conf]# cat nginx.conf

    #user nobody;
    worker_processes 1;

    #error_log logs/error.log;
    #error_log logs/error.log notice;
    #error_log logs/error.log info;

    #pid logs/nginx.pid;


    events {
    worker_connections 1024;
    }


    http {
    include mime.types;
    default_type application/octet-stream;

    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log logs/access.log main;

    sendfile on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    #gzip on;

    server {
    listen 80;
    server_name localhost;

    #charset koi8-r;

    #access_log logs/host.access.log main;

    location / {
    root html;
    index index.html index.htm;
    }

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    # proxy_pass http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ .php$ {
    # root html;
    # fastcgi_pass 127.0.0.1:9000;
    # fastcgi_index index.php;
    # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    # include fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /.ht {
    # deny all;
    #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    # listen 8000;
    # listen somename:8080;
    # server_name somename alias another.alias;

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}


    # HTTPS server
    #
    #server {
    # listen 443 ssl;
    # server_name localhost;

    # ssl_certificate cert.pem;
    # ssl_certificate_key cert.key;

    # ssl_session_cache shared:SSL:1m;
    # ssl_session_timeout 5m;

    # ssl_ciphers HIGH:!aNULL:!MD5;
    # ssl_prefer_server_ciphers on;

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}

    }
    [root@vmhzpnginx conf]# cd /home
    [root@vmhzpnginx home]# ls
    nginx-1.15.8 pcre-8.38 www
    nginx-1.15.8.tar.gz pcre-8.38.tar.gz zabbix-get-4.0.0-2.el7.x86_64.rpm
    [root@vmhzpnginx home]# rpm -qa| grep python
    python-2.7.5-76.el7.x86_64
    libselinux-python-2.5-14.1.el7.x86_64
    python-iniparse-0.4-9.el7.noarch
    python-urlgrabber-3.10-9.el7.noarch
    python-slip-dbus-0.4.0-4.el7.noarch
    python-libs-2.7.5-76.el7.x86_64
    python-decorator-3.4.0-3.el7.noarch
    python-slip-0.4.0-4.el7.noarch
    python-linux-procfs-0.4.9-4.el7.noarch
    newt-python-0.52.15-4.el7.x86_64
    python-perf-3.10.0-957.el7.x86_64
    python-configobj-4.7.2-7.el7.noarch
    python-gobject-base-3.22.0-1.el7_4.1.x86_64
    python-pycurl-7.19.0-19.el7.x86_64
    dbus-python-1.1.1-9.el7.x86_64
    python-firewall-0.5.3-5.el7.noarch
    python-schedutils-0.4-6.el7.x86_64
    python-pyudev-0.15-9.el7.noarch
    rpm-python-4.11.3-35.el7.x86_64
    [root@vmhzpnginx home]# whereis python
    python: /usr/bin/python /usr/bin/python2.7 /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/include/python2.7 /usr/share/man/man1/python.1.gz
    [root@vmhzpnginx home]# ls
    nginx-1.15.8 pcre-8.38 www
    nginx-1.15.8.tar.gz pcre-8.38.tar.gz zabbix-get-4.0.0-2.el7.x86_64.rpm
    [root@vmhzpnginx home]# wget https://github.com/adubkov/zbx_nginx_template/archive/master.zip
    --2019-03-18 08:26:49-- https://github.com/adubkov/zbx_nginx_template/archive/master.zip
    Resolving github.com (github.com)... 52.74.223.119, 13.229.188.59, 13.250.177.223
    Connecting to github.com (github.com)|52.74.223.119|:443... connected.
    HTTP request sent, awaiting response... 302 Found
    Location: https://codeload.github.com/adubkov/zbx_nginx_template/zip/master [following]
    --2019-03-18 08:26:49-- https://codeload.github.com/adubkov/zbx_nginx_template/zip/master
    Resolving codeload.github.com (codeload.github.com)... 13.229.189.0, 13.250.162.133, 54.251.140.56
    Connecting to codeload.github.com (codeload.github.com)|13.229.189.0|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: unspecified [application/zip]
    Saving to: ‘master.zip’

    [ <=> ] 5,524 22.9KB/s in 0.2s

    2019-03-18 08:26:50 (22.9 KB/s) - ‘master.zip’ saved [5524]

    [root@vmhzpnginx home]# ls
    master.zip pcre-8.38 zabbix-get-4.0.0-2.el7.x86_64.rpm
    nginx-1.15.8 pcre-8.38.tar.gz
    nginx-1.15.8.tar.gz www
    [root@vmhzpnginx home]# yum install -y unzip zip
    Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
    * base: mirrors.shu.edu.cn
    * extras: mirrors.aliyun.com
    * updates: mirrors.cn99.com
    base | 3.6 kB 00:00:00
    extras | 3.4 kB 00:00:00
    updates | 3.4 kB 00:00:00
    Resolving Dependencies
    --> Running transaction check
    ---> Package unzip.x86_64 0:6.0-19.el7 will be installed
    ---> Package zip.x86_64 0:3.0-11.el7 will be installed
    --> Finished Dependency Resolution

    Dependencies Resolved

    =================================================================================
    Package Arch Version Repository Size
    =================================================================================
    Installing:
    unzip x86_64 6.0-19.el7 base 170 k
    zip x86_64 3.0-11.el7 base 260 k

    Transaction Summary
    =================================================================================
    Install 2 Packages

    Total download size: 430 k
    Installed size: 1.1 M
    Downloading packages:
    (1/2): unzip-6.0-19.el7.x86_64.rpm | 170 kB 00:00:00
    (2/2): zip-3.0-11.el7.x86_64.rpm | 260 kB 00:00:00
    ---------------------------------------------------------------------------------
    Total 1.2 MB/s | 430 kB 00:00
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
    Warning: RPMDB altered outside of yum.
    Installing : zip-3.0-11.el7.x86_64 1/2
    Installing : unzip-6.0-19.el7.x86_64 2/2
    Verifying : unzip-6.0-19.el7.x86_64 1/2
    Verifying : zip-3.0-11.el7.x86_64 2/2

    Installed:
    unzip.x86_64 0:6.0-19.el7 zip.x86_64 0:3.0-11.el7

    Complete!
    [root@vmhzpnginx home]# unzip master.zip
    Archive: master.zip
    e3484c88ee0cd9fb5ffa6765b8c3e0cf55c1e4f2
    creating: zbx_nginx_template-master/
    inflating: zbx_nginx_template-master/README.md
    inflating: zbx_nginx_template-master/zbx_nginx_stats.py
    inflating: zbx_nginx_template-master/zbx_nginx_templates.xml
    [root@vmhzpnginx home]# ls
    master.zip pcre-8.38 zabbix-get-4.0.0-2.el7.x86_64.rpm
    nginx-1.15.8 pcre-8.38.tar.gz zbx_nginx_template-master
    nginx-1.15.8.tar.gz www
    [root@vmhzpnginx home]# cd zbx_nginx_template-master
    [root@vmhzpnginx zbx_nginx_template-master]# ls
    README.md zbx_nginx_stats.py zbx_nginx_templates.xml
    [root@vmhzpnginx zbx_nginx_template-master]# ll
    total 56
    -rwxr-xr-x 1 root root 1979 Dec 16 2017 README.md
    -rwxr-xr-x 1 root root 5614 Dec 16 2017 zbx_nginx_stats.py
    -rwxr-xr-x 1 root root 42775 Dec 16 2017 zbx_nginx_templates.xml
    [root@vmhzpnginx zbx_nginx_template-master]# pwd
    /home/zbx_nginx_template-master
    [root@vmhzpnginx zbx_nginx_template-master]# cd /etc/zabbix
    [root@vmhzpnginx zabbix]# ls
    zabbix_agentd.conf zabbix_agentd.conf.bak zabbix_agentd.d
    [root@vmhzpnginx zabbix]# mkdir scripts
    [root@vmhzpnginx zabbix]# cd scripts
    [root@vmhzpnginx scripts]# ls
    [root@vmhzpnginx scripts]# pwd
    /etc/zabbix/scripts
    [root@vmhzpnginx scripts]# cd /home/zbx_nginx_template-master
    [root@vmhzpnginx zbx_nginx_template-master]# ls
    README.md zbx_nginx_stats.py zbx_nginx_templates.xml
    [root@vmhzpnginx zbx_nginx_template-master]# cp zbx_nginx_stats.py /etc/zabbix/scripts
    [root@vmhzpnginx zbx_nginx_template-master]# cd /etc/zabbix/scripts
    [root@vmhzpnginx scripts]# ls
    zbx_nginx_stats.py
    [root@vmhzpnginx scripts]# cat zbx_nginx_stats.py
    #!/usr/bin/python

    import urllib2, base64, re, struct, time, socket, sys, datetime, os.path

    try:
    import json
    except:
    import simplejson as json

    zabbix_host = '127.0.0.1' # Zabbix server IP
    zabbix_port = 10051 # Zabbix server port
    hostname = 'Zabbix Agent' # Name of monitored host, like it shows in zabbix web ui
    time_delta = 1 # grep interval in minutes

    # URL to nginx stat (http_stub_status_module)
    stat_url = 'https://nginx.server/nginx_stat'

    # Nginx log file path
    nginx_log_file_path = '/var/log/nginx/access.log'

    # Optional Basic Auth
    username = 'user'
    password = 'pass'

    # Temp file, with log file cursor position
    seek_file = '/tmp/nginx_log_stat'


    class Metric(object):
    def __init__(self, host, key, value, clock=None):
    self.host = host
    self.key = key
    self.value = value
    self.clock = clock

    def __repr__(self):
    if self.clock is None:
    return 'Metric(%r, %r, %r)' % (self.host, self.key, self.value)
    return 'Metric(%r, %r, %r, %r)' % (self.host, self.key, self.value, self.clock)

    def send_to_zabbix(metrics, zabbix_host='127.0.0.1', zabbix_port=10051):

    j = json.dumps
    metrics_data = []
    for m in metrics:
    clock = m.clock or ('%d' % time.time())
    metrics_data.append(('{"host":%s,"key":%s,"value":%s,"clock":%s}') % (j(m.host), j(m.key), j(m.value), j(clock)))
    json_data = ('{"request":"sender data","data":[%s]}') % (','.join(metrics_data))
    data_len = struct.pack('<Q', len(json_data))
    packet = 'ZBXDx01'+ data_len + json_data

    #print packet
    #print ':'.join(x.encode('hex') for x in packet)

    try:
    zabbix = socket.socket()
    zabbix.connect((zabbix_host, zabbix_port))
    zabbix.sendall(packet)
    resp_hdr = _recv_all(zabbix, 13)
    if not resp_hdr.startswith('ZBXDx01') or len(resp_hdr) != 13:
    print 'Wrong zabbix response'
    return False
    resp_body_len = struct.unpack('<Q', resp_hdr[5:])[0]
    resp_body = zabbix.recv(resp_body_len)
    zabbix.close()

    resp = json.loads(resp_body)
    #print resp
    if resp.get('response') != 'success':
    print 'Got error from Zabbix: %s' % resp
    return False
    return True
    except:
    print 'Error while sending data to Zabbix'
    return False


    def _recv_all(sock, count):
    buf = ''
    while len(buf)<count:
    chunk = sock.recv(count-len(buf))
    if not chunk:
    return buf
    buf += chunk
    return buf


    def get(url, login, passwd):
    req = urllib2.Request(url)
    if login and passwd:
    base64string = base64.encodestring('%s:%s' % (login, passwd)).replace(' ', '')
    req.add_header("Authorization", "Basic %s" % base64string)
    q = urllib2.urlopen(req)
    res = q.read()
    q.close()
    return res

    def parse_nginx_stat(data):
    a = {}
    # Active connections
    a['active_connections'] = re.match(r'(.*):s(d*)', data[0], re.M | re.I).group(2)
    # Accepts
    a['accepted_connections'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(1)
    # Handled
    a['handled_connections'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(2)
    # Requests
    a['handled_requests'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(3)
    # Reading
    a['header_reading'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(2)
    # Writing
    a['body_reading'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(4)
    # Waiting
    a['keepalive_connections'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(6)
    return a


    def read_seek(file):
    if os.path.isfile(file):
    f = open(file, 'r')
    try:
    result = int(f.readline())
    f.close()
    return result
    except:
    return 0
    else:
    return 0

    def write_seek(file, value):
    f = open(file, 'w')
    f.write(value)
    f.close()


    #print '[12/Mar/2014:03:21:13 +0400]'

    d = datetime.datetime.now()-datetime.timedelta(minutes=time_delta)
    minute = int(time.mktime(d.timetuple()) / 60)*60
    d = d.strftime('%d/%b/%Y:%H:%M')

    total_rps = 0
    rps = [0]*60
    tps = [0]*60
    res_code = {}

    nf = open(nginx_log_file_path, 'r')

    new_seek = seek = read_seek(seek_file)

    # if new log file, don't do seek
    if os.path.getsize(nginx_log_file_path) > seek:
    nf.seek(seek)

    line = nf.readline()
    while line:
    if d in line:
    new_seek = nf.tell()
    total_rps += 1
    sec = int(re.match('(.*):(d+):(d+):(d+)s.*]', line).group(4))
    code = re.match(r'(.*)"s(d*)s', line).group(2)
    if code in res_code:
    res_code[code] += 1
    else:
    res_code[code] = 1

    rps[sec] += 1
    line = nf.readline()

    if total_rps != 0:
    write_seek(seek_file, str(new_seek))

    nf.close()

    metric = (len(sys.argv) >= 2) and re.match(r'nginx[(.*)]', sys.argv[1], re.M | re.I).group(1) or False
    data = get(stat_url, username, password).split(' ')
    data = parse_nginx_stat(data)

    data_to_send = []

    # Adding the metrics to response
    if not metric:
    for i in data:
    data_to_send.append(Metric(hostname, ('nginx[%s]' % i), data[i]))
    else:
    print data[metric]

    # Adding the request per seconds to response
    for t in range(0,60):
    data_to_send.append(Metric(hostname, 'nginx[rps]', rps[t], minute+t))

    # Adding the response codes stats to respons
    for t in res_code:
    data_to_send.append(Metric(hostname, ('nginx[%s]' % t), res_code[t]))


    send_to_zabbix(data_to_send, zabbix_host, zabbix_port)
    [root@vmhzpnginx scripts]# vim zbx_nginx_stats.py
    #!/usr/bin/python

    import urllib2, base64, re, struct, time, socket, sys, datetime, os.path

    try:
    import json
    except:
    import simplejson as json

    zabbix_host = '127.0.0.1' # Zabbix server IP
    zabbix_port = 10051 # Zabbix server port
    hostname = 'Zabbix Agent' # Name of monitored host, like it shows in zabbix web ui
    time_delta = 1 # grep interval in minutes

    # URL to nginx stat (http_stub_status_module)
    stat_url = 'https://nginx.server/nginx_stat'

    # Nginx log file path
    nginx_log_file_path = '/var/log/nginx/access.log'

    # Optional Basic Auth
    username = 'user'
    password = 'pass'

    # Temp file, with log file cursor position
    seek_file = '/tmp/nginx_log_stat'


    class Metric(object):
    hostname = 'Zabbix Agen' # Name of monitored host, like it shows in zabbix web hostname = 'Zabbix Age' # Name of monitored host, like it shows in zabbix web u return 'Metric(%r, %r, %r)' % (self.host, self.key, self.value)
    hostname = 'vmhzpnginx' # Name of monitored host, like it shows in zabbix web u"zbx_nginx_stats.py" 196L, 5611C written
    [root@vmhzpnginx scripts]# pwd
    /etc/zabbix/scripts
    [root@vmhzpnginx scripts]# cd /etc/nginx
    [root@vmhzpnginx nginx]# ls
    client_body_temp fastcgi_temp logs sbin uwsgi_temp
    conf html proxy_temp scgi_temp
    [root@vmhzpnginx nginx]# cd logs
    [root@vmhzpnginx logs]# ls
    access.log error.log nginx.pid
    [root@vmhzpnginx tmp]# cd /etc/nginx
    [root@vmhzpnginx nginx]# ls
    client_body_temp fastcgi_temp logs sbin uwsgi_temp
    conf html proxy_temp scgi_temp
    [root@vmhzpnginx nginx]# cd logs
    [root@vmhzpnginx logs]# pwd
    /etc/nginx/logs
    [root@vmhzpnginx logs]# cd /home
    [root@vmhzpnginx home]# ls
    master.zip pcre-8.38 zabbix-get-4.0.0-2.el7.x86_64.rpm
    nginx-1.15.8 pcre-8.38.tar.gz zbx_nginx_template-master
    nginx-1.15.8.tar.gz www
    [root@vmhzpnginx home]# cd /etc/zabbix
    [root@vmhzpnginx zabbix]# ls
    scripts zabbix_agentd.conf zabbix_agentd.conf.bak zabbix_agentd.d
    [root@vmhzpnginx zabbix]# cd scripts
    [root@vmhzpnginx scripts]# ls
    zbx_nginx_stats.py
    [root@vmhzpnginx scripts]# vim zbx_nginx_stats.py
    #!/usr/bin/python

    import urllib2, base64, re, struct, time, socket, sys, datetime, os.path

    try:
    import json
    except:
    import simplejson as json

    zabbix_host = '172.16.1.214' # Zabbix server IP
    zabbix_port = 10051 # Zabbix server port
    hostname = 'vmhzpnginx' # Name of monitored host, like it shows in zabbix web ui
    time_delta = 1 # grep interval in minutes

    # URL to nginx stat (http_stub_status_module)
    stat_url = 'http://127.0.0.1/nginx_stat'

    # Nginx log file path
    nginx_log_file_path = '/var/log/nginx/access.log'

    # Optional Basic Auth
    username = 'user'
    password = 'pass'

    # Temp file, with log file cursor position
    seek_file = '/tmp/nginx_log_stat'


    class Metric(object):
    "zbx_nginx_stats.py" 196L, 5629C written
    [root@vmhzpnginx scripts]# cat zbx_nginx_stats.py
    #!/usr/bin/python

    import urllib2, base64, re, struct, time, socket, sys, datetime, os.path

    try:
    import json
    except:
    import simplejson as json

    zabbix_host = '172.16.1.***' # Zabbix server IP
    zabbix_port = 10051 # Zabbix server port
    hostname = 'vmhzpnginx' # Name of monitored host, like it shows in zabbix web ui
    time_delta = 1 # grep interval in minutes

    # URL to nginx stat (http_stub_status_module)
    stat_url = 'http://127.0.0.1/nginx_stat'

    # Nginx log file path
    nginx_log_file_path = '/etc/nginx/logs/access.log'

    # Optional Basic Auth
    username = 'zabbix'
    password = '*****'

    # Temp file, with log file cursor position
    seek_file = '/etc/nginx/logs/nginx_log_stat'


    class Metric(object):
    def __init__(self, host, key, value, clock=None):
    self.host = host
    self.key = key
    self.value = value
    self.clock = clock

    def __repr__(self):
    if self.clock is None:
    return 'Metric(%r, %r, %r)' % (self.host, self.key, self.value)
    return 'Metric(%r, %r, %r, %r)' % (self.host, self.key, self.value, self.clock)

    def send_to_zabbix(metrics, zabbix_host='127.0.0.1', zabbix_port=10051):

    j = json.dumps
    metrics_data = []
    for m in metrics:
    clock = m.clock or ('%d' % time.time())
    metrics_data.append(('{"host":%s,"key":%s,"value":%s,"clock":%s}') % (j(m.host), j(m.key), j(m.value), j(clock)))
    json_data = ('{"request":"sender data","data":[%s]}') % (','.join(metrics_data))
    data_len = struct.pack('<Q', len(json_data))
    packet = 'ZBXDx01'+ data_len + json_data

    #print packet
    #print ':'.join(x.encode('hex') for x in packet)

    try:
    zabbix = socket.socket()
    zabbix.connect((zabbix_host, zabbix_port))
    zabbix.sendall(packet)
    resp_hdr = _recv_all(zabbix, 13)
    if not resp_hdr.startswith('ZBXDx01') or len(resp_hdr) != 13:
    print 'Wrong zabbix response'
    return False
    resp_body_len = struct.unpack('<Q', resp_hdr[5:])[0]
    resp_body = zabbix.recv(resp_body_len)
    zabbix.close()

    resp = json.loads(resp_body)
    #print resp
    if resp.get('response') != 'success':
    print 'Got error from Zabbix: %s' % resp
    return False
    return True
    except:
    print 'Error while sending data to Zabbix'
    return False


    def _recv_all(sock, count):
    buf = ''
    while len(buf)<count:
    chunk = sock.recv(count-len(buf))
    if not chunk:
    return buf
    buf += chunk
    return buf


    def get(url, login, passwd):
    req = urllib2.Request(url)
    if login and passwd:
    base64string = base64.encodestring('%s:%s' % (login, passwd)).replace(' ', '')
    req.add_header("Authorization", "Basic %s" % base64string)
    q = urllib2.urlopen(req)
    res = q.read()
    q.close()
    return res

    def parse_nginx_stat(data):
    a = {}
    # Active connections
    a['active_connections'] = re.match(r'(.*):s(d*)', data[0], re.M | re.I).group(2)
    # Accepts
    a['accepted_connections'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(1)
    # Handled
    a['handled_connections'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(2)
    # Requests
    a['handled_requests'] = re.match(r's(d*)s(d*)s(d*)', data[2], re.M | re.I).group(3)
    # Reading
    a['header_reading'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(2)
    # Writing
    a['body_reading'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(4)
    # Waiting
    a['keepalive_connections'] = re.match(r'(.*):s(d*)(.*):s(d*)(.*):s(d*)', data[3], re.M | re.I).group(6)
    return a


    def read_seek(file):
    if os.path.isfile(file):
    f = open(file, 'r')
    try:
    result = int(f.readline())
    f.close()
    return result
    except:
    return 0
    else:
    return 0

    def write_seek(file, value):
    f = open(file, 'w')
    f.write(value)
    f.close()


    #print '[12/Mar/2014:03:21:13 +0400]'

    d = datetime.datetime.now()-datetime.timedelta(minutes=time_delta)
    minute = int(time.mktime(d.timetuple()) / 60)*60
    d = d.strftime('%d/%b/%Y:%H:%M')

    total_rps = 0
    rps = [0]*60
    tps = [0]*60
    res_code = {}

    nf = open(nginx_log_file_path, 'r')

    new_seek = seek = read_seek(seek_file)

    # if new log file, don't do seek
    if os.path.getsize(nginx_log_file_path) > seek:
    nf.seek(seek)

    line = nf.readline()
    while line:
    if d in line:
    new_seek = nf.tell()
    total_rps += 1
    sec = int(re.match('(.*):(d+):(d+):(d+)s.*]', line).group(4))
    code = re.match(r'(.*)"s(d*)s', line).group(2)
    if code in res_code:
    res_code[code] += 1
    else:
    res_code[code] = 1

    rps[sec] += 1
    line = nf.readline()

    if total_rps != 0:
    write_seek(seek_file, str(new_seek))

    nf.close()

    metric = (len(sys.argv) >= 2) and re.match(r'nginx[(.*)]', sys.argv[1], re.M | re.I).group(1) or False
    data = get(stat_url, username, password).split(' ')
    data = parse_nginx_stat(data)

    data_to_send = []

    # Adding the metrics to response
    if not metric:
    for i in data:
    data_to_send.append(Metric(hostname, ('nginx[%s]' % i), data[i]))
    else:
    print data[metric]

    # Adding the request per seconds to response
    for t in range(0,60):
    data_to_send.append(Metric(hostname, 'nginx[rps]', rps[t], minute+t))

    # Adding the response codes stats to respons
    for t in res_code:
    data_to_send.append(Metric(hostname, ('nginx[%s]' % t), res_code[t]))


    send_to_zabbix(data_to_send, zabbix_host, zabbix_port)

    [root@vmhzpnginx scripts]# chmod u+x zbx_nginx_stats.py
    [root@vmhzpnginx scripts]# ll
    total 8
    -rwxr-xr-x 1 root root 5629 Mar 18 08:48 zbx_nginx_stats.py
    [root@vmhzpnginx scripts]# cd /etc/nginx
    [root@vmhzpnginx nginx]# ls
    client_body_temp fastcgi_temp logs sbin uwsgi_temp
    conf html proxy_temp scgi_temp
    [root@vmhzpnginx nginx]# cd conf
    [root@vmhzpnginx conf]# ls
    fastcgi.conf mime.types scgi_params.default
    fastcgi.conf.default mime.types.default uwsgi_params
    fastcgi_params nginx.conf uwsgi_params.default
    fastcgi_params.default nginx.conf.bak win-utf
    koi-utf nginx.conf.default
    koi-win scgi_params
    [root@vmhzpnginx conf]# vim nginx.conf
    #user nobody;
    worker_processes 1;

    #error_log logs/error.log;
    #error_log logs/error.log notice;
    #error_log logs/error.log info;

    #pid logs/nginx.pid;


    events {
    worker_connections 1024;
    }


    http {
    include mime.types;
    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    sendfile on;
    #keepalive_timeout 0;
    events {
    worker_connections 1024;
    events {
    worker_connections 1024;
    events {
    worker_connections 1024;
    events {
    worker_connections 1024;

    #charset koi8-r;

    #access_log logs/host.access.log main;

    location / {
    root html;
    index index.html index.htm;
    }

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    # proxy_pass http://127.0.0.1;
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    # proxy_pass http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ .php$ {
    # root html;
    # fastcgi_pass 127.0.0.1:9000;
    # fastcgi_index index.php;
    # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    # include fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /.ht {
    # deny all;
    #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    # listen 8000;
    # listen somename:8080;
    # server_name somename alias another.alias;

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}
    #}


    # HTTPS server
    #
    #server {
    # listen 443 ssl;
    # server_name localhost;

    # ssl_certificate cert.pem;
    # ssl_certificate_key cert.key;

    # ssl_session_cache shared:SSL:1m;
    "nginx.conf" 127L, 3034C written
    [root@vmhzpnginx conf]# cat nginx.conf

    #user nobody;
    worker_processes 1;

    #error_log logs/error.log;
    #error_log logs/error.log notice;
    #error_log logs/error.log info;

    #pid logs/nginx.pid;


    events {
    worker_connections 1024;
    }


    http {
    include mime.types;
    default_type application/octet-stream;

    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log logs/access.log main;

    sendfile on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    #gzip on;

    server {
    listen 80;
    server_name localhost;

    #charset koi8-r;

    #access_log logs/host.access.log main;

    location / {
    root html;
    index index.html index.htm;
    }

    location /nginx_stat {
    stub_status on; # Turn on nginx stats
    access_log off; # We do not need logs for stats
    allow 127.0.0.1; # Security: Only allow access from IP
    allow 172.16.1.214;
    allow 172.16.1.222;
    #allow ::1; # Security IPv6: allow only from localhost
    #deny all; # Deny requests from the other of the world
    }

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    # proxy_pass http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ .php$ {
    # root html;
    # fastcgi_pass 127.0.0.1:9000;
    # fastcgi_index index.php;
    # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    # include fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /.ht {
    # deny all;
    #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    # listen 8000;
    # listen somename:8080;
    # server_name somename alias another.alias;

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}


    # HTTPS server
    #
    #server {
    # listen 443 ssl;
    # server_name localhost;

    # ssl_certificate cert.pem;
    # ssl_certificate_key cert.key;

    # ssl_session_cache shared:SSL:1m;
    # ssl_session_timeout 5m;

    # ssl_ciphers HIGH:!aNULL:!MD5;
    # ssl_prefer_server_ciphers on;

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}

    }
    [root@vmhzpnginx conf]#
    [root@vmhzpnginx conf]# systemctl restart nginx
    [root@vmhzpnginx conf]# systemctl status nginx
    ● nginx.service - nginx service
    Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
    Active: active (running) since Mon 2019-03-18 08:53:57 CST; 7s ago
    Process: 14677 ExecStop=/etc/nginx/sbin/nginx -s quit (code=exited, status=0/SUCCESS)
    Process: 14681 ExecStart=/etc/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
    Main PID: 14682 (nginx)
    CGroup: /system.slice/nginx.service
    ├─14682 nginx: master process /etc/nginx/sbin/nginx
    └─14683 nginx: worker process

    Mar 18 08:53:57 vmhzpnginx systemd[1]: Stopped nginx service.
    Mar 18 08:53:57 vmhzpnginx systemd[1]: Starting nginx service...
    Mar 18 08:53:57 vmhzpnginx systemd[1]: Started nginx service.
    [root@vmhzpnginx sbin]# ./nginx -t
    nginx: the configuration file /etc/nginx/conf/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/conf/nginx.conf test is successful
    [root@vmhzpnginx sbin]# crontab -l
    no crontab for root
    [root@vmhzpnginx sbin]# crontab -e
    [root@vmhzpnginx sbin]# crontab -l
    /1 * * * * /etc/zabbix/scripts/zbx_nginx_stats.pyi*/1 * * * * /etc/zabbix/script

    --------------------------------------

    后续需要在zabbix web页面上导入zbx_export_templates.xml模板,并且设置主机的模板关联即可实现图形界面监控Nginx状况;

  • 相关阅读:
    Maven的生命周期
    Spring Framework: @RestController vs @Controller
    HTMl5的sessionStorage和localStorage
    Gradle下载类库源码
    Spring Boot, Java Config
    NodeJS简记
    8 commands to check cpu information on Linux
    守护进程之守护进程的惯例
    守护进程之单实例守护进程
    守护进程之出错记录
  • 原文地址:https://www.cnblogs.com/tiantom/p/10550372.html
Copyright © 2011-2022 走看看