PHP程序如何发送syslog到远程服务器

给同事做了个 PHP 接口,转发发送短信的请求,同时要把发送记录发送到远程的 cacti 的 syslog 去

很简单,但是也不简单

首先是 PHP 服务器,是最简化编译的,php -m 查了一下

 1php -m
 2[PHP Modules]
 3Core
 4ctype
 5curl
 6date
 7dom
 8fileinfo
 9filter
10gettext
11hash
12iconv
13json
14libxml
15openssl
16pcre
17PDO
18pdo_sqlite
19Phar
20posix
21Reflection
22session
23SimpleXML
24SPL
25sqlite3
26standard
27tokenizer
28xml
29xmlreader
30xmlwriter
31
32[Zend Modules]

居然没有 socket 模块,没办法,找到源代码,编译一个安装,原有的 php 安装路径是 /export/servers/php

1$ tar zxvf php-7.4.0.tar.gz 
2$ cd php-7.4.0/sockets
3$ /export/servers/php/bin/phpize
4$ ./configure --enable-sockets --with-php-config=/export/servers/php/bin/php-config
5$ make
6$ make install

又看了一眼,是 php-fpm,居然没有 php.ini ,得,再生成一个,放在 /export/servers/php/lib/php.ini

1extension_dir = "/export/servers/php740/lib/php/extensions/no-debug-non-zts-20190902/"
2extension = sockets.so

然后重启 php-fpm ,重新 php -m 检查,发现有 socket 模块就 ok 了。

接下来就是 php 源代码了

 1<?php
 2date_default_timezone_set('Asia/Shanghai');
 3
 4function send_remote_syslog($message) {
 5    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
 6    foreach(explode("\n", $message) as $line) {
 7      $syslog_message = "<22>" . date('M d H:i:s ') . 'Qi_an_xin sms_log: ' . $line;
 8      socket_sendto($sock, $syslog_message, strlen($syslog_message), 0, '172.18.31.6', 514);
 9    }
10    socket_close($sock);
11}
12
13    send_remote_syslog("ABC 验证码: 39792192");
14?>    

这样就可以了,上面代码比较难理解的是<22>,那是报错级别的计算方法,Facility + Severity:

 1 *   Facility values:
 2 *      0 kernel messages
 3 *      1 user-level messages
 4 *      2 mail system
 5 *      3 system daemons
 6 *      4 security/authorization messages
 7 *      5 messages generated internally by syslogd
 8 *      6 line printer subsystem
 9 *      7 network news subsystem
10 *      8 UUCP subsystem
11 *      9 clock daemon
12 *     10 security/authorization messages
13 *     11 FTP daemon
14 *     12 NTP subsystem
15 *     13 log audit
16 *     14 log alert
17 *     15 clock daemon
18 *     16 local user 0 (local0) (default value)
19 *     17 local user 1 (local1)
20 *     18 local user 2 (local2)
21 *     19 local user 3 (local3)
22 *     20 local user 4 (local4)
23 *     21 local user 5 (local5)
24 *     22 local user 6 (local6)
25 *     23 local user 7 (local7)
26 *
27 *   Severity values:
28 *     0 Emergency: system is unusable
29 *     1 Alert: action must be taken immediately
30 *     2 Critical: critical conditions
31 *     3 Error: error conditions
32 *     4 Warning: warning conditions
33 *     5 Notice: normal but significant condition (default value)
34 *     6 Informational: informational messages
35 *     7 Debug: debug-level messages

计算方法就是 (facility*8 + severity),这里的22+0,可以理解成 local6 ,就是级别6

image-20211028114512589

如果发了一个 “local use 4” 和 Serverity = 5 的消息,那么就是 20×8+5=165 ,包头就是 <165>


没有装Docker如何从镜像中释放出文件
Dockerfile的编写与调试技巧
comments powered by Disqus