脚本需求
1、python一个对外接口
2、不同的bitcoin命令通过传不同的参数实现
3、接口及接口的参数依次往后传递
4、日志全部打印到日志文件中并且日志文件按天进行切割
#!/usr/bin/python3
from flask import Flask, request, jsonify
import subprocess
import json
import os
import re
import logging
from logging.handlers import TimedRotatingFileHandler
# 创建一个 TimedRotatingFileHandler,按天切割日志文件,并在每天的凌晨 12 点创建新的日志文件
handler = TimedRotatingFileHandler(filename='ordi-info.log', when='midnight', interval=1, backupCount=7)
handler.suffix = '%Y-%m-%d' # 添加日期后缀
# 配置日志输出格式和日志级别,并添加处理器
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[handler])
# 配置日志输出格式和日志级别,并将日志写入到文件中
#logging.basicConfig(filename='ordi-info.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
app = Flask(__name__)
ord_cmd = ["/data/ord/target/release/ord", "--cookie-file=/data/btc/btcdata/regtest/.cookie", "--rpc-url=127.0.0.1:8540", "-r"]
bitcoincli_cmd=["/data/btc/bin/bin/bitcoin-cli", "-regtest", "--conf=/data/btc/conf/bitcoin.conf"]
def run_command(command):
try:
# 使用 subprocess.run 获取命令执行结果和错误输出
result = subprocess.run(command, capture_output=True, text=True)
# 如果命令返回非零退出码,表示发生错误
if result.returncode != 0:
# 从错误输出中提取包含 "error" 的部分
match = re.search(r'error:.*', result.stderr, re.IGNORECASE)
processed_error_message = match.group(0) if match else "Unknown error"
# 记录错误到日志
logging.error("Error in command execution: %s", result.stderr)
# 手动创建 JSON 响应并设置状态码
response = jsonify({"error": processed_error_message, "normal_output": result.stdout.strip()})
response.status_code = 500
return response
# 记录正常输出到日志
logging.info("Normal output in command execution: %s", result.stdout)
# 返回正常输出到客户端
return result.stdout.strip()
except Exception as e:
# 记录异常到日志
logging.error("Error in command execution: %s", str(e))
return str(e), 500
@app.route('/bitcoin_method', methods=['POST'])
def bitcoin_method():
try:
bitcoin_method_args = request.json['bitcoin_method_args']
return bitcoin_method_impl(*bitcoin_method_args)
except Exception as e:
return jsonify({"error": str(e)}), 400
def bitcoin_method_impl(*bitcoin_method_args):
command = bitcoincli_cmd + list(bitcoin_method_args)
# 使用 subprocess.run 获取命令执行结果和错误输出
result = subprocess.run(command, capture_output=True, text=True)
return run_command(command)
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=2757)
脚本测试
1、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest listwallets
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "listwallets"]}
2、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest getbalances
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "getbalances"]}
3、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest getbalance
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "getbalance"]}
4、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest listunspent
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "listunspent"]}
5、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest getrawchangeaddress
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "getrawchangeaddress"]}
6、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest listaddressgroupings
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "listaddressgroupings"]}
7、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest getblockchaininfo
参数内容{"bitcoin_method_args": ["getblockchaininfo"]}
5、bitcoin-cli --conf=/data/btc/conf/bitcoin.conf -regtest -rpcwallet=btcregtest getrawchangeaddress bech32m
参数内容{"bitcoin_method_args": ["-rpcwallet=btcregtest", "getrawchangeaddress", "bech32m"]}