759 字
4 分钟
Python 运维基础脚本
Python 运维基础脚本
1. 文件操作
# 读取文件所有行并统计行数with open("/etc/passwd", 'r') as f: lines = f.readlines() print(f"行数: {len(lines)}")
# 逐行读取(大文件推荐)with open("/var/log/messages", 'r') as f: for line in f: if 'error' in line.lower(): print(line.strip())
# 写入文件with open("/tmp/output.txt", 'w') as f: f.write("第一行\n") f.write("第二行\n")
# 追加写入with open("/tmp/log.txt", 'a') as f: f.write("新的日志行\n")2. 目录遍历
import os
# 列出目录内容print(os.listdir('/etc/'))
# 递归遍历目录树for root, dirs, files in os.walk('/etc/'): for f in files: print(os.path.join(root, f))
# 判断路径类型os.path.exists('/etc/passwd') # 是否存在os.path.isfile('/etc/passwd') # 是否为文件os.path.isdir('/etc/') # 是否为目录3. 命令行参数解析(argparse)
比赛开发题必用模块,用于构建命令行工具。
import argparse
parser = argparse.ArgumentParser(description='示例工具')sub = parser.add_subparsers(dest='command')
# create 子命令p_create = sub.add_parser('create', help='创建资源')p_create.add_argument('-n', '--name', required=True, help='资源名称')p_create.add_argument('-m', '--memory', type=int, default=512, help='内存大小(MB)')
# delete 子命令p_del = sub.add_parser('delete', help='删除资源')p_del.add_argument('-n', '--name', required=True, help='资源名称')
# list 子命令sub.add_parser('list', help='列出所有资源')
args = parser.parse_args()
if args.command == 'create': print(f"创建 {args.name}, 内存 {args.memory}MB")elif args.command == 'delete': print(f"删除 {args.name}")elif args.command == 'list': print("列出所有资源")# 使用方式python tool.py create -n test -m 1024python tool.py delete -n testpython tool.py list4. JSON 处理
import json
# 字典转 JSON 字符串data = {"name": "server01", "status": "active"}json_str = json.dumps(data, indent=2)print(json_str)
# JSON 字符串转字典parsed = json.loads('{"name": "server01", "status": "active"}')print(parsed['name'])
# 读取 JSON 文件with open('config.json', 'r') as f: config = json.load(f)
# 写入 JSON 文件with open('output.json', 'w') as f: json.dump(data, f, indent=2, ensure_ascii=False)5. HTTP 请求(requests)
RESTful API 开发的核心模块。
import requests, json
# GET 请求resp = requests.get('http://192.168.1.10:8774/v2.1/flavors', headers={'X-Auth-Token': 'xxx'})print(resp.status_code)print(resp.json())
# POST 请求body = {"flavor": {"name": "test", "ram": 1024, "vcpus": 2, "disk": 20}}resp = requests.post('http://192.168.1.10:8774/v2.1/flavors', data=json.dumps(body), headers={'X-Auth-Token': 'xxx', 'Content-Type': 'application/json'})
# PUT 请求resp = requests.put('http://192.168.1.10:9292/v2/images/xxx/file', data=open('image.qcow2', 'rb').read(), headers={'X-Auth-Token': 'xxx', 'Content-Type': 'application/octet-stream'})
# DELETE 请求resp = requests.delete('http://192.168.1.10:5000/v3/users/xxx', headers={'X-Auth-Token': 'xxx'})print(resp.status_code) # 204 表示成功6. YAML 处理
K8S 开发题常用,用于读写资源清单。
import yaml
# 读取 YAML 文件with open('deployment.yaml', 'r', encoding='utf-8') as f: data = yaml.safe_load(f)print(data['kind']) # Deployment
# YAML 字符串转字典yaml_str = """apiVersion: v1kind: Podmetadata: name: nginx"""parsed = yaml.safe_load(yaml_str)
# 字典转 YAML 字符串output = yaml.dump(parsed, default_flow_style=False)print(output)7. 系统命令调用(subprocess)
import subprocess
# 执行命令并获取输出result = subprocess.run(['kubectl', 'get', 'pods'], capture_output=True, text=True)print(result.stdout)print(result.returncode) # 0 表示成功
# 执行 shell 命令result = subprocess.run('openstack server list', shell=True, capture_output=True, text=True)print(result.stdout)
# 检查命令是否执行成功if result.returncode != 0: print(f"命令失败: {result.stderr}")8. 异常处理
import requests
# 基本异常捕获try: resp = requests.get('http://192.168.1.10:5000/v3/users', timeout=5) resp.raise_for_status() # 非 2xx 状态码抛异常except requests.exceptions.ConnectionError: print("连接失败")except requests.exceptions.Timeout: print("请求超时")except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}")
# K8S SDK 异常处理from kubernetes.client.exceptions import ApiException
try: api.delete_namespaced_pod('nginx', 'default')except ApiException as e: if e.status == 404: print("Pod 不存在") else: print(f"API 错误: {e.status} - {e.reason}")9. 日志记录
import logging
logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
logger.info("服务启动")logger.warning("配置文件缺失,使用默认值")logger.error("连接数据库失败")10. 环境变量读取
import os
# 读取环境变量(带默认值)host = os.getenv('OS_AUTH_URL', 'http://192.168.1.10:5000/v3')password = os.getenv('OS_PASSWORD', '000000')debug = os.getenv('DEBUG', 'false').lower() == 'true' Python 运维基础脚本
https://blog.xeu.asia/posts/python-ops-scripts/