运维常用脚本(持续更新~)

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)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
学习Python运维的路线可以分为以下几个步骤: 1. 入门阶段: 首先,你需要学习Python的基础知识,包括语法、数据类型、函数、模块等等。可以通过参考中提到的各种学习方法和资源来自学或参加培训课程。 2. 系统管理: 掌握Linux系统管理的基本知识是Python运维的基础。你需要了解Linux命令行操作、文件管理、进程管理、用户管理等内容,以及如何使用Python来实现自动化系统管理任务。可以参考相关的学习资料和教程。 3. 自动化运维工具: 掌握一些常用的自动化运维工具是Python运维的重要一步。例如,掌握使用Ansible、SaltStack等工具来进行配置管理、自动化部署和监控等任务。可以参考相关的文档和教程。 4. 网络管理: 网络管理是Python运维的另一个重要方面。你需要了解网络的基本概念和常用的网络协议,以及如何使用Python编写网络管理脚本。可以参考相关的学习资料和实践项目。 5. 容器化技术: 学习容器化技术如Docker和Kubernetes可以提升你的运维能力。了解如何使用Python来管理和部署容器化应用,以及如何进行容器编排和集群管理。可以参考相关的学习资料和实践项目。 6. 监控和故障排查: 运维工作中经常需要处理系统监控和故障排查的任务。学习使用Python编写监控脚本,以及使用Python进行故障排查和日志分析等工作。可以参考相关的学习资料和实践项目。 总之,学习Python运维需要掌握Python的基础知识,并结合系统管理、自动化工具、网络管理、容器化技术、监控和故障排查等方面的知识来应用。参考中提到的应用范围,你可以根据自己的兴趣和需求选择适合自己的进阶方向。但无论选择哪个方向,都需要保持持续学习和实践的态度。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [一文讲清Python的7大学习路线(建议收藏)](https://blog.csdn.net/m0_60571990/article/details/127176246)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不爱吃肉@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值