Last active
March 28, 2022 07:22
-
-
Save sh1dow3r/beddaf293f33bcb638357257c07876ae to your computer and use it in GitHub Desktop.
script ran on pfsense router and alert on slack using web-hook when a new IP address is registered
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, json, subprocess, os | |
web_hook = "" | |
filepath = "/tmp/addresses" | |
def msg_sender(hostname, macaddress, ipaddress): | |
slack_data = { | |
"text": "Text.", | |
"blocks": [ | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": "Hostname: `" + hostname + "` \nMac Address: `" + macaddress + "` \nIP Address: `" + ipaddress + "` " | |
} | |
} | |
] | |
} | |
response = requests.post(web_hook, data=json.dumps( | |
slack_data), headers={'Content-Type': 'application/json'}) | |
if response.status_code != 200: | |
raise ValueError( | |
'Request to slack returned an error %s, the response is:\n%s' | |
% (response.status_code, response.text)) | |
def cmd_runner(command): | |
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
output, error = process.communicate() | |
if error: | |
return None | |
return output.decode() | |
def file_writer(macaddress): | |
file_object = open(filepath, 'a') | |
for mac in macaddress: | |
if not check_address(macaddress): | |
file_object.write(mac) | |
file_object.write("\n") | |
def check_address(macaddress): | |
fileExist = os.path.exists(filepath) | |
if not fileExist: | |
f = open(filepath,"w+") | |
file_object = open(filepath, 'r') | |
flines = file_object.readlines() | |
flines = [i.strip("\n") for i in flines] | |
if macaddress in flines: | |
return True | |
return False | |
def arp_reader(): | |
mac_addresses_lst = [] | |
Hostnames = "arp -a | awk '{print $1}'" | |
macaddress = "arp -a | awk '{print $4}'" | |
IPAdress = "arp -a | awk '{print $2}'" | |
Hostnames = cmd_runner(Hostnames).strip().split('\n') | |
macaddress = cmd_runner(macaddress).strip().split('\n') | |
IPAdress = cmd_runner(IPAdress).strip().split('\n') | |
length = len(IPAdress) | |
for record in range(0, length): | |
mac_addresses_lst.append(macaddress[record]) | |
if Hostnames[record] == "?": | |
Hostnames[record] = "None" | |
if not check_address(macaddress[record]): | |
msg_sender(Hostnames[record],macaddress[record], IPAdress[record]) | |
return mac_addresses_lst | |
def worker(): | |
mac_address_lst = arp_reader() | |
file_writer(mac_address_lst) | |
def main(): | |
worker() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is useful. Thank you for sharing.