#!/usr/bin/env python3
"""
Remove one or more Perforce users and their associated clients and shelves
using the P4Python API.
This script accepts either a single username or a file containing a list of
usernames (one per line). For each user, it uses the P4Python API to run
``p4 user -FDy``, which deletes the user along with any clients and shelves
they own. The script respects a list of service accounts that should never
be removed.
"""
import argparse
import logging
import sys
from typing import Iterable
from P4 import P4, P4Exception # type: ignore
import sdputils # type: ignore
def parse_arguments(argv: Iterable[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Remove Perforce users and their associated clients/shelves via P4Python",
)
parser.add_argument(
"instance",
nargs="?",
default="1",
help="SDP instance identifier (defaults to '1')",
)
parser.add_argument(
"user_or_file",
help="Username to remove or path to a file containing one username per line",
)
parser.add_argument(
"--simulate",
action="store_true",
help="Simulation mode: print actions without deleting users",
)
return parser.parse_args(list(argv))
class P4UserRemoverAPI:
"""Helper to manage user deletion using the P4Python API."""
def __init__(self, instance: str) -> None:
self.instance = instance
self.utils = sdputils.SDPUtils(instance)
self.p4: P4 | None = None
def connect_and_login(self) -> None:
try:
self.p4 = self.utils.connect_p4()
except P4Exception as exc:
logging.error("Failed to connect/login: %s", exc)
raise
def delete_user(self, user: str, simulate: bool = False) -> None:
if user.lower() in sdputils.PROTECTED_USERS:
logging.info("Skipping protected user %s", user)
return
logging.info("Deleting user: %s", user)
if simulate:
logging.info("Simulation mode: would run 'user -FDy %s'", user)
return
try:
# run('user', '-FDy', user) deletes the user and associated metadata
self.p4.run("user", "-FDy", user)
logging.debug("Successfully deleted user %s", user)
except P4Exception as exc:
logging.error("Failed to delete user %s: %s", user, exc)
def main(argv: Iterable[str] | None = None) -> int:
args = parse_arguments(argv or sys.argv[1:])
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
remover = P4UserRemoverAPI(args.instance)
# Connect and login once at the beginning
try:
remover.connect_and_login()
except P4Exception:
return 1
# Determine user list
user_list = sdputils.SDPUtils.load_items_or_single(args.user_or_file)
# Delete each user
for user in user_list:
remover.delete_user(user, simulate=args.simulate)
return 0
if __name__ == "__main__":
sys.exit(main())
| # | Change | User | Description | Committed | |
|---|---|---|---|---|---|
| #11 | 32423 | Russell C. Jackson (Rusty) |
Modernize SDP maintenance scripts: security, correctness, and Python 3 - Replace all os.system() and os.popen() calls with subprocess.run() using argument lists to eliminate shell injection vulnerabilities - Fix critical bugs: broken indentation in convert_label_to_autoreload.py, malformed print() in p4lock/p4unlock, wrong variable in isitalabel, format string typo in maintain_user_from_groups - Add p4 property alias and shared SKIP_USERS constant to sdputils.py - Add try/finally with p4.disconnect() to all P4Python scripts - Replace bare except: with specific exception types throughout - Update all shebangs to python3, remove unnecessary __future__ imports - Use context managers for all file handle operations - Replace from subprocess import * with explicit imports |
||
| #10 | 32388 | Russell C. Jackson (Rusty) | Updates using Claude.ai to clean up the code, reduce duplication, enhanace security, and use current standards. | ||
| #9 | 31825 | Russell C. Jackson (Rusty) | Converted to use P4 api and to use only python 3. | ||
| #8 | 30830 | Russell C. Jackson (Rusty) | Switch to using the new -FDy flag to delete users. | ||
| #7 | 28823 | Russell C. Jackson (Rusty) | Added -a to the clients command to pull clients from all servers. | ||
| #6 | 25318 | Russell C. Jackson (Rusty) | Changed ztag to double percent | ||
| #5 | 25025 | Russell C. Jackson (Rusty) | Fixed typo in sdputils.py and forced cfgweeks to be an int. | ||
| #4 | 24919 | Russell C. Jackson (Rusty) | Removed checked for username in p4 users because it is not required. | ||
| #3 | 24675 | Russell C. Jackson (Rusty) |
Fixed bugs in sdputils.py and scripts using it. Converted to standard 2 space spacing, removed copyright stuff. |
||
| #2 | 24648 | Russell C. Jackson (Rusty) |
Updated p4deleteuser to support deleting workspaces off edge servers. Added -a to login in sdputils. |
||
| #1 | 22693 | Russell C. Jackson (Rusty) |
Branched a Unix only version of the SDP. Removed extra items to create a cleaner tree. Moved a few items around to make more sense without Windows in the mix. |
||
| //guest/perforce_software/sdp/dev/Maintenance/p4deleteuser.py | |||||
| #11 | 21745 | Russell C. Jackson (Rusty) | Added quotes around replacements to fix problems with \ in user names. | ||
| #10 | 20607 | Russell C. Jackson (Rusty) | Fixed logic error where p4users list was being created for each user to be deleted. | ||
| #9 | 18888 | Russell C. Jackson (Rusty) |
Added check for shelvedfiles.txt to avoid failure on the open. Added check for user name in the server to avoid reprocessing a user that has already been deleted if you run the script on the same userlist twice. #review @tom_tyler |
||
| #8 | 16638 | C. Thomas Tyler |
Routine merge down to dev from main using: p4 merge -b perforce_software-sdp-dev |
||
| #7 | 16029 | C. Thomas Tyler |
Routine merge to dev from main using: p4 merge -b perforce_software-sdp-dev |
||
| #6 | 15375 | adrian_waters | Routine merge-down from main->dev | ||
| #5 | 13906 | C. Thomas Tyler |
Normalized P4INSTANCE to SDP_INSTANCE to get Unix/Windows implementations in sync. Reasons: 1. Things that interact with SDP in both Unix and Windows environments shoudn't have to account for this obscure SDP difference between Unix and Windows. (I came across this doing CBD work). 2. The Windows and Unix scripts have different variable names for defining the same concept, the SDP instance. Unix uses P4INSTANCE, while Windows uses SDP_INSTANCE. 3. This instance tag, a data set identifier, is an SDP concept. I prefer the SDP_INSTANCE name over P4INSTANCE, so I prpose to normalize to SDP_INSTANCE. 4. The P4INSTANCE name makes it look like a setting that might be recognized by the p4d itself, which it is not. (There are other such things such as P4SERVER that could perhaps be renamed as a separate task; but I'm not sure we want to totally disallow the P4 prefix for variable names. It looks too right to be wrong in same cases, like P4BIN and P4DBIN. That's a discussion for another day, outside the scope of this task). Meanwhile: * Fixed a bug in the Windows 2013.3 upgrade script that was referencing undefined P4INSTANCE, as the Windows environment defined only SDP_INSTANCE. * Had P4INSTANCE been removed completely, this change would likely cause trouble for users doing updates for existing SDP installations. So, though it involves slight technical debt, I opted to keep a redundant definition of P4INSTANCE in p4_vars.template, with comments indicating SDP_INSTANCE should be used in favor of P4INSTANCE, with a warning that P4INSTANCE may go away in a future release. This should avoid unnecessary upgrade pain. * In mkdirs.sh, the varialbe name was INSTANCE rather than SDP_INSTANCE. I changed that as well. That required manual change rather than sub/replace to avoid corrupting other similar varialbe names (e.g. MASTERINSTANCE). This is a trivial change technically (a substitute/replace, plus tweaks in p4_vars.template), but impacts many files. |
||
| #4 | 12028 | C. Thomas Tyler | Refreshed SDP dev branch, merging down from main. | ||
| #3 | 11477 | Russell C. Jackson (Rusty) |
Updated to use /usr/bin/env python Added workshop header. Changed cfg to config. |
||
| #2 | 11464 | Russell C. Jackson (Rusty) | Current maintenance scripts. | ||
| #1 | 10638 | C. Thomas Tyler | Populate perforce_software-sdp-dev. | ||
| //guest/perforce_software/sdp/main/Maintenance/p4deleteuser.py | |||||
| #1 | 10148 | C. Thomas Tyler | Promoted the Perforce Server Deployment Package to The Workshop. | ||