Gets information about peers in the Bor network using the admin.peers command in the Geth console. Reads logs from a specified file defined by log_file_path. Filters the logs to find lines containing the string "Peer delivering stale transactions." Extracts the IDs of peers from the filtered logs. Prints the extracted enodes and corresponding IDs. For each peer ID found in the logs, removes the corresponding peer using admin.removePeer in the Geth console.
importsubprocessimportredefget_enodes_from_peers_info(peers_info):enode_pattern=re.compile(r'enode: "([^"]+)",\s+id: "([^"]+)"')enodes=enode_pattern.findall(peers_info)returndict(enodes)defget_peer_id_from_log(log):peer_id_pattern=re.compile(r'peer=([a-fA-F0-9]+)')match=peer_id_pattern.search(log)returnmatch.group(1) ifmatchelseNonedefprint_peer_ids_from_logs(logs):unique_peer_ids=set()print("Peer IDs in logs:")for log inlogs:peer_id=get_peer_id_from_log(log)ifpeer_idisnotNoneandpeer_idnotinunique_peer_ids:unique_peer_ids.add(peer_id)print(f" {peer_id}")returnunique_peer_idscommand="bor attach /var/lib/bor/bor.ipc --exec 'admin.peers'"peers_info=subprocess.check_output(command,shell=True,text=True)log_file_path="/your-path/log"withopen(log_file_path,'r') aslog_file:filtered_logs= [line forlineinlog_fileif"Peer delivering stale transactions"inline]peer_ids_from_logs=print_peer_ids_from_logs(filtered_logs)enodes_dict=get_enodes_from_peers_info(peers_info)print("\nExtracted Enodes:")for enode, peer_id in enodes_dict.items():print(f" {enode}: {peer_id}")for peer_id_from_log inpeer_ids_from_logs:ifpeer_id_from_loginenodes_dict.values():enode_to_remove= [k fork,vinenodes_dict.items() ifv==peer_id_from_log][0]print(f"\nRemoving enode: {enode_to_remove}")remove_command=f'bor attach /var/lib/bor/bor.ipc --exec \'admin.removePeer("{enode_to_remove}")\'' subprocess.run(remove_command, shell=True, text=True) print(f"Enode removed: {enode_to_remove}") else: print(f"\nPeer ID {peer_id_from_log} not found in peers.")
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:
The script is useful for identifying specific peers based on specific logs and then removing those peers from the Bor network. Make sure to adjust the log file path (log_file_path) to the correct location before running the script.
Note: You can use cron to automate the periodic execution of the script