Automated security scanning guide
Practical perspective from an IT leader working across operations, security, automation, and change.
8 minute read with practical, decision-oriented guidance.
Leaders and operators looking for concise, actionable takeaways.
Automated security scanning runs repeatable checks for known vulnerabilities or configuration problems. For a small IT team, its value is a manageable queue of findings with owners, not a large report that nobody can act on.
This guide explains how to choose a first scanning scope, distinguish a failed scan from a clean report and connect results to remediation. It includes an example wrapper for one approved container image. It is not a substitute for authorisation to scan systems or a claim that a zero count proves security.
Choose the scope before the tool
List the assets you are responsible for and obtain permission for the proposed checks. Agree target identifiers, scan windows, rate limits, credentials, exclusions and stop conditions with their owners. Provider terms may restrict scans even when you use the service. Intrusive templates and authenticated checks need particular care.
Start with a small scope whose results the team can investigate. For example, scanning the exact image used by one internal application makes it easier to identify the owner and test a replacement. A scan of an unrelated local image tagged latest may say little about what production runs.
Record the image digest or other immutable target identifier, scanner version, vulnerability database freshness, enabled checks, exclusions and scan time. Those details explain what a result means and allow a later comparison.
Understand what each tool contributes
Container vulnerability scanning compares recognised packages against vulnerability information. Infrastructure-as-code scanning checks supported configuration formats against rules. Web and network scanning interact with services to test particular conditions. Host hardening audits inspect local configuration. They answer different questions.
Nuclei, Trivy, Greenbone Community Edition and Lynis are examples to evaluate for those needs. Check the current tool documentation, licence, supported targets and maintenance requirements before adoption. This guide does not certify their coverage or claim that a Lynis score proves compliance with a CIS benchmark.
A scanner's severity label is one input to triage. An exposed system with evidence of exploitation can need urgent action even when a finding is not labelled critical. Conversely, a reported vulnerable package may need investigation to establish whether the affected code is present and reachable in your configuration.
Do not turn scanner failure into a zero
Counting strings in a result file can confuse missing output with no findings. A command failure, invalid report, unsupported target or outdated database must remain visible.
Trivy's configuration documentation explains that it normally returns exit code zero even when it finds vulnerabilities. That is separate from operational failure. Its reporting documentation also distinguishes a target that was not scanned from a scanned target with zero findings.
A report should therefore say which of these states occurred:
- The scanner failed or the report is inconclusive. Investigate the error and coverage before using the result.
- The scanner reported matching findings. Assign triage and remediation owners.
- The scanner completed and reported no matching findings for its stated scope. Review coverage; this is not an "all clear" for the environment.
Example: one image, a new report directory and explicit exit states
The following Python wrapper calls an installed Trivy binary for one authorised image. It uses a new output directory so a previous successful report cannot be reused accidentally. It records command scope and logs, validates the expected JSON structure and treats missing targets as inconclusive.
The example deliberately enables only vulnerability scanning and filters to high and critical findings. It does not test secrets, configuration, runtime behaviour or every possible vulnerability. The image command may contact an image registry and vulnerability databases; plan permitted connectivity and credentials before running it. Pin and test your scanner version, and review its configuration and ignore files because these can change coverage.
#!/usr/bin/env python3
"""Run one approved image scan. No notification delivery."""
import json
import subprocess
import sys
from pathlib import Path
def main(argv=None):
args = sys.argv[1:] if argv is None else argv
if len(args) != 2 or not args[0].strip():
print('Usage: scan_image.py IMAGE NEW_OUTPUT_DIRECTORY', file=sys.stderr)
return 2
image, directory = args
output = Path(directory)
try:
# A new directory prevents stale reports being mistaken for this run.
output.mkdir(parents=True, exist_ok=False)
command = ['trivy', 'image', '--scanners', 'vuln',
'--severity', 'HIGH,CRITICAL', '--format', 'json',
'--exit-code', '0', '--exit-on-eol', '2',
'--output', str(output / 'report.json'), image]
(output / 'scope.json').write_text(json.dumps({'image': image, 'command': command}))
with (output / 'scanner.log').open('w') as log:
result = subprocess.run(command, stdout=log, stderr=log,
timeout=900, check=False)
if result.returncode != 0:
raise ValueError(f'scanner returned {result.returncode}; inspect scanner.log')
report = json.loads((output / 'report.json').read_text())
if not isinstance(report, dict) or report.get('SchemaVersion') != 2:
raise ValueError('unsupported or malformed report schema')
results = report.get('Results')
if not isinstance(results, list) or not results:
raise ValueError('no reported scan targets; coverage is unconfirmed')
counts = {'HIGH': 0, 'CRITICAL': 0}
targets = []
for item in results:
if not isinstance(item, dict) or not isinstance(item.get('Target'), str) or not item['Target']:
raise ValueError('malformed scan target')
if item.get('Class') not in ('os-pkgs', 'lang-pkgs'):
raise ValueError('unexpected scan class; review coverage')
targets.append(item['Target'])
findings = item.get('Vulnerabilities', [])
if not isinstance(findings, list):
raise ValueError('malformed vulnerability list')
for finding in findings:
if not isinstance(finding, dict) or not finding.get('VulnerabilityID'):
raise ValueError('malformed vulnerability finding')
severity = finding.get('Severity')
if severity not in counts:
raise ValueError('unexpected severity; review scanner configuration')
counts[severity] += 1
summary = {'status': 'findings_reported' if sum(counts.values()) else 'no_matching_findings_reported',
'counts': counts, 'reported_targets': targets,
'coverage': 'operator_review_required'}
(output / 'summary.json').write_text(json.dumps(summary, indent=2))
print(json.dumps(summary))
return 1 if sum(counts.values()) else 0
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
print(f'SCAN FAILED OR INCONCLUSIVE: {error}', file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())Exit 0 means no matching findings were reported in a structurally valid report. Exit 1 means findings were reported. Exit 2 means failure or an inconclusive result. Configure the scheduler to preserve and surface all three outcomes. Do not append separate JSON reports into one file and assume the result is valid JSON.
The wrapper does not infer complete coverage from a successful process. Review scanner.log, the database age, reported targets and any exclusions. For a production gate, compare the report against a known inventory of expected packages and enforce your own freshness and coverage requirements. If those checks fail, keep the result inconclusive.
Test the failure path before scheduling
Use mocked scanner responses to test a successful zero report, findings, a non-zero scanner exit, timeout, missing binary, missing output, invalid JSON and no reported targets. Confirm that none of the failures produces a success summary. Also verify that an existing output directory is rejected. These tests should not contact a real system or deliver a notification.
A useful operational drill is to disable the test scanner binary in a safe test environment and confirm the scheduler shows a failed job. If nobody notices that failure, the automation is not ready to support assurance reporting.
Make results actionable
Create one record per triaged finding with the asset, evidence, owner, exposure, affected version, planned action and due date. Include the reason if a finding is considered a false positive or accepted risk, with an expiry and approver. Medium and low findings should not be automatically suppressed simply because they fall outside the first report's filter.
For a hypothetical application image, a high-severity library finding may lead the owner to build an updated image, run regression tests and scan the replacement. Close the finding after verifying the deployed version and recording the evidence. A ticket marked complete without a checked replacement does not demonstrate remediation.
Urgency depends on exploitability, exposure, active exploitation and business consequence as well as severity. Use the incident response process if there is evidence of compromise. A ransomware response playbook addresses containment and investigation; patching alone may not remove an attacker already inside.
Schedule only what the team can maintain
Choose frequency according to asset change and risk. Scanning an image on build or before deployment can be more useful than repeatedly scanning an unchanged local cache. Network checks need approved windows and load limits; "overnight" does not automatically mean safe for every service.
Keep results and logs with access controls because they reveal system details. Use a supported monitoring or ticketing route for failed runs and urgent findings, with a named owner and deputy. This example writes local output only and sends no email or other message.
A management summary should separate assets expected, assets checked, failed or excluded targets and unresolved findings. A falling count may reflect removed coverage rather than improved security. Explain changes in scope before presenting a trend.
Know the limits
Automated scans do not fully assess application authorisation, business logic, architecture or human procedures. Determine whether a penetration test, configuration review or specialist assessment is needed for the risk. Specific compliance programmes have their own scope and assessor requirements; this toolset does not automatically satisfy them or mean every programme requires an approved scanning vendor.
Review network segmentation and your SIEM strategy alongside scanning. They can help contain exposure and provide evidence of actual activity, while scanning identifies conditions to investigate.
Build a manageable vulnerability process
My security consulting services and IT compliance support can help define scan scope, ownership and evidence for remediation.
Book a consultation with an asset list, a sample report and the failures your team currently cannot distinguish. We can design a small pilot that produces actionable findings and makes missing coverage visible.
Share this post
About the author
Daniel J Glover
IT Leader with experience spanning IT management, compliance, development, automation, AI, and project management. I write about technology, leadership, and building better systems.
Continue exploring
Keep building context around this topic
Jump to closely related posts and topic hubs to deepen understanding and discover connected ideas faster.
Explore topic hubs
Related article
Google Workspace automation: controls
Google Workspace automation is gaining integration options. Decide permissions, approval boundaries and failure handling before enabling Workspace Studio tools.
Related article
Apps Script data residency: scope checks
Review Apps Script data residency after Google's data regions announcement. Map what your automation stores, processes and sends to external services.
Related article
Nvidia Hugging Face deal: buyer checks
Nvidia's proposed Hugging Face acquisition raises practical questions about model portability, platform dependence and the evidence AI buyers need.
Related article
Qwen downloads: the enterprise reality
Qwen's download headlines deserve careful reading. Use this practical evaluation brief to assess model provenance, workload quality and operating ownership.
Want to Know How Your Security Stacks Up?
Automated scanning reveals gaps you did not know existed. Book a free 30-minute security posture assessment to see where your organisation is exposed and how to close those gaps.
Security posture assessmentGet Occasional IT Leadership Insights
IT leadership insights, occasionally. No fluff. Unsubscribe any time.
No spam. Unsubscribe any time.