etcd v2 版本数据备份恢复脚本
import requests
import json
import sys
action = sys.argv[1]
etcdaddr = sys.argv[2]
def backup_data():
url = f"{etcdaddr}/v2/keys/?recursive=true"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'node' in data:
with open('/tmp/x', 'w') as file:
json.dump(data['node'], file)
print("Backup completed.")
else:
print("No data found in etcd.")
else:
print("Failed to backup data.")
def store_data():
try:
with open('/tmp/x', 'r') as file:
data = json.load(file)
store_node(data)
print("Store completed.")
except FileNotFoundError:
print("Backup file not found. Please run 'backup' action first.")
sys.exit(1)
def store_node(node):
if 'dir' in node and node['dir'] and 'nodes' in node:
for item in node['nodes']:
if 'dir' in item and item['dir']:
store_node(item)
else:
if 'value' in item:
key = item['key']
value = item['value']
if value is not None:
if isinstance(value, str):
value_str = value
else:
value_str = json.dumps(value)
params = {'value': value_str} # 使用params传递请求参数
requests.put(f"{etcdaddr}/v2/keys{key}", params=params)
if action == "backup":
backup_data()
elif action == "store":
store_data()
else:
print("Invalid action. Please specify 'backup' or 'store'.")
sys.exit(1)
本文来自博客园,作者:萱乐庆foreverlove,转载请注明原文链接:https://www.cnblogs.com/leleyao/p/17997090