find-xargs-cut-tr-sort-uniq-tee

本文详细介绍了find命令的各种用法,包括查找文件类型、大小、修改时间、用户、组、正则表达式匹配,并展示了xargs、cut、sort、uniq、diff、tr等工具的实战应用,以及如何使用 tee、echo和用户管理。适合深入理解Linux命令行和文件操作。
find
find 参数
-type f  文件   d目录   l 符号链接
-iname  表示不区分大小写
-regex 正则表达式
-iname 不区分大小写
-cmin +10  十分钟外
-mtime -1 一天内
-user wang 用户王
-size +大于 -小于
-delete
-a 与
-o 或
! 取反
查看.conf文件数量  find /etc/ -name "*.conf"  | wc -l 
查看属组是tom2的文件 [root@localhost home]# find ./  -group tom2 -type f
查看大于1M文件  find /etc/ -size +1M
查看1天内修改的文件 find /root/ -mtime -1
查看权限是700的文件 [root@localhost home]# find ./  -perm /700 -type f
招出20分钟以内修改的文件筛选出文件进行删除find /root/ -cmin -20 | head -n 3 | head -n 2 | tail -n 1 | xargs rm -rf {} \; 
查看20分钟内小于100k文件 find /root/ -cmin -20 -a -size -100k
创建1-10的jpg和mp4文件touch {1..10}.{jpg,mp4}
删除1-10的jpg文件 find ./ -name "*.jpg"  -exec rm -rf {} \;  {}代表前边查找出的结果
复制用法 find ./ -name "*5.mp4"  -exec cp {} /tmp \;
删除10分钟内的文件 find ./ -cmin -10 -type f -exec rm -rf {} \;
除了tom1和tom2的文件find /home/ ! -user tom1  -user tom2
/home/tom2
xargs
xargs 配合mv -t 是用     ls | xargs -i mv -t  /tmp
[root@rocky tmp]# seq 5  
1
2
3
4
5
[root@rocky tmp]# seq 5|xargs  #默认取消换行符
1 2 3 4 5

[root@rocky tmp]# echo 1 2 3 4 5 6 | xargs -n1  按行显示
1
2
3
4
5
6
[root@rocky tmp]# echo 1 2 3 4 5 6 | xargs -n2
1 2
3 4
5 6
[root@rocky tmp]# echo 1 2 3 4 5 6 | xargs -n3
1 2 3
4 5 6

echo user{1..5} | xargs -n1 useradd  创建5个用户

[root@localhost home]# seq 5 | xargs -i echo a{}     花括号配合-i使用
a1
a2
a3
a4
a5
并行下载bilibili
yum install -y python3-pip
pip3 install you-get
seq 2 | xargs -i -P3 you-get https://www.bilibili.com/video/BV1hZ4y1i724?p={}&vd_source=1e8e7227cb73596440fb25edeb6a3f68 并行3个任务
cut
cat /etc/passwd |cut -d":" -f1-3,6  #切割
cat /etc/passwd  | cut -c 2-5  截取第2到第5字符显示
sort
-t 指定分隔符 
-k 指定列
-n 数字排序
-nr 数字倒序
-R  随机排序
[root@rocky ~]# cut -d: -f1,3 /etc/passwd |sort  -t: -nk2 
root:0
bin:1
daemon:2
adm:3
lp:4
sync:5
shutdown:6
------------------------------------------------------------
[root@rocky ~]# df |tail -n +2 | tr -s " " | cut -d" " -f5,6 | sort -t" " -nrk1
83% /boot
13% /
2% /run
0% /sys/fs/cgroup
0% /run/user/0
0% /dev/shm
0% /dev
uniq
-u 显示不重复的行
-c 统计相同次数
-d 每个相同的只显示一个
取相同值  cat 123 321 | sort | uniq -c
取不同值  cat 123 321 | sort | uniq -u
diff
[root@rocky ~]# cat > 123 <<EOF
> q
> a
> z
> EOF
[root@rocky ~]# cat > 321 <<11
> q
> a
> a
> z
> 11
[root@rocky ~]# diff -u 123 321
--- 123	2022-07-17 18:07:26.253703983 +0800
+++ 321	2022-07-17 18:07:43.438688469 +0800
@@ -1,3 +1,4 @@
 q
 a
+a
 z
vimdiff  123  321
patch 恢复文件
tr
[root@rocky tmp]# tr 'a-z' 'A-Z' < 123  #替换用法
ABC
[root@rocky tmp]# cat 123
abc
[root@rocky tmp]# echo healbloc | tr -d 'abc' #删除用法
hello
[root@rocky tmp]# echo healbloc | tr -dc 'abc' #除了abc都删除用法
[root@rocky tmp]# echo aabbaacc | tr -s 'abc'  #压缩用法
abac
cat > 123 <<EOF

echo {a..d} | tr ' ' '\n'  #把空格替换成换行

tee
tee命令用于将数据重定向到文件,另一方面还可以提供一份重定向数据的副本作为后续命令的stdin。简单的说就是把数据重定向到给定文件和屏幕上
-a:向文件中重定向时使用追加模式;
-i:忽略中断(interrupt)信号。

echo haha | tee -a 123
cat 123
ahsdhjkasd
haha

[root@HTNICE home]# cat /proc/version Linux version 5.10.140 (ylc@ylc-Precision-3571) (aarch64-linux-gcc.br_real (Buildroot 2022.02.6) 10.4.0, GNU ld (GNU Binutils) 2.36.1) #7 SMP Mon Feb 20 12:59:02 CST 2023 [root@HTNICE home]# busybox BusyBox v1.35.0 (2023-02-21 13:21:21 CST) multi-call binary. BusyBox is copyrighted by many authors between 1998-2015. Licensed under GPLv2. See source distribution for detailed copyright notices. Usage: busybox [function [arguments]...] or: busybox --list[-full] or: busybox --show SCRIPT or: busybox --install [-s] [DIR] or: function [arguments]... BusyBox is a multi-call binary that combines many common Unix utilities into a single executable. Most people will create a link to busybox for each function they wish to use and BusyBox will act like whatever it was invoked as. Currently defined functions: [, [[, addgroup, adduser, ar, arch, arp, arping, ascii, ash, awk, base32, base64, basename, bc, blkid, bunzip2, bzcat, cat, chattr, chgrp, chmod, chown, chroot, chrt, chvt, cksum, clear, cmp, cp, cpio, crc32, crond, crontab, cut, date, dc, dd, deallocvt, delgroup, deluser, depmod, devmem, df, diff, dirname, dmesg, dnsd, dnsdomainname, dos2unix, du, dumpkmap, echo, egrep, eject, env, ether-wake, expr, factor, fallocate, false, fbset, fdflush, fdformat, fdisk, fgrep, find, flock, fold, free, freeramdisk, fsck, fsfreeze, fstrim, fuser, getopt, getty, grep, gunzip, gzip, halt, hdparm, head, hexdump, hexedit, hostid, hostname, hwclock, i2cdetect, i2cdump, i2cget, i2cset, i2ctransfer, id, ifconfig, ifdown, ifup, inetd, init, insmod, install, ip, ipaddr, ipcrm, ipcs, iplink, ipneigh, iproute, iprule, iptunnel, kill, killall, killall5, klogd, last, less, link, linux32, linux64, linuxrc, ln, loadfont, loadkmap, logger, login, logname, losetup, ls, lsattr, lsmod, lsof, lspci, lsscsi, lsusb, lzcat, lzma, lzopcat, makedevs, md5sum, mdev, mesg, microcom, mim, mkdir, mkdosfs, mke2fs, mkfifo, mknod, mkpasswd, mkswap, mktemp, modinfo, modprobe, more, mount, mountpoint, mt, mv, nameif, netstat, nice, nl, nohup, nologin, nproc, nslookup, nuke, od, openvt, partprobe, passwd, paste, patch, pidof, ping, ping6, pipe_progress, pivot_root, poweroff, printenv, printf, ps, pwd, rdate, readlink, readprofile, realpath, reboot, renice, reset, resize, resume, rm, rmdir, rmmod, route, run-init, run-parts, runlevel, sed, seq, setarch, setconsole, setfattr, setkeycodes, setlogcons, setpriv, setserial, setsid, sh, sha1sum, sha256sum, sha3sum, sha512sum, shred, sleep, sort, start-stop-daemon, strings, stty, su, sulogin, svc, svok, swapoff, swapon, switch_root, sync, sysctl, syslogd, tail, tar, tc, tee, telnet, telnetd, test, tftp, time, top, touch, tr, traceroute, true, truncate, ts, tty, ubirename, udhcpc, udhcpd, uevent, umount, uname, uniq, unix2dos, unlink, unlzma, unlzop, unxz, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi, vlock, w, watch, watchdog, wc, wget, which, who, whoami, xargs, xxd, xz, xzcat, yes, zcat [root@HTNICE home]# 我尝试使用这个系统进行网安agent探针开发,目前先尝试使用C语言标准库和POSIX标准实现登录成功、退出登录、登陆失败、操作命令、串口数量信息、串口占用、串口释放等事件的日志记录
09-09
<think> 我们面临的需求是在基于Buildroot 2022.02.6构建的嵌入式Linux系统中(内核版本5.10.140,BusyBox v1.35.0)利用C语言标准库和POSIX接口实现多种事件的日志记录。这些事件包括: 1. 用户登录成功 2. 用户退出登录 3. 用户登录失败 4. 用户操作命令记录 5. 串口数量信息 6. 串口占用事件 7. 串口释放事件 由于系统使用BusyBox,我们将充分利用其现有工具和自定义程序相结合的方式。 ### 一、整体设计思路 1. **日志记录方式**: - 使用`syslog` API记录所有事件,并通过`syslogd`统一管理日志 - 日志文件存储在`/var/log/messages`(默认)或单独配置(如`/var/log/auth.log`) 2. **事件捕获策略**: - **登录/退出事件**:替换BusyBox的`login`程序为自定义包装器 - **命令记录**:使用`bash`或`ash`的`HISTFILE`功能结合`trap`命令 - **串口监控**:编写守护进程监控`/dev/ttyS*`设备状态变化 ### 二、具体实现方法 #### 1. 用户登录/退出事件 **步骤**: 1. 创建自定义`login`包装器(用C语言编写): ```c // mylogin.c #include <unistd.h> #include <syslog.h> #include <string.h> int main(int argc, char *argv[]) { // 原始login路径(Buildroot中通常是/bin/busybox) char *login_path = "/bin/busybox"; char *login_args[argc+1]; memcpy(login_args, argv, argc * sizeof(char*)); login_args[0] = "login"; // busybox要求第一个参数为applet名称 login_args[argc] = NULL; // 登录尝试日志 openlog("AUTH", LOG_PID, LOG_AUTH); syslog(LOG_INFO, "Login attempt: user=%s", getenv("USER")); closelog(); // 执行原始login execvp(login_path, login_args); // 如果exec失败则记录错误 perror("execvp"); return 1; } ``` 2. **登录成功/失败判断**: - 修改BusyBox的`login`源码(可选):在`loginutils/login.c`中添加日志点 - **替代方案**(推荐):在`/etc/profile`中使用`trap`捕获登录会话结束事件 ```bash # /etc/profile 追加 logger -p auth.info "User $USER logged in successfully" trap 'logger -p auth.info "User $USER logged out"; exit' EXIT ``` 3. **Buildroot集成**: - 将`mylogin`程序添加到Buildroot的`overlay`文件系统中 - 修改`/etc/inittab`,替换原始login: ```diff - ::respawn:/bin/login + ::respawn:/usr/sbin/mylogin ``` #### 2. 用户操作命令记录 使用`bash`的`history`功能并实时写入syslog: 1. **启用`bash`历史记录**(若使用`ash`需额外配置): ```bash # /etc/profile 追加 export HISTFILE=/etc/.history export HISTTIMEFORMAT="%F %T " shopt -s histappend export PROMPT_COMMAND='history -a' ``` 2. **添加日志钩子**: ```bash # 将每条命令实时写入syslog log_command() { local cmd=$(history 1 | sed 's/^ *[0-9]* *//') logger -p user.info "CMD[$USER@$(hostname)]: $cmd" } export PROMPT_COMMAND="log_command;$PROMPT_COMMAND" ``` #### 3. 串口监控 编写C语言守护进程监控串口设备: ```c // serial_monitor.c #include <sys/inotify.h> #include <limits.h> #include <syslog.h> #include <unistd.h> #define SERIAL_PATH "/dev" int main() { int fd = inotify_init(); inotify_add_watch(fd, SERIAL_PATH, IN_CREATE | IN_DELETE); openlog("SERIAL", LOG_PID, LOG_DAEMON); syslog(LOG_INFO, "Serial monitor started"); while (1) { char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event)))); ssize_t len = read(fd, buf, sizeof(buf)); struct inotify_event *event; for (char *ptr = buf; ptr < buf + len; ptr += sizeof(*event) + event->len) { event = (struct inotify_event*)ptr; if (event->mask & IN_CREATE) syslog(LOG_INFO, "Serial port %s/%s created", SERIAL_PATH, event->name); if (event->mask & IN_DELETE) syslog(LOG_INFO, "Serial port %s/%s removed", SERIAL_PATH, event->name); } } return 0; } ``` **扩展功能**(串口占用/释放): - 使用`lsof`检测设备占用情况(需安装) - 或通过内核调试接口`/proc/tty/drivers`解析 ### 三、系统配置 1. **syslog配置**: ```conf # /etc/syslog.conf auth.* /var/log/auth.log user.* /var/log/user.log daemon.* /var/log/serial.log ``` 2. **Buildroot定制**: - 启用`BR2_PACKAGE_BUSYBOX_SHOW_OTHERS=y` - BusyBox配置: ``` CONFIG_SYSLOGD=y CONFIG_FEATURE_ROTATE_LOGFILE=y CONFIG_FEATURE_SYSLOGD_READ_BUFFER_SIZE=256 ``` ### 四、测试验证 ```bash # 手动触发登录测试 telnet localhost # 实时查看日志 logread -f # 预期输出示例 # AUTH: Login attempt: user=root # AUTH: User root logged in successfully # CMD: root@buildroot: ls /dev # SERIAL: Serial port /dev/ttyS2 created ``` ### 注意事项 1. **资源占用优化**: - 日志文件使用`tmpfs`存储:在`/etc/fstab`添加 ```bash tmpfs /var/log tmpfs defaults,size=1M 0 0 ``` - 启用`logrotate`防止日志溢出 2. **权限管理**: - `serial_monitor`需以root身份运行 - 确保`/etc/.history`文件权限为600 --- §§相关问题§§ 1. 如何防止日志记录被恶意篡改? 2. 嵌入式系统中如何实现日志的远程备份? 3. 如何降低串口监控守护进程的资源消耗? 4. Buildroot中如何永久保存历史命令记录? [^1]: BusyBox登录机制源码分析(loginutils/login.c) [^2]: Linux inotify API手册(man 7 inotify) </think> ### 在Buildroot系统中实现事件日志记录方案 #### 一、整体架构设计 使用分层架构实现事件监控: ``` +------------------------+ | 事件源层 | (登录/串口操作等) +------------------------+ | v +------------------------+ | 监控层 | (自定义守护进程 + 系统钩子) +------------------------+ | v +------------------------+ | 日志记录层 | (syslog + 自定义日志文件) +------------------------+ ``` #### 二、登录事件监控实现(C语言实现) ##### 1. 登录状态监控程序 ```c // login_monitor.c #include <stdio.h> #include <stdlib.h> #include <syslog.h> #include <unistd.h> #include <utmp.h> #include <signal.h> #include <string.h> #define LOG_TAG "AUTH" // 监控登录状态变化 void monitor_logins() { setutent(); // 打开utmp文件 struct utmp *entry; static struct utmp last_record; while(1) { while((entry = getutent()) != NULL) { if(entry->ut_type == USER_PROCESS) { // 检测新登录 if(strcmp(entry->ut_user, last_record.ut_user) != 0) { syslog(LOG_INFO, "[%s] Login success: User %s from %s", LOG_TAG, entry->ut_user, entry->ut_host); memcpy(&last_record, entry, sizeof(struct utmp)); } } // 检测退出事件 (需结合其他方法) } sleep(5); // 每5秒检查一次 setutent(); // 重置文件指针 } endutent(); } // 登录失败处理函数 void handle_failed_login(const char *username) { syslog(LOG_WARNING, "[%s] Login failed: User %s", LOG_TAG, username); } int main() { openlog("login_monitor", LOG_PID, LOG_AUTH); monitor_logins(); closelog(); return 0; } ``` ##### 2. 编译和安装 ```Makefile # Makefile CC = $(CROSS_COMPILE)gcc CFLAGS = -Wall -Os all: login_monitor login_monitor: login_monitor.o $(CC) $(CFLAGS) -o $@ $^ install: install -m 0755 login_monitor $(TARGET_DIR)/usr/sbin/ echo "::respawn:/usr/sbin/login_monitor" >> $(TARGET_DIR)/etc/inittab ``` #### 三、串口事件监控实现 ##### 1. 串口监控守护进程 ```c // serial_monitor.c #include <stdio.h> #include <stdlib.h> #include <syslog.h> #include <sys/inotify.h> #include <limits.h> #include <unistd.h> #include <dirent.h> #define DEV_PATH "/dev" #define SERIAL_PREFIX "ttyS" #define LOG_TAG "SERIAL" // 检测当前串口数量 int count_serial_ports() { DIR *dir; struct dirent *entry; int count = 0; if ((dir = opendir(DEV_PATH)) == NULL) return -1; while ((entry = readdir(dir)) != NULL) { if (strstr(entry->d_name, SERIAL_PREFIX) != NULL) { count++; } } closedir(dir); return count; } // 监控串口设备变化 void monitor_serial_devices() { int fd = inotify_init(); if (fd < 0) { syslog(LOG_ERR, "[%s] inotify_init failed", LOG_TAG); return; } int wd = inotify_add_watch(fd, DEV_PATH, IN_CREATE | IN_DELETE); if (wd < 0) { syslog(LOG_ERR, "[%s] Failed to watch %s", LOG_TAG, DEV_PATH); close(fd); return; } char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event)))); while (1) { ssize_t len = read(fd, buf, sizeof(buf)); if (len <= 0) continue; const struct inotify_event *event; for (char *ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) { event = (const struct inotify_event *)ptr; if (strstr(event->name, SERIAL_PREFIX)) { if (event->mask & IN_CREATE) { syslog(LOG_INFO, "[%s] Serial port created: %s/%s", LOG_TAG, DEV_PATH, event->name); } else if (event->mask & IN_DELETE) { syslog(LOG_INFO, "[%s] Serial port released: %s", LOG_TAG, event->name); } } } // 周期性报告串口数量 static int counter = 0; if (++counter % 12 == 0) { // 每分钟报告一次 int count = count_serial_ports(); if (count >= 0) { syslog(LOG_INFO, "[%s] Active serial ports: %d", LOG_TAG, count); } } } close(fd); } int main() { openlog("serial_monitor", LOG_PID, LOG_DAEMON); syslog(LOG_INFO, "[%s] Starting serial monitor", LOG_TAG); // 初始串口数量报告 int count = count_serial_ports(); if (count >= 0) { syslog(LOG_INFO, "[%s] Initial serial ports: %d", LOG_TAG, count); } monitor_serial_devices(); closelog(); return 0; } ``` #### 四、系统集成步骤 1. **Buildroot配置**: ```bash # 启用syslog功能 make menuconfig -> Busybox -> Linux System Utilities [*] syslogd [*] Rotate message files [*] Remote Log support [*] Support for /etc/syslog.conf ``` 2. **创建系统服务**: ```bash # /etc/init.d/S99monitors #!/bin/sh start() { /usr/sbin/login_monitor & /usr/sbin/serial_monitor & } stop() { killall login_monitor killall serial_monitor } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "Usage: $0 {start|stop|restart}" esac ``` 3. **syslog配置**: ```conf # /etc/syslog.conf auth.* /var/log/auth.log daemon.* /var/log/serial.log *.* /var/log/messages ``` #### 五、串口占用检测补充方案 对于串口占用状态检测,需增加以下逻辑: ```c // 在serial_monitor.c中添加 #include <sys/stat.h> #include <fcntl.h> int is_serial_used(const char *dev) { char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", DEV_PATH, dev); int fd = open(path, O_RDWR | O_NONBLOCK); if (fd < 0) { // EACCES表示设备被占用 if (errno == EACCES) return 1; return 0; } close(fd); return 0; } ``` #### 六、测试验证 ```bash # 查看登录日志 cat /var/log/auth.log # 监控实时日志 logread -f # 测试串口事件 echo test > /dev/ttyS0 rmmod serial_driver # 触发串口释放 ``` #### 七、资源优化建议 1. 使用`tmpfs`存储日志: ```bash # /etc/fstab tmpfs /var/log tmpfs defaults,size=2M 0 0 ``` 2. 日志轮转配置: ```conf # /etc/logrotate.conf /var/log/*.log { rotate 3 size 100k missingok compress } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值