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 rename an existing project from the command line.
This task provides a Python script for renaming a specified analysis, along with some suggestions for modifying the script to suit your needs.
For other scripting options, see:
Note: The Python script in this task is structured to be as similar as possible to those in the other download script tasks listed above.The script requires that special user Anonymous has the following permissions for the project P of interest.
If you will be extending the script to derive the project ID from an analysis directory for some analysis A of the project, you will also need the following permissions for A.
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, os, re, 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 change the name of
import argparse
import os
import re
import subprocess
def rename_project(hubaddr, project_id, newname):
curl_cmd = ['curl']
def check_page(inarg):
args = ['-o', os.devnull, '-w', '%{http_code}']
if isinstance(inarg, str):
args = args + [inarg]
else:
args = args + inarg
http_code = subprocess.check_output(curl_cmd + args)
return (int(http_code.strip())==200)
project_html_url = '{0}/project/{1}.html'.format(hubaddr,project_id)
# Download and scrape Project HTML page for old_name_hash
project_dl=subprocess.Popen(curl_cmd + [project_html_url],
stdout=subprocess.PIPE)
project_page=project_dl.communicate()[0].decode()
onh_match=re.search(r'<input\s+type="hidden"\s+id="old_name_hash"\s+name="old_name_hash"\s+value="((-?)\d+)">',
project_page)
if onh_match is None:
print('Could not get project page', project_html_url)
print('Make sure you have PROJECT_READ permission for this project.')
exit(1)
# Attempt to rename the project; check the HTTP response code.
rename_arguments = ['-d', 'old_name_hash={0}'.format(onh_match.group(1)),
'-d', 'new_name={0}'.format(newname),
project_html_url]
if not check_page(rename_arguments):
print('Could not rename project {0}'.format(project_id))
print('Make sure you have PROJECT_WRITE permission for this project.')
exit(1)
# Fetch and output the updated Project page on success. This is
# not necessary and can be commented out: it just ensures that
# the script outputs the updated page as specified in the Task description.
subprocess.check_call(curl_cmd + [project_html_url])
# Set up.
def go():
parser = argparse.ArgumentParser(
description=('Rename a project on a CodeSonar hub, '
+ 'as specified by the command-line arguments.'))
parser.add_argument("hub",
help="The hub URL.")
parser.add_argument("pid",
help="The project ID of the project to rename")
parser.add_argument("newname",
help="The new project name; must be URL-encoded.")
args = parser.parse_args()
allargs = (args.hub, args.pid, args.newname)
if not any([a is None for a in allargs]):
rename_project(*allargs)
go()
This Python script uses an HTTP POST request to send the new project name to the hub, just as the web form on the Project page would do if you were changing the name in the web GUI. It outputs the updated Project page HTML.
Note that the HTTP POST request must include both the new project name (new_name) and CodeSonar's hash of the current project name (old_name_hash). The CodeSonar hub requires the hash value as a consistency check, so the script must recover it from a separate initial page request.
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. |
| pid |
is the project ID
for the project whose name you wish to change. You can find the project ID:
|
| newname | is new name you wish to set for the project. It must be URL-encoded. |
Using the hub at http://[::1]:7341, change the name of the project with ID 3 to "My Renamed Project ":
| Get more verbose output |
For more verbose curl output,
edit rename_project.py so that
curl is invoked with the
-v flag. For example:
curl_cmd=['curl', '-v'] |
|---|---|
| No files downloaded |
If there is no HTML output, this indicates that cURL did not
download anything. There are two possible reasons.
|
| Downloaded files contain "Permission Denied" messages | If there is an output HTML file but it contains a "Permission Denied" message rather than an updated Project page, this indicates that Anonymous does not have PROJECT_READ and PROJECT_WRITE permission for the analysis. You will need to specify credentials for a user with these permissions. |
You may wish to make one or more of the following modifications.
If you don't want to see the updated HTML file as part of your script's output, you can redirect it to the null location by modifying your curl command. Note that if you make further changes that you need to debug later, you may wish to lift this suppression at least temporarily.
Instead of specifying the project ID on the command line, you can change the script to read the analysis directory from the command line and derive the project ID by reading the most recent analysis ID from the analysis directory, requesting the corresponding Analysis page from the hub, then reading the project ID from the Analysis page.
Because this approach requires the Analysis page for the analysis A in question, you must have the following permissions for A in addition to the required project permissions.
Once you have verified that you have these permissions, proceed as follows.
parser.add_argument("pid", help="The project ID of the project to rename.")
parser.add_argument("adir", help="The analysis .prj_files directory.")
allargs = (args.hub, args.adir, args.newname)
def rename_project(hubaddr, analysis_dir, newname):
with open(os.path.join(analysis_dir,'aid.txt'),'r') as aidfile:
analysis_id=aidfile.read()
analysis_html_url = f'{hubaddr}/analysis/{analysis_id}.html'
# Download and scrape Analysis HTML page for a project ID,
# which will be that of the analyzed project.
analysis_dl=subprocess.Popen(curl_cmd + [analysis_html_url],
stdout=subprocess.PIPE)
analysis_page=analysis_dl.communicate()[0]
pid_match=re.search(r'<a href="/project/(\d+).html">',
analysis_page)
if pid_match is None:
print 'Could not get analysis page', analysis_html_url
print 'Make sure you have ANALYSIS_READ permission for this analysis.'
exit(1)
project_id = pid_match.group(1)
For example: using the hub at http://[::1]:7341, rename the project analyzed in directory whose /myprojects/projectX.prj_files/ to "Another Renamed Project".
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 renaming the project with ID 3 on the hub at http://[::1]:7340 to "IMPORTANT! Keep This!":
python rename_project.py http://jean:xyz123@[::1]:7340 3
IMPORTANT%21%20Keep%20This%21
Username, password, and new name must all 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 rename_project.py at 2:05am every day, renaming the project with project ID 2 on hub http://red:7341 to "My New Name".
5 2 * * * python /path/to/rename_project.py http://red:7341 2 My%20New%20Name
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/.