起因最近使用lastb命令发现服务器被暴力登录ssh,就好奇有哪些有哪些用户名以及IP在那个时段进行了尝试。首先,查看lastb的输出sudo lastb node ssh:notty 92.118.39.133 Thu Aug 1 00:19 - 00:19 (00:00) node ssh:notty 92.118.39.133 Thu Aug 1 00:19 - 00:19 (00:00) validato ssh:notty 92.118.39.133 Thu Aug 1 00:12 - 00:12 (00:00) validato ssh:notty 92.118.39.133 Thu Aug 1 00:12 - 00:12 (00:00) validato ssh:notty 92.118.39.133 Thu Aug 1 00:06 - 00:06 (00:00) validato ssh:notty 92.118.39.133 Thu Aug 1 00:06 - 00:06 (00:00) amir ssh:notty 103.140.239.254 Thu Aug 1 00:05 - 00:05 (00:00) amir ssh:notty 103.140.239.254 Thu Aug 1 00:04 - 00:04 (00:00) root ssh:notty 103.140.239.254 Thu Aug 1 00:04 - 00:04 (00:00) root ssh:notty 103.140.239.254 Thu Aug 1 00:03 - 00:03 (00:00) root ssh:notty 103.140.239.254 Thu Aug 1 00:02 - 00:02 (00:00) root ssh:notty 103.140.239.254 Thu Aug 1 00:01 - 00:01 (00:00) guest ssh:notty 146.59.127.25 Thu Aug 1 00:01 - 00:01 (00:00) guest ssh:notty 146.59.127.25 Thu Aug 1 00:01 - 00:01 (00:00) root ssh:notty 65.190.102.226 Thu Aug 1 00:01 - 00:01 (00:00) root ssh:notty 103.140.239.254 Thu Aug 1 00:00 - 00:00 (00:00) ubuntu ssh:notty 146.59.127.25 Thu Aug 1 00:00 - 00:00 (00:00) ubuntu ssh:notty 146.59.127.25 Thu Aug 1 00:00 - 00:00 (00:00) ubuntu ssh:notty 65.190.102.226 Thu Aug 1 00:00 - 00:00 (00:00) ubuntu ssh:notty 65.190.102.226 Thu Aug 1 00:00 - 00:00 (00:00) operator ssh:notty 92.118.39.133 Thu Aug 1 00:00 - 00:00 (00:00) operator ssh:notty 92.118.39.133 Thu Aug 1 00:00 - 00:00 (00:00) btmp begins Thu Aug 1 00:00:10 2024 可以看见这里有用户名,IP,时间等信息。他们分别在第一,第三,第五,第六,第七列。这时候我们就需要一个工具来获取相应的字段。 这时候awk就进入了我的视线。awk作用awk 是一种强大的文本处理工具,常用于处理结构化数据,如表格数据、列数据等。awk用法基本命令格式:awk 'pattern { action }' filenameawk 'pattern { action }' filenamepattern 是一个条件表达式,如果满足条件,则执行 {} 中的 action。action 是要执行的命令,可以是打印、赋值等操作。变量:$1, $2, ... 表示字段(列),$0 表示整行。NF 是字段的数量。NR 是记录的行号。内置函数:print 用于打印文本。split 用于分割字符串。length 返回字符串的长度。控制流:if 语句用于条件判断。while 循环用于重复执行代码块。模式:BEGIN 在处理文件之前执行。END 在处理文件之后执行。awk使用这时候我们就能用awk命令去选取需要的列,顺便拼接成需要的格式。这里第一列和第三列分别是用户名,IP,所以需要用逗号分隔。第五,第六,第七列分别是月份,日期还有时间,需要拼接出一个时间日期。同时这里不显示ni年份,所以默认要加上2024作为年份,最终输出 MM-dd-yyyy HH:mm的格式。sudo lastb | awk '{print $1 "," $3 "," $5 "-" $6 "-2024" " " $7}' amir,103.140.239.254,Aug-1-2024 00:05 amir,103.140.239.254,Aug-1-2024 00:04 root,103.140.239.254,Aug-1-2024 00:04 root,103.140.239.254,Aug-1-2024 00:03 root,103.140.239.254,Aug-1-2024 00:02 root,103.140.239.254,Aug-1-2024 00:01 guest,146.59.127.25,Aug-1-2024 00:01 guest,146.59.127.25,Aug-1-2024 00:01 root,65.190.102.226,Aug-1-2024 00:01 root,103.140.239.254,Aug-1-2024 00:00 ubuntu,146.59.127.25,Aug-1-2024 00:00 ubuntu,146.59.127.25,Aug-1-2024 00:00 ubuntu,65.190.102.226,Aug-1-2024 00:00 ubuntu,65.190.102.226,Aug-1-224 00:00 operator,92.118.39.133,Aug-1-2024 00:00 operator,92.118.39.133,Aug-1-2024 00:00 最后,把结果保存到文件sudo lastb | awk '{print $1 "," $3 "," $5 "-" $6 "-2024" " " $7}' > lastb.txt这样就完成了整个流程。这里需要注意的是里面结果还不是很干净,后续还需要进行数据的清洗。