-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiplookup.py
More file actions
executable file
·119 lines (106 loc) · 4.61 KB
/
iplookup.py
File metadata and controls
executable file
·119 lines (106 loc) · 4.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# IPlookup
# 05/08/2025 0.01 Initial script
# 06/08/2025 0.02 Logging policy updated
# 11/08/2025 0.03 Minor update
# 14/08/2025 0.04 Add proxy support
# 05/09/2025 0.05 Change standard output to JSON format and proxy configuration
# 29/10/2025 0.06 Search FQDN from certificates found on opened/filtered ports
import argparse
import os
import sys
import json
import csv
import easydict
from sys import stdout
from lib.log import setup_logger
from lib.ipinfo import ip
__version__ = '0.06'
def get_options():
""" Argument control """
parser = argparse.ArgumentParser(description=f"--== IP lookup v{__version__} ==--")
parser.add_argument('-V', '--version', action='version', version='{} v{}'.format(os.path.basename(__file__), __version__))
parser.add_argument('-d', '--debug', dest='debug', help='enable debug mode', action="store_true")
parser.add_argument('--nmap', dest='nmap', help='get FQDN from TLS certificate(s) retrieved from ports identified by nmap', action='store_true')
parser.add_argument('--nmap-port', dest='nmap_port', nargs='+', help='get FQDN from TLS certificate(s) retrieved from ports given in argument', metavar='<port>', type=int, action='store')
parser.add_argument('-i', dest='ip', help='IP to check', metavar='<ip address>')
parser.add_argument('--file', dest='ipfile', help='IPs to check', metavar='<filename>', action='store')
parser.add_argument('-s', '--separator', dest='separator', help='specify the separator used in input CSV file', metavar='<separator_character>', default=',')
parser.add_argument('--field', '--field', dest='field', help='select field includes IP address', metavar='<separator_field>')
parser.add_argument('--format', dest='output_format', help='specify output format (default: csv)', choices=['json', 'csv'], default='csv', type=str.lower)
parser.add_argument('-o', '--output', dest='output_file', help='specify the output filename', metavar='<filename>', action='store')
parser.add_argument('--proxy', dest='proxy', help='specify HTTP proxy with port. Example: "localhost:3128"', metavar='<proxy_host>:<proxy_port>', type=parse_proxy, action='store')
parser.add_argument('--noproxy', dest='noproxy', help='Ignore system proxy (if defined)', action="store_true")
return parser
def parse_proxy(value):
try:
host, port = value.split(":")
return host, int(port)
except ValueError:
raise argparse.ArgumentTypeError("Proxy must be defined as <host>:<port>. (Example: localhost:3128)")
def output_json(data, output_file=None):
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
else:
json.dump(data, sys.stdout, indent=2)
print() # newline for clean terminal output
def output_csv(data, output_file=None):
if not data:
logger.error("No data to write to CSV.")
return False
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
if __name__ == "__main__":
# Initialization
args_parser = get_options()
args = args_parser.parse_args()
script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
if args.debug:
log_level = 10 # DEBUG
else:
log_level = 20 # INFO
logger = setup_logger(script_name, log_level)
if not args.nmap_port:
args.nmap_port = ['443', '4443', '5443']
if not args.proxy and not args.noproxy and 'https_proxy' in os.environ:
# Use default proxy
logger.debug('Proxy system detected. Script will use it.')
default_proxy = os.environ['https_proxy'].split('/')[-1].split('@')[-1]
args.proxy = parse_proxy(default_proxy)
else:
# Ignore system proxy
args.proxy = None
result = []
nb_ip = 0
if not args.ip and not args.ipfile:
args_parser.print_help()
sys.exit(1)
if args.ip:
nb_ip += 1
ip.set_log_level(log_level)
result.append(ip.lookup(args.ip, proxy=args.proxy, nmap_action=args.nmap, nmap_port=args.nmap_port))
elif args.ipfile:
with open(args.ipfile, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=args.separator)
ip.set_log_level(log_level)
for row in reader:
if len(row) == 1:
item = row[0]
else:
item = row[args.field]
nb_ip += 1
if res := ip.lookup(item, proxy=args.proxy, nmap_action=args.nmap, nmap_port=args.nmap_port):
result.append(res)
if result:
logger.info(f"{len(result)} lookup(s) successfully performed for {nb_ip} IP address(s) given.")
if isinstance(result, dict):
result = [result]
if args.output_file:
eval(f"output_{args.output_format}")(result, args.output_file)
else:
# Return result (in JSON format) to STDOUT
output_json(result)