-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground_scanner.py
More file actions
188 lines (154 loc) · 6.74 KB
/
background_scanner.py
File metadata and controls
188 lines (154 loc) · 6.74 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
"""
Background Scanner - Runs network scans in the background and notifies when complete
"""
import argparse
import subprocess
import os
import sys
import time
import json
from datetime import datetime
from colorama import Fore, Style, init
from table_formatter import format_scan_results, save_formatted_results
# Initialize colorama
init()
def run_background_scan(target, ports=None, scan_type="-sV", output_file=None, check_exploits=True, no_table=False, format_output=None, table_style="fancy_grid"):
"""
Run a network scan in the background
Args:
target (str): Target IP address or network range
ports (str): Ports to scan
scan_type (str): Type of scan to perform
output_file (str): Output file for scan results
check_exploits (bool): Whether to check for exploits
no_table (bool): Whether to disable tabular output format
format_output (str): Output file for formatted results
table_style (str): Table style for formatted output
"""
# Generate a timestamp for the output file if not provided
if not output_file:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"scan_results_{timestamp}.json"
# Build the command
cmd = [sys.executable, "network_scanner.py", "-t", target]
if ports:
cmd.extend(["-p", ports])
if scan_type:
cmd.extend(["-s", scan_type])
cmd.extend(["-o", output_file])
if check_exploits:
cmd.append("-e")
if no_table:
cmd.append("--no-table")
if table_style:
cmd.extend(["--table-style", table_style])
if format_output:
cmd.extend(["--format-output", format_output])
print(f"{Fore.BLUE}[*] Starting background scan on {target}{Style.RESET_ALL}")
print(f"{Fore.BLUE}[*] Command: {' '.join(cmd)}{Style.RESET_ALL}")
try:
# Start the process
if os.name == 'nt': # Windows
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
creationflags=subprocess.CREATE_NEW_CONSOLE
)
else: # Unix/Linux
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
start_new_session=True
)
print(f"{Fore.GREEN}[+] Scan started with PID: {process.pid}{Style.RESET_ALL}")
print(f"{Fore.GREEN}[+] Results will be saved to: {output_file}{Style.RESET_ALL}")
if format_output:
print(f"{Fore.GREEN}[+] Formatted results will be saved to: {format_output}{Style.RESET_ALL}")
return process.pid, output_file
except Exception as e:
print(f"{Fore.RED}[!] Error starting background scan: {str(e)}{Style.RESET_ALL}")
return None, None
def check_scan_status(pid):
"""
Check if a scan is still running
Args:
pid (int): Process ID of the scan
Returns:
bool: True if the scan is still running, False otherwise
"""
try:
if os.name == 'nt': # Windows
output = subprocess.check_output(f"tasklist /FI \"PID eq {pid}\"", shell=True, text=True)
return str(pid) in output
else: # Unix/Linux
os.kill(pid, 0) # This will raise an exception if the process is not running
return True
except:
return False
def load_scan_results(output_file):
"""
Load scan results from a file
Args:
output_file (str): Path to the scan results file
Returns:
dict: Scan results
"""
try:
if not os.path.exists(output_file):
print(f"{Fore.RED}[!] Results file not found: {output_file}{Style.RESET_ALL}")
return None
with open(output_file, 'r') as f:
return json.load(f)
except Exception as e:
print(f"{Fore.RED}[!] Error loading scan results: {str(e)}{Style.RESET_ALL}")
return None
def main():
parser = argparse.ArgumentParser(description="Background Network Scanner")
parser.add_argument("-t", "--target", required=True, help="Target IP address or network range (e.g., 192.168.1.1 or 192.168.1.0/24)")
parser.add_argument("-p", "--ports", default="1-1000", help="Ports to scan (e.g., '22,80,443' or '1-1000')")
parser.add_argument("-s", "--scan-type", default="-sV", help="Type of scan to perform")
parser.add_argument("-o", "--output", help="Output file for scan results")
parser.add_argument("-e", "--exploits", action="store_true", default=True, help="Check for exploits after scanning")
parser.add_argument("-w", "--wait", action="store_true", help="Wait for the scan to complete and show results")
parser.add_argument("-f", "--format", action="store_true", help="Format results in a tabular format (deprecated, now always on)")
parser.add_argument("--no-table", action="store_true", help="Disable tabular output format")
parser.add_argument("--format-output", help="Output file for formatted results")
parser.add_argument("--table-style", default="fancy_grid", help="Table style for formatted output (e.g., 'fancy_grid', 'grid', 'simple')")
args = parser.parse_args()
pid, output_file = run_background_scan(
args.target,
args.ports,
args.scan_type,
args.output,
args.exploits,
args.no_table,
args.format_output,
args.table_style
)
if pid and args.wait:
print(f"{Fore.BLUE}[*] Waiting for scan to complete...{Style.RESET_ALL}")
while check_scan_status(pid):
time.sleep(5)
print(f"{Fore.GREEN}[+] Scan complete!{Style.RESET_ALL}")
# Load and display results
results = load_scan_results(output_file)
if results:
if not args.no_table:
print(f"\n{Fore.CYAN}=== Scan Results Summary ==={Style.RESET_ALL}")
format_scan_results(output_file, args.table_style)
else:
print(f"{Fore.GREEN}[+] Scan results:{Style.RESET_ALL}")
for host, host_data in results.items():
if host_data["status"] == "up":
print(f"{Fore.GREEN}[+] Host {host} is up{Style.RESET_ALL}")
for port, port_data in host_data["ports"].items():
service = port_data["service"]
version = port_data["version"]
print(f"{Fore.YELLOW}[+] Port {port} - {service} {version}{Style.RESET_ALL}")
if __name__ == "__main__":
main()