forked from nihilexmachina/tenable.io-autoscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tenableio_autoscan.py
165 lines (135 loc) · 5.02 KB
/
tenableio_autoscan.py
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
#!/usr/bin/python3
# v0.6
############
# To-do List#
############
# Task;Status;Date;Validated?
# Initial build;Done;01-12-2021;Y
# Add argument-based selector;Done;02-12-2021;Y
# Basic error handling;Done;03-12-2021;Y
# Additional If logic;Done;10-12-2021;Y
# Logging capabilities;Done;02-03-2023;Y
# Added username display;Done;02-12-2023;Y
########
# Lib #
########
#load dotenv lib
from dotenv import load_dotenv
load_dotenv() #Makes system environment variables available to the script. Needed in [1]. Else, use [2]
# load argparse lib
import argparse
# load tenable.io lib https://github.com/tenable/pyTenable
from tenable.io import TenableIO
# load sys module
import sys
import os
# load Logging
import logging.handlers
import logging
########
# Vars #
########
tio = TenableIO() # [1] Grabs API Keys automatically from env
# tio = TenableIO('TIO_ACCESS_KEY', 'TIO_SECRET_KEY') #[2]
full_list = []
list_never_scanned = []
list_scanned = []
agent_count = None
key = 'last_scanned'
target_group = int(os.getenv('TARGET_GROUP'))
#############
# Functions #
#############
def add_agent():
print("Logged in as: ", tio.users.list()[0]['username'])
print("Searching for Agents that never got scanned...")
try:
for agent in tio.agents.list(('groups', 'neq', '%s' % target_group)):
full_list.append(agent)
for i in full_list:
if key not in tio.agents.details(i['id']):
list_never_scanned.append(i)
agent_count = len(list_never_scanned)
if agent_count == 0:
print("No agents to add. Exiting...")
return
print("The following IDs never got scanned:")
for i in list_never_scanned:
print("Agent ID:", i['id'], "| Agent Name:", i['name'])
for x in list_never_scanned:
print("Adding Agent", x['id'], "(",
x['name'], ")", "to group", target_group)
tio.agent_groups.add_agent(target_group, x['id'])
except:
sys.exit("An error has occurred attempting to add new Agents. Exiting...")
def delete_agent():
print("Logged in as: ", tio.users.list()[0]['username'])
print("Searching for Agents that got scanned...")
try:
for agent in tio.agents.list(('groups', 'eq', '%s' % target_group)):
if key in tio.agents.details(agent['id']):
list_scanned.append(agent)
agent_count = len(list_scanned)
if agent_count == 0:
print("No agents to delete. Exiting...")
return
print("The following IDs got scanned already:")
for i in list_scanned:
print("Agent ID:", i['id'], "| Agent Name:", i['name'])
for i in list_scanned:
print("Deleting Agent",
i['id'], "(", i['name'], ")", "from group", target_group)
tio.agent_groups.delete_agent(target_group, i['id'])
except:
sys.exit("An error has occurred attempting to delete Agents. Exiting...")
def list_agents():
print("Logged in as: ", tio.users.list()[0]['username'])
print("Listing Agents in group", target_group, "...")
try:
for agent in tio.agents.list(('groups', 'eq', '%s' % target_group)):
print("Agent ID:", agent['id'], "| Agent Name:", agent['name'])
except:
sys.exit("An error has occurred attempting to list Agents. Exiting...")
# change to false to not mask the log entries or true to mask
def setup_logging(log_level, mask=False):
if mask:
format = '%(asctime)s %(levelname)s [MASKED]'
else:
format = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(
level=log_level,
format=format,
handlers=[
logging.FileHandler("script.log"),
logging.StreamHandler()
])
def main():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--add', action='store_const',
help='Adds Nessus Agents to group for scanning', const=add_agent)
group.add_argument('--delete', action='store_const',
help='Deletes Nessus Agents from group if already scanned', const=delete_agent)
group.add_argument('--list', action='store_const',
help='Lists Nessus Agents in target group', const=list_agents)
parser.add_argument('--log', choices=['debug', 'info', 'warning', 'error', 'critical'],
default='info', help='Log level')
args = parser.parse_args()
log_level = getattr(logging, args.log.upper(), None)
if not isinstance(log_level, int):
parser.error("Invalid log level: %s" % args.log)
sys.exit(1)
setup_logging(log_level)
if args.add:
add_agent()
elif args.delete:
delete_agent()
elif args.list:
list_agents()
else:
pass
########
# main #
########
if __name__ == "__main__":
main()