以下是一个基本的Unix脚本示例,用于列出正在运行的应用程序和cron作业以及其端口号和其他一些常规信息:
#!/bin/bash
# Get the current date and time
now=$(date +"%Y-%m-%d %H:%M:%S")
# Print the header
echo "Timestamp|Process ID|Port|Command"
# List the running processes and filter for those listening on a TCP port
lsof -i TCP | awk '{if($1!="COMMAND") print $0}' | while read line
do
# Extract the process ID and port number
pid=$(echo $line | awk '{print $2}')
port=$(echo $line | awk '{print $9}' | awk -F: '{print $2}')
# Get the command for the process
cmd=$(ps -p $pid -o cmd=)
# Print the information
echo "$now|$pid|$port|$cmd"
done
# List the cron jobs and their processes
echo "Cron jobs:"
crontab -l | while read line
do
# Skip comments and empty lines
if [[ $line == "#"* ]] || [[ -z $line ]]; then
continue
fi
# Extract the schedule and command
schedule=$(echo $line | awk '{print $1" "$2" "$3" "$4" "$5}')
cmd=$(echo $line | awk '{$1=$2=$3=$4=$5=""; print $0}' | xargs)
# Find the process ID for the command
pid=$(ps -ef | grep "$cmd" | grep -v grep | awk '{print $2}')
# Print the information
echo " $schedule|$pid|$cmd"
done
该脚本使用lsof命令来获取所有正在运行的TCP进程,然后使用awk过滤结果以仅显示具有端口号的进程。对于每个进程,脚本提取进程ID、端口号和命令,并将信息打印到STDOUT。
脚本还使用crontab命令获取当前用户的cron作业,并提取计划和命令,然后使用ps命令查找其进程ID并将所有信息打印到STDOUT。
此脚本可以定期运行,以便记录系统中正在运行的应用程序和定期作业的