Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pr/2 #4

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 58 additions & 22 deletions nessus_report_downloader.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/python
#!/usr/bin/env python3

########################################################################################################
# Name: Nessus Report downloader
# Author: Nikhil Raj ( [email protected] )
#
# Version: 1.0
# Last Updated: 13 Aug 2017
# Version: 1.2
# Last Updated: 2 June 2021
#
# Description: A python script for automating the download of nessus reports in multiple formats.
#
Expand All @@ -23,12 +23,13 @@
import json
import argparse
import time
import pandas as pd
from datetime import datetime

try:
from prettytable import PrettyTable
except ImportError:
print "[-] Unable to load PrettyTable library, will print data in generic format"
print("[-] Unable to load PrettyTable library, will print data in generic format")
HAS_PRETTYTABLE = False
else:
HAS_PRETTYTABLE = True
Expand All @@ -42,9 +43,10 @@
def sendGetRequest(url, headers):
try:
r = requests.get(url, verify=False, headers=headers)
# print("Connecting to " + url + " " + str(headers) + " HTTP Code: " + str(r.status_code))
return r
except requests.exceptions.ConnectionError:
print "[-] Failed to establish connection"
print("[-] Failed to establish connection")
exit(-1)


Expand All @@ -54,7 +56,7 @@ def sendPostRequest(url, json_data={}, headers={}):
r = requests.post(url, verify=False, headers=headers, json=json_data)
return r
except requests.exceptions.ConnectionError:
print "[-] Failed to establish connection"
print("[-] Failed to establish connection")
exit(-1)

# Send HTTP DELETE request
Expand All @@ -63,19 +65,19 @@ def sendDeleteRequest(url, json_data={}, headers={}):
r = requests.delete(url, verify=False, headers=headers, json=json_data)
return r
except requests.exceptions.ConnectionError:
print "[-] Failed to establish connection"
print("[-] Failed to establish connection")
exit(-1)

# Print message on stdout
def printMessage(msg, flag=1):
if flag == 1:
print "[+] " + msg
print("[+] " + msg)
elif flag == 0:
print "[-] " + msg
print("[-] " + msg)
elif flag == 2:
print "[*] " + msg
print("[*] " + msg)
else:
print msg
print(msg)


# Check response code for an HTTP Response and print req message
Expand All @@ -100,7 +102,7 @@ def printTable(data, table_headers):
else:
l.append(str(row[header]))
tab.add_row(l)
print tab
print(tab)


def printScanData(scan_data):
Expand All @@ -111,15 +113,17 @@ def printScanData(scan_data):

if HAS_PRETTYTABLE:
printTable(scan_data["scans"], ["id", "name", "folder_id", "status", "creation_date", "last_modification_date"])
#print(scan_data)
#print(folder_info)
else:
# print scan header
print '\t %-10s %-20s %-20s %-40s %-20s %-20s' %("Scan Id", "Folder Name (id)", "Scan status","Scan Name","creation_date", "last_modification_date")
print '\t %-10s %-20s %-20s %-40s %-20s %-20s' %("-------", "---------------", "------------", "-----------------","-------------------", "--------------------")
print('\t %-10s %-20s %-20s %-40s %-20s %-20s' %("Scan Id", "Folder Name (id)", "Scan status","Scan Name","creation_date", "last_modification_date"))
print('\t %-10s %-20s %-20s %-40s %-20s %-20s' %("-------", "---------------", "------------", "-----------------","-------------------", "--------------------"))
for scan in scan_data["scans"]:
print '\t %-10s %-20s %-20s %-40s %-20s %-20s' %(str(scan["id"]),folder_info[scan["folder_id"]] + ' (' + str(
scan["folder_id"]) + ') ', scan["status"], scan["name"],datetime.fromtimestamp(int(scan["creation_date"])).strftime('%Y-%m-%d %H:%M:%S'),datetime.fromtimestamp(int(scan["last_modification_date"])).strftime('%Y-%m-%d %H:%M:%S'))
print('\t %-10s %-20s %-20s %-40s %-20s %-20s' %(str(scan["id"]),folder_info[scan["folder_id"]] + ' (' + str(
scan["folder_id"]) + ') ', scan["status"], scan["name"],datetime.fromtimestamp(int(scan["creation_date"])).strftime('%Y-%m-%d %H:%M:%S'),datetime.fromtimestamp(int(scan["last_modification_date"])).strftime('%Y-%m-%d %H:%M:%S')))

print '\n'
print('\n')

# Verify user specified folder Id
def verifyScanId(scan_data, ui_scan_id):
Expand All @@ -138,6 +142,7 @@ def verifyScanId(scan_data, ui_scan_id):
else:
printMessage("Omitting invalid Scan ID: " + scan, 0)

#print (valid_scan_list)
return valid_scan_list


Expand Down Expand Up @@ -205,7 +210,9 @@ def getFormatAndChapterList(nessus_format_list, chapter_list, db_pass):

return data

def downloadNessusReport(base_url, token, scan_id_list, json_user_data):
def downloadNessusReport(base_url, token, scan_id_list, scan_data, json_user_data):
name_file = "hehe"

for scan_id in scan_id_list:

printMessage("Format: {0} | Chapter: {1}".format(json_user_data["format"], json_user_data["chapters"]))
Expand All @@ -227,19 +234,21 @@ def downloadNessusReport(base_url, token, scan_id_list, json_user_data):
resp2 = sendGetRequest(url, headers=token_header)

# If nessus report is ready for download, then write the response in external file
url= base_url + "/scans/exports/{0}/download".format(str(file_token["token"]))
url= base_url + "/tokens/{0}/download".format(str(file_token["token"]))
if json.loads(resp2.text)["status"] == "ready":
printMessage("Download link is available now", 1)
resp3 = sendGetRequest(url,headers=token_header)

if checkStatus(resp3, "Started downloading the nessus report",
"Unable to download scan: " + str(scan_id)):
filename = resp3.headers["Content-Disposition"].split('"')[1]
#print(resp3.text)
try:
nessus_file = open(filename, "w")
nessus_file.write(resp3.text)
nessus_file.close()
printMessage("Report was saved in " + filename, 1)
name_file = filename
printMessage("\n", 99)
except IOError:
printMessage("Error occurred while writing to file : " + filename, 0)
Expand All @@ -250,7 +259,33 @@ def downloadNessusReport(base_url, token, scan_id_list, json_user_data):
nessus_file.write(resp3.content)
nessus_file.close()
printMessage("Report was saved in " + filename2, 1)
name_file = filename2
printMessage("\n", 99)

#make site and session column for csv report
if json_user_data["format"] == "csv":
makingNewColumn(scan_data, scan_id, name_file)



def makingNewColumn(scan_data, scan_id, name_file):
new_column = dict()

for scan in scan_data["scans"]:
#print(scan["id"])
if scan["id"] == int(scan_id):
new_column["scan_name"] = scan["name"]
new_column["folder_id"] = scan["folder_id"]

for folder in scan_data["folders"]:
if folder["id"] == new_column["folder_id"]:
new_column["folder_name"] = folder["name"]

#print(new_column)
df = pd.read_csv(name_file)
df["site"] = new_column["scan_name"]
df["session"] = new_column["folder_name"]
df.to_csv(name_file, index = False)


def main():
Expand Down Expand Up @@ -292,7 +327,7 @@ def main():
resp = sendPostRequest(base_url + "/session", creds)
if checkStatus(resp, "Login successful", "Invalid Login credentials"):
token = json.loads(resp.text)
# print token["token"]
# print(token["token"])

# Fetching nessus scan report list
resp = sendGetRequest(base_url + "/scans", headers={'X-Cookie': 'token=' + token['token']})
Expand All @@ -312,6 +347,7 @@ def main():

printMessage("Identified " + str(len(scan_id_list)) + " scan(s) for download\n", 2)

#makingNewColumn(scan_data, scan_id_list)
# Choose default values if not supplied via std input
if not args.format:
printMessage("Missing -f option, using default [0]-nessus format\n",0)
Expand All @@ -323,7 +359,7 @@ def main():
# Create a list of format and chapters for report creation
format_specification = getFormatAndChapterList(args.format, args.chapter, args.db_pass)
for report_format in format_specification:
downloadNessusReport(base_url, token, scan_id_list, json_user_data=report_format)
downloadNessusReport(base_url, token, scan_id_list, scan_data, json_user_data=report_format)

# Logout
resp = sendDeleteRequest(base_url+"/session",headers={'X-Cookie': 'token=' + token['token']})
Expand All @@ -332,4 +368,4 @@ def main():
printMessage("Thanks, See you again!")

if __name__ == '__main__':
main()
main()