The script is designed for the maintenance and management of peers in a Bor network, disconnecting peers that do not meet certain version criteria, and blocking traffic from the IPs associated with those peers.
importsubprocessimportreimportjsonimportosdefremove_peer(enode):command=f'bor attach /var/lib/bor/bor.ipc --exec "admin.removePeer(\'{enode}\')"' try: subprocess.run(command, shell=True, check=True) print(f"Peer removed: {enode}") except subprocess.CalledProcessError as e: print(f"Errorremovingpeer{enode}:{e}")def block_ip(ip_address): block_command = f'sudo iptables -A INPUT -s {ip_address} -j DROP' os.system(block_command) print(f"TrafficfromIP{ip_address}blockedusingiptables")get_peers_command = 'bor attach /var/lib/bor/bor.ipc --exec "admin.peers"'def version_compare(v1, v2): """Compareversionstringsv1andv2.ReturnsTrueifv1islessthanv2.""" return v1 < v2try: result = subprocess.check_output(get_peers_command, shell=True, text=True) result = re.sub(r'([{,]\s*)([A-Za-z_][a-zA-Z_0-9]*)(\s*:)','\\1"\\2"\\3', result) peers = json.loads(result) for peer in peers: caps = peer.get('caps', []) name_version = peer.get('name', '').split('/')[1] if '/' in peer.get('name', '') else '' ip_match = re.search(r'@(\d+\.\d+\.\d+\.\d+):30303', peer['enode']) if "snap/1" not in caps or version_compare(name_version, 'v1'): remove_peer(peer['enode']) if ip_match: ip_address = ip_match.group(1) block_ip(ip_address) else: print(f"Healthypeer:{peer['enode']}")except subprocess.CalledProcessError as e: print(f"Errorgettingthelistofpeers:{e}")
Python and Requests Installation:
Make sure you have Python installed on your system. Open the terminal or command prompt. Execute the following command to install the requests library:
pipinstallrequests
Script Execution:
Save the Python script (Your_script.py) in the directory of your choice.
Run the Script:
In the terminal or command prompt, navigate to the directory where the script is located. Execute the script using the following command:
python3your_script.py
Results:
Iterates over the list of peers obtained from the Geth console. For each peer, it checks whether it has the "snap/1" capability and if the name version is less than "v1". If the above conditions are not met, it removes the peer using admin.removePeer and blocks the traffic from the associated IP using iptables.
Note: You can use cron to automate the periodic execution of the script.