A client asked me last week whether their sudoers config was locked down. The short answer was “no” — I knew about a NOPASSWD rule that someone had added for Jenkins months ago and no one had cleaned up. The real problem is that sudoers and its drop-in directory /etc/sudoers.d can have dozens of files across a fleet. Manual grep misses things. I wrote a Python script that scans both locations, flags dangerous patterns, and checks file permissions.
Links: sudoers(5) man page · GitHub — sudocheck.py
- Python 3.6+ (any modern Linux)
- Read access to
/etc/sudoersand/etc/sudoers.d - (Optional) root — you said you had a sudo audit to run)
Save the script as sudocheck.py on the target machine. Run it with no arguments to scan the default paths:
#!/usr/bin/env python3
"""sudocheck.py — audit sudoers files for risky privilege escalations.
Scans /etc/sudoers and /etc/sudoers.d/*, flags NOPASSWD, ALL=(ALL),
wildcard commands, and world-readable permission on sudoers files."""
import os, re, stat, sys
SUDOERS_DIR = sys.argv[1] if len(sys.argv) > 1 else '/etc/sudoers.d'
SUDOERS_FILE = sys.argv[2] if len(sys.argv) > 2 else '/etc/sudoers'
COMMENT_RE = re.compile(r'^\s*(?:#|//)')
SPEC_RE = re.compile(r'^\s*(\S+)\s+(\S+)=\(([^)]*)\)\s+(.+)$')
METAS = {'Defaults','Host_Alias','User_Alias','Cmnd_Alias','Runas_Alias','@include','@includedir'}
NOPASSWD_RE = re.compile(r'NOPASSWD', re.I)
PASSWD_RE = re.compile(r'PASSWD', re.I)
EXECPT_RE = re.compile(r'\!')
def check_perms(path):
try:
m = os.stat(path)
if m.st_mode & stat.S_IROTH:
return True, oct(m.st_mode)[-3:]
except OSError: return None, None
return False, oct(m.st_mode)[-3:]
def parse_file(path, filename):
findings = []
world_readable, perms = check_perms(path)
if world_readable:
findings.append((filename, -1, 'PERM', f'World-readable ({perms})'))
try:
lines = open(path).read().splitlines()
except OSError: return findings
for lineno, line in enumerate(lines, 1):
if COMMENT_RE.match(line): continue
stripped = line.strip()
if not stripped: continue
if stripped.split()[0] in METAS: continue
m = SPEC_RE.match(stripped)
if not m: continue
user, host, runas, cmdspec = m.groups()
has_nopasswd = bool(NOPASSWD_RE.search(cmdspec))
has_wildcard = ('*' in cmdspec.split(',')[0]) # wildcard in first command path
runas_all = runas.strip() in ('ALL', 'ALL:ALL')
# flag: NOPASSWD alone, or ALL=(ALL)+wildcard
flag = has_nopasswd or (runas_all and has_wildcard)
if flag and not EXECPT_RE.search(cmdspec):
issues = []
if has_nopasswd: issues.append('NOPASSWD')
if runas_all: issues.append('ALL=(ALL)')
if has_wildcard: issues.append('WILDCARD')
findings.append((filename, lineno, '|'.join(issues),
f'{user} {host}=({runas}) {cmdspec.strip()}'))
return findings
def main():
print('=' * 80)
print('SUDOERS AUDIT REPORT')
print('=' * 80)
all_findings = []
if os.path.isfile(SUDOERS_FILE):
all_findings += parse_file(SUDOERS_FILE, 'sudoers')
if os.path.isdir(SUDOERS_DIR):
for fn in sorted(os.listdir(SUDOERS_DIR)):
fp = os.path.join(SUDOERS_DIR, fn)
if os.path.isfile(fp):
all_findings += parse_file(fp, fn)
if not all_findings:
print('No issues found.')
return
print()
fmt = '{:<20} {:<5} {:<22} {}'
print(fmt.format('File', 'Line', 'Issue Type', 'Spec'))
print('-' * 80)
for f, ln, it, spec in sorted(all_findings, key=lambda x: (x[0], x[1])):
print(fmt.format(f, str(ln) if ln > 0 else '-', it, spec[:70]))
print('-' * 80)
print(f'Total issues: {len(all_findings)}')
if __name__ == '__main__':
main()Run it with sudo python3 sudocheck.py. You can also pass a custom sudoers.d directory and sudoers file path if your setup uses non-standard locations:
================================================================================
SUDOERS AUDIT REPORT
================================================================================
File Line Issue Type Spec
--------------------------------------------------------------------------------
deploy 1 NOPASSWD|ALL=(ALL)|WILDCARD deploy2 ALL=(ALL) NOPASSWD: /opt/deploy/*.sh
dev - PERM World-readable (644)
ldap - PERM World-readable (644)
ldap 1 NOPASSWD|ALL=(ALL)|WILDCARD svc_ldap ALL=(ALL) NOPASSWD: /usr/sbin/slapd *
legacy - PERM World-readable (644)
legacy 1 NOPASSWD|ALL=(ALL) tomcat ALL=(ALL:ALL) NOPASSWD: ALL
sudoers 7 NOPASSWD|ALL=(ALL) admin ALL=(ALL) NOPASSWD: ALL
sudoers 9 NOPASSWD|ALL=(ALL) deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/
sudoers 10 NOPASSWD|ALL=(ALL) jenkins ALL=(ALL:ALL) NOPASSWD: ALL
sudoers 11 ALL=(ALL)|WILDCARD monitor ALL=(ALL) /usr/bin/tail -f /var/log/*
sudoers 16 NOPASSWD|ALL=(ALL) OPS ALL=(ALL) NOPASSWD: /usr/bin/apt-get, /usr/bin/vim
--------------------------------------------------------------------------------
Total issues: 11
The script flags three things. PERM means the file is world-readable — sudoers files should always be 0440. NOPASSWD rules let any permitted user run commands without a password, which is the highest risk: a single compromised account becomes full root. WILDCARD paths (like /opt/deploy/*.sh) are dangerous because an attacker who can write anywhere in that tree can execute arbitrary code. Lines flagged with both ALL=(ALL) and NOPASSWD are the most critical — they grant unrestricted root with no authentication gate.
Pair this with the authorized keys audit script for a complete access control review. The local account audit catches stale users that should not have sudo at all. For a full hardening pass, combine all three with the sshd_config audit — one session covers who can log in, who can escalate, and how.

I run this script quarterly on every box I manage. If you have more than a handful of servers, do the same — ask yourself whether every NOPASSWD entry on the report has a documented reason. Most of mine did not.