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: [email protected] ###
########################################################
# 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: [email protected] ###
##################################################
# 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: [email protected] ###
##################################################
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: [email protected] ###
##################################################
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: [email protected] ###
#######################################################################
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
}
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)