跳到主要内容

命令行工具

批量删除僵尸进程ID

 ps -A -ostat,ppid,pid,cmd |grep -e '^[Zz]' | grep -v grep |cut -c 5-13 |xargs kill  -9

显示 linux 内核版本信息

#!/bin/bash
uname -a

批量在多台Linux实例上安装或卸载包

#!/bin/bash
function configurePackages() {
installer=$1
action=$2
packageName=$3
if [ "$installer" = "yum" ]; then
if [ "$action" = "install" ]; then
yum install -y $packageName
if [ $? -ne 0 ]; then
echo "Package install failed. Please check your command"
exit 1
fi
elif [ "$action" = "uninstall" ]; then
yum remove -y $packageName
if [ $? -ne 0 ]; then
echo "Package uninstall failed. Please check your command"
exit 1
fi
else
echo "Package command must be install or uninstall"
exit 1
fi
elif [ "$installer" = "apt-get" ]; then
if [ "$action" = "install" ]; then
apt-get -y install $packageName
if [ $? -ne 0 ]; then
echo "Package install failed. Please check your command"
exit 1
fi
elif [ "$action" = "uninstall" ]; then
apt-get -y remove $packageName
if [ $? -ne 0 ]; then
echo "Package uninstall failed. Please check your command"
exit 1
fi
else
echo "Package command must be install or uninstall"
exit 1
fi
else
echo "Unknown package installer. Only support yum/apt-get"
exit 1
fi
}

configurePackages {{installer}} {{action}} {{packageName}}

显示僵尸进程

#!/bin/bash
processes=$(ps ax -o user,pid,ppid,pgid,args,stat,start,time)
zombies=$(echo -e "${processes}" | grep -E "\s(Z|z|Z.*)\s")
if [ $? == 1 ]; then
echo "no zombie processes exists on machine"
else
echo -e "${processes}" | head -1
echo "$zombies"
fi

批量在多台Linux实例上清理磁盘

#!/bin/bash

function deletefiles() {
if [ ! -d $2 ]; then
echo "The specified directory("$2") is not exist."
return
fi

expiredTimeUnit=${1: -1}
expiredTimeValue=${1:0:-1}

if [ "$expiredTimeUnit" = "d" ]; then
expiredTime=$(($expiredTimeValue * 24 * 60 * 60))
elif [ "$expiredTimeUnit" = "h" ]; then
expiredTime=$(($expiredTimeValue * 60 * 60))
elif [ "$expiredTimeUnit" = "m" ]; then
expiredTime=$(($expiredTimeValue * 60))
else
echo "The unit("$expiredTimeUnit") of file age is not supported."
return
fi

for file in $(find $2 -type f -name "$3"); do
local currentDate=$(date +%s)
local modifyDate=$(stat -c %Y $file)
local existTime=$(($currentDate - $modifyDate))

if [ $existTime -gt $expiredTime ]; then
echo "File cleaning succeeded,path:"$file"."
rm -f $file
fi
done
}

deletefiles {{delayTime}} {{filePath}} "{{matchPattern}}"

查看目录占用磁盘空间大小

#!/bin/bash
du -sh {{directory}}

查看CPU占用率高的进程

#!/bin/bash
TOPK={{topk}}
SECS={{samplingTime}}
INTERVAL={{interval}}
STEPS=$(( $SECS / $INTERVAL ))
TEMP_FILE_PREFIX="/tmp/tat_public_cpu_usage"

echo Watching CPU usage...
for((i=0;i<$STEPS;i++))
do
ps -eocomm,pcpu | tail -n +2 >> $TEMP_FILE_PREFIX.$$
sleep $INTERVAL
done

echo
echo CPU eaters :
cat $TEMP_FILE_PREFIX.$$ | \
awk '
{ process[$1]+=$2;}

END{
for(i in process) {
printf("%-20s %s\n",i, process[i]) ;
}
}' | sort -nrk 2 | head -n $TOPK

rm $TEMP_FILE_PREFIX.$$

检测指定端口和协议是否被iptables封禁

#!/bin/bash

# ports to be checked, seperated by comma.
PORTS="{{PORTS}}"
# supported protocols, available values: all, tcp, udp.
PROTOCOL="{{PROTOCOL}}"

gen_result() {
result=$1
err_info=$2
if [ "$result" == "success" ]; then
echo "result: success"
else
echo "result: failed"
echo "reason: $err_info"
fi
exit 0;
}

check_param() {
protocol=$1
if [ "$protocol" != "all" ] && [ "$protocol" != "tcp" ] && [ "$protocol" != "udp" ]; then
gen_result "failed" "PROTOCOL $protocol is not valid."
fi

ports=$2
IFS=',' read -ra arr <<< "$ports"
for port in "${arr[@]}"; do
[ -n "${port##*[!0-9]*}" ] || gen_result "failed" "port is not number."
done
}

# check if port blocked for specific protocol.
is_port_blocked() {
port=$1
protocol=$2
blocked='false'
if [ "$protocol" == "all" ]; then
if iptables -L -n -v | grep "$port" | head -1 | grep 'tcp\|udp' | grep "DROP" >/dev/null; then
blocked='true'
fi
else
if iptables -L -n -v | grep "$port" | head -1 | grep "$protocol" | grep "DROP" >/dev/null; then
blocked='true'
fi
fi
echo "$port: $blocked"
}

main() {
check_param $PROTOCOL $PORTS

echo "result: success"
IFS=',' read -ra arr <<< "$PORTS"
for port in "${arr[@]}"; do
is_port_blocked "$port" $PROTOCOL
done
}

main

在iptables放开指定协议和端口

#!/bin/bash

# ports to be checked, seperated by comma.
PORTS="{{PORTS}}"
# supported protocols, available values: all, tcp, udp.
PROTOCOL="{{PROTOCOL}}"

gen_result() {
result=$1
err_info=$2
if [ "$result" == "success" ]; then
echo "result: success"
else
echo "result: failed"
echo "reason: $err_info"
fi
exit 0;
}

check_param() {
protocol=$1
if [ "$protocol" != "all" ] && [ "$protocol" != "tcp" ] && [ "$protocol" != "udp" ]; then
gen_result "failed" "PROTOCOL $protocol is not valid."
fi

ports=$2
IFS=',' read -ra arr <<< "$ports"
for port in "${arr[@]}"; do
[ -n "${port##*[!0-9]*}" ] || gen_result "failed" "port is not number."
done
}

open_port() {
port=$1
protocol=$2
protocols=($protocol)
if [ "$protocol" == "all" ]; then
protocols=("tcp" "udp")
fi

for item in "${protocols[@]}"; do
# clear outdated `DROP` and `ACCEPT` rules if exists.
iptables -D INPUT -p "$item" --dport "$port" -j DROP >/dev/null 2>&1
iptables -D INPUT -p "$item" --dport "$port" -j ACCEPT >/dev/null 2>&1
# insert new `ACCEPT` rule.
iptables -I INPUT -p "$item" --dport "$port" -j ACCEPT
done
}

main() {
check_param $PROTOCOL $PORTS

IFS=',' read -ra arr <<< "$PORTS"
for port in "${arr[@]}"; do
open_port "$port" $PROTOCOL || gen_result "failed" "open port failed: $port."
done
}

main && gen_result "success"

添加 ssh

#!/bin/bash
# sshPublicKey null 待添加的ssh公钥,默认保存在 ~/.ssh/id_rsa.pub 。


# ssh public key to be added.
sshPublicKey="{{sshPublicKey}}"

mkdir -p ~/.ssh && chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
echo $sshPublicKey >> ~/.ssh/authorized_keys
echo "operation success!"


批量上传文件

#!/bin/bash
set -e

fileName="{{fileName}}"
contentType="{{contentType}}"
targetDir="{{targetDir}}"
fileOwner="{{fileOwner}}"
fileGroup="{{fileGroup}}"
fileMode="{{fileMode}}"
overWrite="{{overWrite}}"

mkdir -p $targetDir

path=$targetDir/$fileName
# skip if overWrite is false and file already exists.
if [ "$overWrite" = "False" ] && [ -f $path ]; then
echo "file already exists and overWrite is set false, skip."
exit 0
fi

tmpFile=$(mktemp)
cat > "$tmpFile" <<'EOF'
{{fileContent}}
EOF

if [ "$contentType" = "Base64" ]; then
base64 -di "$tmpFile" > $path
rm -f "$tmpFile"
else
mv -f "$tmpFile" "$path"
fi

chgrp $fileGroup "$path"
chown $fileOwner "$path"
chmod $fileMode "$path"

echo "upload file success."



修改密码

 #!/bin/bash

if [ -z '{{userName}}' ]; then
echo 'userName is empty'
exit 1
fi

if [ -z '{{newPassword}}' ]; then
echo 'newPassword is empty'
exit 2
fi

if passwd --help | grep "stdin" > /dev/null 2>&1; then
echo '{{newPassword}}' | passwd '{{userName}}' --stdin
else
echo '{{userName}}:{{newPassword}}' | chpasswd
fi

批量kill 进程

ps -ef | grep rtprecv | grep -v grep | awk '{print $2}' | xargs kill -9

信息
  • ps -ef 用于获取当前系统所有进程,如上图所示。
  • grep rtprecv 过滤出与“rtprecv”字符相关的数据(以行为单位)。
  • grep -v grep 的作用是除去本次操作所造成的影响,-v 表示反向选择。
  • awk {print $2} 表示筛选出我们所关注的进程号,$2 表示每行第二个变量,在这*个例子中就是进程号。所以如果你使用ps工具不一样,或者ps带的参数不一样,那需要关注的就可能不是$2,可能是$1
  • xargs kill -9 中的 xargs 命令表示用前面命令的输出结果(也就是一系列的进程号)作为 kill -9 命令的参数,-9 表示强制终止,不是必须的。