JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.
If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.
If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.
| CodeSonar® 9.2p0 | CONFIDENTIAL | CodeSecure Inc |
You can use a script to download web GUI files from the command line.
This task provides a Python script for downloading warning reports from a specified analysis, along with some suggestions for modifying the script to suit your needs.
For other scripting options, see:
If you do not need the warning reports and just want a list of warnings, use codesonar dump_warnings.py instead.
To get all warnings from a single analysis, you can use the /analysis/analysis_id-allwarnings.xml URL. For example, to download all warnings from the analysis with ID 5 from the hub at http://myhub:7340, use http://myhub:7340/analysis/5-allwarnings.xml.
The script requires that special user Anonymous has the following permissions for the analysis A of interest.
See Modifying the Script for information on modifying the script to specify credentials for a non-Anonymous user with the required permissions.
The example script imports standard Python modules argparse, csv, os, shutil, and subprocess.
You will need a Python installation to run the script. If you do not have a local installation, you can use the cspython shipped with CodeSonar:
Use the cURL shipped with CodeSonar: $CSONAR/third-party/curl/inst/bin/curl, where $CSONAR is the CodeSonar installation directory. Either:
The following script will download the HTML warning reports for:
and store them under the directory specified in the third argument to the script.
import argparse import csv import os import shutil import subprocess # Identify and download the warnings. def download_warnings(hubaddr, analysis_id, savedir): curl_cmd = ['curl'] def check_page(url): http_code = subprocess.check_output(curl_cmd + ['-w', '%{http_code}', '-o', os.devnull, url]) return (int(http_code.strip())==200) analysis_csv_url = f'{hubaddr}/analysis/{analysis_id}.csv' out_csv = 'warnings.csv' if not check_page(analysis_csv_url): print(f'Could not access analysis page for analysis {analysis_id}') print('This may indicate one or more of the following.') print('- The analysis ID was not specified correctly.') print('- You do not have ANALYSIS_READ permission for the analysis') exit(1) cmdline = curl_cmd + ['-o', out_csv, analysis_csv_url] subprocess.check_call(cmdline) search_results=[] with open(out_csv, 'r', newline='') as csvfile: search_results = csv.DictReader(csvfile) firstrow=True for row in search_results: warning_rel = row['url'].replace('.txt','.html') warning_url = f'{hubaddr}{warning_rel}' if firstrow: if not check_page(warning_url): print(f'Could not access Warning Report {warning_url}.') print(f'Make sure you have ANALYSIS_WARNING_READ permission for analysis {analysis_id}.') exit(1) firstrow=False dl_cmdline = curl_cmd + ['-o', os.path.basename(warning_rel), warning_url] subprocess.check_call(dl_cmdline) if firstrow: # No results: report and exit. print('No warnings were found for analysis ID', analysis_id) print('This may indicate one or more of the following.') print('- The analysis ID was not specified correctly.') print('- You do not have ANALYSIS_WARNING_EXISTS permission for the analysis.') print('- The analysis has no active warnings.') exit(1) # Set up. def go(): parser = argparse.ArgumentParser( description=('Download warnings from an analysis on a CodeSonar hub, ' + 'as specified by the command-line arguments.')) parser.add_argument("hub", help="The hub URL.") parser.add_argument("aid", help="The analysis ID.") parser.add_argument("savedir", help="The save directory.") args = parser.parse_args() allargs = (args.hub, args.aid, args.savedir) if not any([a is None for a in allargs]): if os.path.isdir(args.savedir): print(f'Output directory {args.savedir} exists, deleting and recreating.') shutil.rmtree(args.savedir) os.mkdir(args.savedir) os.chdir(args.savedir) download_warnings(*allargs) go()
This Python script works as follows.
To use this script with your hub, do the following.
| protocol | is the protocol for your hub: http or https. |
|---|---|
| host:port | is the location of your hub. |
| aid |
is the analysis
ID for the analysis whose warnings you wish to
download. You can find the analysis ID:
|
| savepath | is the path to the savedir directory you created in the first step. |
| Get more verbose output |
For more verbose curl output,
edit download_warnings.py so that
curl is invoked with the
-v flag. For example:
curl_cmd=['curl', '-v'] |
|---|---|
| No files downloaded |
If the HTML warning reports are not present, check the command
line output for information. If the only line of output is the
URL of the Analysis: Warnings
CSV file, this indicates that cURL did not attempt to download
any warning reports. There are three possible reasons.
|
| Downloaded files contain "Permission Denied" messages | If there are downloaded HTML files but they contain "Permission Denied" messages rather than warning reports, this indicates that Anonymous does not have ANALYSIS_WARNING_READ permission for the analysis. You will need to specify credentials for a user with the required permissions. |
You may wish to make one or more of the following modifications.
If an Analysis: Warnings URL is specified without a query string component, the default warning filter setting for the authorizing user (Anonymous, in this case) is applied. To apply a different visibility filter, the URL must include a query string that specifies a filter value.
For example, suppose we want to specify the all visibility filter.
analysis_csv_url=f'{hub}/analysis/{analysis_id}.csv?filter=\"all\"'
Warning reports can be output in text and XML formats as well as HTML. To download the XML versions, do the following.
warning_url = row['url'].replace('.txt','xml')
Instead of specifying the analysis ID on the command line, you can change the script to read the analysis directory from the command line and then read the most recent analysis ID from the analysis directory.
parser.add_argument("aid", help="The analysis ID.")
parser.add_argument("adir", help="The analysis .prj_files directory.")
allargs = (args.hub, args.adir, args.savedir)
def download_warnings(hubaddr, analysis_dir, savedir):
with open(os.path.join(analysis_dir,'aid.txt'),'r') as aidfile:
analysis_id=aidfile.read()
For example: using the hub at http://[::1]:7341, download warnings for the analysis whose analysis directory is /myprojects/projectX.prj_files/ and save in directory /tmp/mywarnings.
If your hub is configured so that special user Anonymous does not have the required permissions, you will need to edit the script to submit credentials for a suitable hub user account.
We recommend using bearer authentication. Alternative mechanisms are described in the table below.
For bearer authentication, do the following.
with open('path/to/bearerfile','r') as bearerfile: bearer_token = bearerfile.read().strip()
| path/to/bearerfile | is the path to the file containing the bearer token you want to use. |
|---|
curl_cmd=['curl', '-H', f"Authorization: Bearer {bearer_token}"]
For more information about bearer authentication in CodeSonar, see User Sessions and Anonymous Sessions: Bearer Authentication.
| Certificate |
If the hub is configured for certificate-based
authentication, you can edit the script to
specify a suitable user
certificate.
|
||||
|---|---|---|---|---|---|
| Hard-Coded Username/Password |
If you will be running the Python script under secure
conditions, you may be willing to specify the account username
and password
directly in the script invocation.
For example, if your hub location is http://[::1]:7340 and the hub user account has username jean and password xyz123, the first argument to the script would be http://jean:xyz123@[::1]:7340. Example: Use the hub user account with username jean and password xyz123 to authorize downloading warnings from the hub at http://[::1]:7340 for the analysis with ID 3, saving in directory /tmp/mywarnings:
python download_warnings.py http://jean:xyz123@[::1]:7340 3 /tmp/mywarnings
Both username and password must be URL-encoded.
|
||||
| Username/Password: Other | See the curl man page for alternative username/password authentication mechanisms. |
See CodeSonar HTTP API: Authentication for more information on authentication strategies.
You can follow the overall structure of this script to create Python scripts that download other kinds of file from the hub.
In general, the process for constructing a script will be along the following lines.
You can use your system tools to arrange for the Python script to be run automatically.
For example, if you are using cron, add the following line to your crontab to run download_warnings.py at 2:05am every day, downloading from http://red:7341 the warnings issued by the analysis whose analysis directory is /home/projectX.prj_files/ and saving them in /tmp/mywarnings.
5 2 * * * python /path/to/download_warnings.py http://red:7341 `cat /home/projectX.prj_files/aid.txt` /tmp/mywarnings
Note. This page contains references to HTTP API documentation, which is served directly by the hub and cannot be accessed via a file:// URL. For active HTTP API documentation links, start a hub (if one is not already running), then open the manual from the hub.
To report problems with this documentation, please visit https://support.codesecure.com/.