shell脚本
颜色函数及格式化输出函数(此文shell脚本全局引用)
###################################################################################
# Color function
#############################################################################################
function COLOR_RED() {
echo -e "\033[1;31m$1\033[0m"
}
function COLOR_GREEN() {
echo -e "\033[1;32m$1\033[0m"
}
function COLOR_YELLOW() {
echo -e "\033[1;33m$1\033[0m"
}
###################################################################################
# Format output function
###################################################################################
function log_success() {
COLOR_GREEN "[SUCCESS] $1"
}
function log_error() {
COLOR_RED "[ERROR] $1"
}
function log_info() {
COLOR_YELLOW "[INFO] $1"
}
1.获取k8s中某一个deployment下所有pod的ready状态,并将结果发送到企业微信
#!/bin/bash
########################################################
### Description: Get Deployment Pod Ready Status ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
########################################################
# appoint deployment name
deployment_name="deployment-example"
# Get the name of all pods in the deployment
pod_names=$(kubectl get pods -l app=$deployment_name -o jsonpath="{.items[*].metadata.name}")
# Loop through each pod and get its ready status
for pod_name in $pod_names; do
ready_status=$(kubectl get pod $pod_name -o jsonpath="{.status.conditions[?(@.type=='Ready')].status}")
if [ "${ready_status}" == "True"];then
log_success "$pod_name is now ready"
elif [ "${ready_status}" == "False" ];then
log_error "$pod_name is Not ready"
else
log_info "$pod_name In unknown state"
fi
#echo "$pod_name is $ready_status"
# Send message
WEBHOOK_URL="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<YOURKEY>"
curl -X POST $WEBHOOK_URL -H 'Content-Type: application/json' -d '
{
"msgtype": "text",
"text": {
"content": "'"$pod_name is $ready_status"'"
}
}'
done
2.shell批量ping脚本
#!/bin/bash
##################################################
### Description: Batch ping ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
##################################################
# You can store the IP or domain name to be tested in a file
[root@localhost tmp]# cat hosts.txt
192.168.1.101
192.168.1.102
192.168.1.103
www.baidu.com
www.bing.com
www.jd.com
for ip in `cat /tmp/hosts.txt`
do
ping -c 1 $ip &> /dev/null
if [ $? -eq 0 ]
then
log_success "$ip is up"
else
log_error "$ip is down"
fi
done
3.检测当前用户是否是超级管理员(root)
#!/bin/bash
##################################################
### Description: Detect current user ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
##################################################
if [ $(id -u) -eq 0 ]; then
log_success "Current user is root."
else
log_info "Current user is not root."
fi
4.获取Linux系统信息
##################################################
### Description: Get system information ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
##################################################
function print_system_info()
{
KERNEL_DIR="/etc/redhat-release"
CPU_DIR="/proc/cpuinfo"
SYSTEM_DATE=$(/usr/bin/date)
SYSTEM_VERSION=$(cat ${KERNEL_DIR})
SYSTEM_CPU=$(cat ${CPU_DIR} | grep 'model name' | head -1 | awk -F: '{print $2}' | sed 's#^[ \t]*##g')
SYSTEM_CPU_NUMS=$(cat ${CPU_DIR} | grep 'model name' -c)
SYSTEM_KERNEL=$(uname -a | awk '{print $3}')
SYSTEM_IPADDR=$(hostname -I | awk '{print $1}')
SYSTEM_HOSTNANE=$(hostname)
# 输出系统信息
log_info "操作系统名称: ${SYSTEM_HOSTNANE}"
log_info "服务器IP地址: ${SYSTEM_IPADDR}"
log_info "操作系统版本: ${SYSTEM_VERSION}"
log_info "系统内核版本: ${SYSTEM_KERNEL}"
log_info "处理器的型号: ${SYSTEM_CPU}"
log_info "处理器的核数: ${SYSTEM_CPU_NUMS}"
log_info "系统当前时间: ${SYSTEM_DATE}"
}
5.Linux免密远程登录
#######################################################################
### Description: Bulk distribution of secret free public key ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
#######################################################################
function confidentiality_free_configuration()
{
log_info "Configure Password Free Login."
# 将要分发的服务器IP、用户名及密码写入文本文件中
HOSTS_DIR="/scripts/iplist.txt"
cat >${HOSTS_DIR} <<EOF
192.168.1.200 root redhat
192.168.1.101 root redhat
192.168.1.102 root redhat
EOF
# 判断密钥文件是否存在
if [ `ls -al /root/.ssh/ |grep id_rsa|wc -l` -eq 0 ]; then
ssh-keygen -t rsa -N '' <<EOF
/root/.ssh/id_rsa
yes
EOF
else
log_info " The “id_rsa” already exists in this machine"
fi
# 安装自动化交互软件except
yum -y install expect
# 分发公钥
while read host;do
ip=$(echo "$host" |cut -d " " -f1)
username=$(echo "$host" |cut -d " " -f2)
password=$(echo "$host" |cut -d " " -f3)
expect <<EOF
spawn ssh-copy-id -i $username@$ip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "$password\n"}
}
expect eof
EOF
done < ${HOSTS_DIR}
# 测试免密远程连接服务器是否配置成功
log_info "host $ip pub-key check"
USERNAME="root"
HOSTS=$(cat ${HOSTS_DIR} | awk '{print $1}')
for ip in ${HOSTS}; do
if ssh "$USERNAME"@"$ip" "echo ${HOSTNAME}"; then
log_success "${ip} Connection successful."
else
log_error "${ip} connection failed."
fi
done
}
6.批量导出docker镜像
#######################################################################
### Description: Batch Docker Images Export ###
### Auther: Huang-Bo ###
### Email: haunbo@163.com ###
#######################################################################
# 设置要导出的镜像列表
image_list=(
"node:12.22.11-buster"
"node:12.22.12-buster"
"node:14.21.3-buster"
"node:16.20.0-buster"
"node:18.16.0-buster"
"golang:1.20.4"
"mcr.microsoft.com/dotnet/sdk:6.0"
"mcr.microsoft.com/dotnet/aspnet:6.0"
"docker:20.10.23"
)
# 设置导出镜像的目录
export_dir="/opt/docker_image"
# 创建导出目录
mkdir -p "$export_dir"
# 循环遍历镜像列表
for image in "${image_list[@]}"
do
# 导出镜像
docker save "$image" -o "$export_dir/$image.tar"
# 输出导出完成的消息
echo "镜像 $image 导出完成!"
done
echo "所有镜像导出完成!"
7.批量停止指定命名空间deployment
# cat /deploy_list/deployment_list.txt
nginx-temp
sentinel-dashboard-deploy
deployment_list=`cat /deploy_list/deployment_list.txt`
namespaces="ops"
k8s_cluster="k8s-test"
# 切换集群
kubectl config use-context ${k8s_cluster}
log_info "########容器调整前副本数如下:########"
# 查看当前副本数
for deploy in ${deployment_list};do
replicas=$(kubectl get deployment ${deploy} --namespace=${namespaces} -o jsonpath='{.spec.replicas}')
log_info "Deployment\tReplicas"
log_info "${deploy}\t${replicas}"
done
#调整副本数
target_replicas=0
log_info "###########开始停止容器##############"
for deploy in ${deployment_list};do
kubectl scale -n ${namespaces} deployment --replicas=${target_replicas} ${deploy}
done
log_info "********************************"
log_success "###########容器停止完成##########"
# 查看调整后副本数
for deploy in ${deployment_list};do
replicas=$(kubectl get deployment ${deploy} --namespace=${namespaces} -o jsonpath='{.spec.replicas}')
log_info "########当前容器副本数如下:########"
log_info "Deployment\tReplicas"
log_info "${deploy}\t${replicas}"
done
8.修改k8s pod副本数
# cat /deploy_list/deployment_list.txt
nginx-temp 1
sentinel-dashboard-deploy 3
file_path="/deploy_list/deployment_list.txt"
namespace="ops"
# 涉及到配置了多集群kubeconfig时,可以先切换大指定集群
k8s_cluster="k8s-test"
log_info "********开始修改pod副本数********"
while read -r line; do
# 读取文件并将文件中的两行内容作为变量传递
read -r deploy_name replicas <<< "${line}"
# 切换k8s content(涉及到配置了多集群kubeconfig时,可以先切换大指定集群.但集群可以忽略)
kubectl config use-context ${k8s_cluster}
# 查看调整前容器组的副本数
current_replicas=$(kubectl get deployment "${deploy_name}" --namespace="${namespace}" -o=jsonpath='{.spec.replicas}')
log_info "Current replicas for ${deploy_name}: ${current_replicas}"
# 调整容器组pod副本数
kubectl scale deployment --replicas=${replicas} --namespace=${namespace} ${deploy_name}
# 查看调整后的副本数
updated_replicas=$(kubectl get deployment "${deploy_name}" --namespace="${namespace}" -o=jsonpath='{.spec.replicas}')
log_success "Updated replicas for ${deploy_name}: ${updated_replicas}"
done < "${file_path}"
9.批量修改K8S ingress tls证书
#!/bin/bash
old_tls_name="tls-renew-expired-2025"
new_tls_name="tls-renew-expired-2024"
cluster_name="k8s-test"
namespace="ops"
current_date=$(date +"%Y-%m-%d")
# 切换到指定集群
kubectl config use-context ${cluster_name}
# 导出指定namespace下的ingress yaml
kubectl get -n ${namespace} ingress -oyaml > ./${namespace}_ingress.yaml
# 查找老的ingress secretname的值
# 备份修改前的yaml
cp ${namespace}_ingress.yaml ${namespace}_ingress.yaml-${current_date}
# 更新secretname的值
sed -i 's/old_tls_name/${new_tls_name}/g' ${namespace}_ingress.yaml
# 应用更新后的配置
kubectl apply -f ${namespace}_ingress.yaml
python脚本
1 python批量ping域名或者ip
import subprocess
import platform
# hosts = ['www.baidu.com', 'www.baidu.com', 'www.jd.com']
hosts = ['192.168.1.101','192.168.1.102','192.168.1.103']
def ping(host):
param = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
for host in hosts:
if ping(host):
print(host, 'is up!')
else:
print(host, 'is down!')
2.实时监测站点可用性,并将结果发送至企业微信
import requests
import time
# 定义要检测的域名
url = "http://xxxx.xxx.com"
webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<YOUR TOCKEN>"
def send_message(msg, webhook):
payload = {
"msgtype": "text",
"text": {
"content": msg
}
}
headers = {
'Content-Type': 'application/json;charset=utf-8'
}
response = requests.post(webhook, json=payload, headers=headers)
if response.status_code != 200:
raise ValueError("Failed to send message, response code: {}".format(response.status_code))
def get_website_status(url):
tempStatusCode = 200
while True:
response = requests.get(url)
status_code = response.status_code
if tempStatusCode == status_code:
continue
if status_code == 200:
msg = "Website is up and running! Website Name is: %s Return code is: %d" %(url,status_code)
print("Website is up and running!")
send_message(msg,webhook)
elif status_code == 404:
msg = "The page does not exist Website Name is: %s Return code is: %d" %(url,status_code)
send_message(msg,webhook)
print("The page does not exist")
elif status_code == 403:
msg = "No permission to access Website Name is: %s Return code is: %d" %(url,status_code)
send_message(msg,webhook)
print("No permission to access")
elif status_code == 503:
msg = "Back-end application is not ready, please check the application status Website Name is: %s Return code is: %d" %(url,status_code)
send_message(msg,webhook)
print("Back-end application is not ready, please check the application status")
elif status_code == 504:
msg = "Gateway timeout, please confirm whether the back-end server status is normal Website Name is: %s Return code is: %d" %(url,status_code)
send_message(msg,webhook)
print("Gateway timeout, please confirm whether the back-end server status is normal")
elif status_code == 502:
print("Gateway error request did not reach the backend application")
else:
msg = "Unusual error code Website Name is: %s Return code is: %d" %(url,status_code)
send_message(msg,webhook)
print("Unusual error code")
tempStatusCode = status_code
time.sleep(3)
get_website_status(url)