Monitor geth to restart by python
#!/usr/bin/python3
# Copyright EricChang(c) 2017 under GNU GPL v3.0 or later
import argparse
import logging
import subprocess
import re
import urllib.request
import json
import time
import os
import logging
def getetherscan():
response = urllib.request.urlopen(
'https://ropsten.etherscan.io/api?module=proxy&action=eth_blockNumber&apikey=8W1ZM4YHDMESNWMS12VBY8CKCVN723V7EM',
None)
responseStr = response.read()
highestblock = int(eval(responseStr)['result'],16)
print("highest block number:", highestblock)
return highestblock
def blockScan():
try:
result = subprocess.run(['geth', '--exec','eth.blockNumber','attach','/root/.ethereum/testnet/geth.ipc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
print(type(e),e)
return -1
if result.returncode ==1:
print("Can't attach to another geth process; exiting")
return -1
output = result.stdout.decode('utf-8').split('\n')
print('current block number = {:d}'.format(int(output[0])))
return int(output[0])
def gethstarter():
os.system("geth --fast --testnet --nat=none -rpc -rpcapi db,eth,net,web3,personal,admin,miner --rpcaddr 0.0.0.0 --rpccorsdomain http://119.23.108.120:8000 -mine --maxpeers=10 &")
logging.debug("geth started!")
def gethkiller():
os.system("killall -9 geth")
logging.debug("geth manual killed!")
if __name__ == '__main__':
logging.basicConfig(filename = os.path.join(os.getcwd(), 'gethlog.txt'), level = logging.DEBUG)
gethstarter()
while 1:
time.sleep(1800)
if getetherscan() - blockScan() > 200 or blockScan() == -1:
logging.debug("current block: %d",blockScan())
logging.debug("highest block: %d", getetherscan())
logging.error('block sync failed, restart the geth')
gethkiller()
gethstarter()
浙公网安备 33010602011771号