- #!/usr/bin/python3
- # Management of gandi mail redirections
- #
- ################################################# #####
- # imports
- ################################################# #####
- import requests
- import json
- import sys
- from configGandiAPI import * # Initialization of api_key variable
- ################################################# #####
- # Initiate variables
- ################################################# #####
- debug=False
- # api_key = 'XXX' -> Variable entered in the configGandiAPI.py file
- api_url_base_redir = "https://api.gandi.net/v5/email/forwards/"
- api_url_base_mailboxes = "https://api.gandi.net/v5/email/mailboxes/"
- ################################################# #####
- # Functions
- ################################################# #####
- def print_usage():
- print("Usage:")
- print(" ", sys.argv[0], "-count domain\n\t-> Count domain redirects.")
- print(" ", sys.argv[0], "-list domain\n\t-> List domain redirects.")
- print(" ", sys.argv[0], "-search_src domain string\n\t-> Search source addresses for string.")
- print(" ", sys.argv[0], "-search_dest domain string\n\t-> Searches for a string in destination addresses.")
- print(" ", sys.argv[0], "-create domain new_redir destination\n\t-> Create a new mail redirect.")
- #
- # Reading API in a json
- #
- def list_addresses_redir(api_url, api_key):
- headers = {'authorization': 'Apikey' + api_key}
- print("Downloading", api_url, "...")
- #response = requests.request("GET", api_url, headers=headers)
- response = requests.get(api_url, headers=headers)
- data = response.json()
- head = response.headers
- #print (type(response))
- if str(response) != "<Response[200]>":
- print ("\nProblem accessing the API. \nReturn code = " + str(response))
- quit()
- if debug:
- print("Type data:", type(data))
- #print(data)
- print("Type head:", type(head))
- print(head)
- # print("Type head.link", type(head['link']))
- #print(head['link'])
- # print(response.text)
- # quit()
- return (head, data)
- #
- # Count the number of redirects
- #
- def count_redir(head, domain):
- print(" " + head['total-count'] + " addresses found.")
- #
- # Display nb occurrences
- #
- def displays_nb_occurences(nb_src, liste_dest):
- # Remove duplicates from destination address list
- list_dest = list(set(list_dest))
- print ("\n", nb_src, "source addresses and", len(dest_list), "destination addresses found.")
- #
- # Search if redirect exists
- #
- def search_redir(data, domain, email_string, src_or_dest):
- nb_src = 0
- dest_list = []
- #email_string = email_string.ascii_lowercase()
- for mail_list in data:
- #if src_or_dest == 'source' and (email_string == "ALL" or email_string.lower() in mail_list[src_or_dest].lower() ):
- if src_or_dest == 'source' and (email_string.lower() in mail_list[src_or_dest].lower() ):
- nb_src += 1
- #print ("- " + mail_list['source'] + "@" + domain + "\t-> ", end='')
- src = mail_list['source'] + "@" + domain
- print (" - {:<40} -> "-> ".format(src), end='' )
- for destination in mail_list['destinations']:
- # Counting destination addresses
- ses
- dest_list.append(dest.lower())
- print(dest + ' ', end='')
- print()
- elif src_or_dest == 'destinations':
- for destination in mail_list['destinations']:
- if email_string.lower() in dest.lower():
- nb_src += 1
- #print (" - " + mail_list['source'] + "@" + domain + "\t -> ", dest)
- st)
- src = mail_list['source'] + "@" + domain
- print (" - {:<40} -> ".format(src) + des# Counting destination addresses
- dresses
- dest_list.append(dest.lower(#print (dest + ' ', end='')
- end='')
- displays_nb_occurences(nb_src, list#
- # Create a redirect
- #
- t
- #
- def create_redir(api_url, new_redir, dest):
- payload = "{\":\u"ce\":\"" + new_redir + "\",\"destinations\":[\"" + dest + "\"]}"
- headers = {
- 'authorization': "Apikey" + api_key,
- 'content-type': "application/json"
- }
- response = requests.request("POST", api_url, data=payload, headers=headers)
- print("Return API:", respons#
- # Find Aliases
- #
- iases
- #
- def search_alias(api_url, alias_string, api_key):
- headers = {'authorization': 'Apikey' + api_key}
- response = requests.request("GET", api_url, headers=headers)
- if debug:
- print(response.text)
- data = response.# Path of mailboxes
- ilboxes
- for mail_list in data:
- if debug:
- print(type(data))
- print(mail_list['href'])
- url = mail_list['href']
- headers = {'authorization': 'Apikey' + api_key}
- response = requests.request("GET", url, headers=headers)
- data_detail = response.json()
- print ("\n - Search for mailbox alias '" + data_detail['] + "'s'] + "' ...")
- if debug:
- print(type(data_detail))
- print(response.# Browse mailbox aliases
- al# print(data_detail['aliases'])
- ases'])
- nb_alias = 0
- for alias in data_detail[']:
- #if (alias_string == "ALL" or alias_string.lower() in alias ):
- if (alias_string.lower() in alias):
- nb_alias += 1
- print (" ", alias, end='s, end='')
- print ("\n " + str(nb_alias) + " alias found for mailbox " + data_detail['])
- ################################################# #####
- # Hand
- ################################################# #####
- #
- # Argument testing
- #
- if len(sys.argv) < 3:
- print_usage()
- quit()
- domain = sys.argv[2]
- # 1000 per page to avoid pb pagination
- api_url_redir = api_url_base_redir + domain + "?per_page=1000"
- api_url_mailboxes = api_url_base_mailboxes + domain
- if sys.argv[1] == "-create" and len(sys.argv) == 5:
- new_redir = sys.argv[3]
- dest = sys.argv[4]
- create_redir(api_url_redir, new_redir, dest)
- elif sys.argv[1] == "-count" and len(sys.argv) == 3:
- print("\pCount of mail redirections in domain 'domain '" + domain + "'...")
- tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
- count_redir(tuple_head_redir[0], domain)
- elif sys.argv[1] == "-list" and len(sys.argv) == 3:
- print("\nDisplay of mail redirections for domain '" + domain + "'...")
- tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
- search_redir(tuple_head_redir[1], domain, "", "source")
- print("\nDisplay of mailbox aliases for domain '" + domain + "'...")
- search_alias(api_url_mailboxes, "", api_key)
- elif sys.argv[1] == "-search_src" and len(sys.argv) == 4:
- email_string = sys.argv[3]
- print("\nSearch for '" + email_string + "' in the mail redirections of the domain '" + domain + "'...")
- tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
- search_redir(tuple_head_redir[1], domain, email_string, "source")
- print("\nSearch for '" + email_string + "' in the mailbox aliases of the domain '" + domain + "'...")
- search_alias(api_url_mailboxes, email_string, api_key)
- elif sys.argv[1] == "-search_dest" and len(sys.argv) == 4:
- email_string = sys.argv[3]
- print("\nSearch for '" + email_string + "' in destination addresses of domain '" + domain + "'...")
- tuple_head_redir = lister_adresses_redir (api_url_redir, api_key)
- search_redir(tuple_head_redir[1], domain, email_string, "destinations")
- else:
- print_usage()
Raw Paste