Skip to content

Instantly share code, notes, and snippets.

@joeashcraft
Created September 24, 2021 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeashcraft/94fce279f86f496c084542e2f7d6a438 to your computer and use it in GitHub Desktop.
Save joeashcraft/94fce279f86f496c084542e2f7d6a438 to your computer and use it in GitHub Desktop.
Test if a file exists and is not group-writable
#!/usr/bin/python
"""Test if a file exists and is not group-writable.
AUTHOR: joe.ashcraft@rackspace.com
"""
from __future__ import print_function
import os, stat, sys
def usage():
print("FATAL: invalid usage", file=sys.stderr)
print("USAGE: %s file" % __file__)
sys.exit(1)
def file_not_found():
print("file not found", file=sys.stderr)
sys.exit(1)
def result_bad(n=999):
print("file is group writable")
sys.exit(n)
def result_good():
print("file is not group writable")
sys.exit(0)
try:
FILE = os.path.expanduser(sys.argv[1])
except IndexError:
usage()
if not os.path.exists(FILE):
file_not_found()
# bitwise AND to test if the group-writable bit is set
result = os.stat(FILE).st_mode & stat.S_IWGRP
if result != 0:
result_bad(result)
else:
result_good()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment