37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
|
#!/usr/bin/python3
|
||
|
# Put this script into a Crontab on your Mailcow instance.
|
||
|
# I use an interval of 5 minutes.
|
||
|
import requests
|
||
|
import socket
|
||
|
# Your Mailcow API key
|
||
|
API_KEY=''
|
||
|
# The forwarding host you would like to whitelist
|
||
|
DYN_FWDHOST='dsl-dynamic-host.example.org'
|
||
|
# The public-facing hostname of your Mailcow instance
|
||
|
MAILCOW_HOSTNAME='mx.example.org'
|
||
|
|
||
|
s = requests.Session()
|
||
|
s.headers.update({'X-API-Key': API_KEY})
|
||
|
r = s.get('https://{}/api/v1/get/fwdhost/all'.format(MAILCOW_HOSTNAME))
|
||
|
r.raise_for_status()
|
||
|
current_fwdhosts = r.json()
|
||
|
print('got current hosts: {}'.format(r.text))
|
||
|
home_ip = socket.gethostbyname(DYN_FWDHOST)
|
||
|
current_ips = [x['host'] for x in current_fwdhosts]
|
||
|
if home_ip in current_ips:
|
||
|
exit('Home IP already registered, exiting.')
|
||
|
fwdhosts_to_delete = []
|
||
|
if current_fwdhosts:
|
||
|
for host in current_fwdhosts:
|
||
|
if host['source'] == DYN_FWDHOST:
|
||
|
fwdhosts_to_delete.append(host['host']) # ['host'] => IP
|
||
|
d = s.post('https://{}/api/v1/delete/fwdhost'.format(MAILCOW_HOSTNAME), json=fwdhosts_to_delete)
|
||
|
print('Deleted hosts {} with response {}:'.format(str(fwdhosts_to_delete), d.status_code))
|
||
|
print(d.text)
|
||
|
a = s.post('https://{}/api/v1/add/fwdhost'.format(MAILCOW_HOSTNAME), json={
|
||
|
'filter_spam':'0',
|
||
|
'hostname': DYN_FWDHOST
|
||
|
})
|
||
|
print('Added host {} with response {}'.format(DYN_FWDHOST, a.status_code))
|
||
|
exit(0)
|