&-" 0 file='/data/nginx/llogs/access.log'"/> &-" 0 file='/data/nginx/llogs/access.log'">
Home > Article > Operation and Maintenance > Shell implements network client method
Need to send the online access log to another program for reception
I started thinking about using python to implement it. Although python also has a way to implement tail -F, it is too troublesome and the efficiency is also compromised
I discovered it by accident. The shell can implement the network client, and it can be implemented with only a few lines of code.
First the code:
trap "exec 8<&-;exec 8>&-" 0 file='/data/nginx/llogs/access.log' exec 8<>/dev/tcp/10.3.0.200/9001 tail -F "$file" | grep --line-buffered "sid">&8
It is super simple. The actual processing logic code is only 2 lines. The following is the code description:
The first line is mainly to capture the program exit status and close the connection after exiting
The second line defines the log file
The third line establishes a network connection. Linux has a special file /dev/(udp|tcp)/ ip/port
Bind this file to a file descriptor to establish the corresponding network connection. The file descriptor is greater than 3.
The fourth line sends data to the established channel
Because grep will have a buffer, it will output data only after the buffer is full by default. Therefore, the --line-buffered parameter must be added and line buffering is used
Otherwise, the data received by the server will have line breaks.
This kind of agent's super simple function has good performance but there is a drawback
After the agent establishes a channel with the server, if the server hangs, the agent will also hang when the channel is disconnected, and the program will exit (tcp Client has this problem, upd does not)
Or the network is not good, it may also cause the agent to exit (I did not have this problem this time, it was all fiber optic interconnection network)
Therefore, a corresponding monitoring program is needed to detect the agent, and automatically when there is an abnormality Restart, or if the network quality is good, consider using udp
The above is the detailed content of Shell implements network client method. For more information, please follow other related articles on the PHP Chinese website!