#!/usr/bin/env python3
"""
Warn Perforce users whose accounts have been inactive for a specified number
of weeks using the P4Python API.
This script connects to the Perforce server and retrieves all user accounts via
the P4Python `users` command. For each user, it examines the last access
time and, if the account has been inactive longer than the configured
threshold, sends an email warning that the account will be deleted in one
week unless it is used.
"""
import argparse
import logging
import smtplib
import sys
import time
from email.message import EmailMessage
from typing import Iterable, Optional
from P4 import P4, P4Exception # type: ignore
import sdputils # type: ignore
def parse_args(argv: Iterable[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Send account inactivity warnings via P4Python",
)
parser.add_argument(
"instance",
nargs="?",
default="1",
help="SDP instance identifier (default: '1')",
)
return parser.parse_args(list(argv))
def connect_p4(instance: str) -> P4:
utils = sdputils.SDPUtils(instance)
p4 = P4()
p4.port = utils.server
# Set user if available
try:
p4.user = utils.p4user # type: ignore[attr-defined]
except AttributeError:
pass
# Set password from file if exists
passwd_path = f"/p4/common/config/.p4passwd.p4_{instance}.admin"
try:
with open(passwd_path) as pf:
p4.password = pf.read().strip()
except FileNotFoundError:
pass
p4.connect()
if p4.password:
p4.run_login()
return p4
def send_email(smtp: smtplib.SMTP, sender: str, recipient: str, subject: str, body: str) -> None:
msg = EmailMessage()
msg["From"] = sender
msg["To"] = recipient
msg["Subject"] = subject
msg.set_content(body)
smtp.send_message(msg)
def warn_inactive_users(
p4: P4,
weeks: int,
mailhost: str,
administrator: str,
complain_from: str,
cc_admin: Optional[str],
server: str,
) -> None:
threshold_seconds = weeks * 7 * 24 * 60 * 60
now = int(time.time())
try:
users = p4.run("users")
except P4Exception as exc:
logging.error("Failed to list users: %s", exc)
return
try:
with smtplib.SMTP(mailhost) as smtp:
for rec in users:
username = rec.get("User") or rec.get("user")
if not username:
continue
# Skip protected accounts
if username.lower() in sdputils.SKIP_USERS:
continue
access_str = rec.get("Access") or rec.get("access")
if not access_str:
continue
try:
access = int(access_str)
except (ValueError, TypeError):
continue
if now - access < threshold_seconds:
continue
email = rec.get("Email") or rec.get("email") or username
subject = f"User {username} on {server} server is scheduled for deletion."
body = (
f"Your Perforce account hasn't been used in the last {weeks} weeks. "
"It will be deleted in one week unless you log into Perforce before that time.\n\n"
"Thanks for your cooperation,\n"
"The Perforce Admin Team\n"
)
# Send to user and optionally CC admin
recipients = [email]
if cc_admin:
recipients.append(cc_admin)
try:
for recip in recipients:
send_email(smtp, administrator, recip, subject, body)
except Exception as exc:
logging.error("Failed to send email to %s: %s", recipients, exc)
except Exception as exc:
logging.error("Unable to connect to SMTP host %s: %s", mailhost, exc)
def main(argv: Iterable[str] | None = None) -> int:
args = parse_args(argv or sys.argv[1:])
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
try:
p4 = connect_p4(args.instance)
except P4Exception:
return 1
try:
utils = sdputils.SDPUtils(args.instance)
weeks = int(utils.get("userweeks"))
administrator = utils.get("administrator")
complain_from = utils.get("complain_from")
cc_admin = utils.get("ccadmin") or None
mailhost = utils.get("mailhost")
warn_inactive_users(p4, weeks, mailhost, administrator, complain_from, cc_admin, utils.server)
finally:
if p4.connected():
p4.disconnect()
return 0
if __name__ == "__main__":
sys.exit(main())
| # | Change | User | Description | Committed | |
|---|---|---|---|---|---|
| #6 | 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 |
||
| #5 | 32388 | Russell C. Jackson (Rusty) | Updates using Claude.ai to clean up the code, reduce duplication, enhanace security, and use current standards. | ||
| #4 | 31825 | Russell C. Jackson (Rusty) | Converted to use P4 api and to use only python 3. | ||
| #3 | 26869 | Russell C. Jackson (Rusty) | Added server to subject of pending deletes. | ||
| #2 | 24675 | Russell C. Jackson (Rusty) |
Fixed bugs in sdputils.py and scripts using it. Converted to standard 2 space spacing, removed copyright stuff. |
||
| #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/email_pending_user_deletes.py | |||||
| #6 | 16638 | C. Thomas Tyler |
Routine merge down to dev from main using: p4 merge -b perforce_software-sdp-dev |
||
| #5 | 16029 | C. Thomas Tyler |
Routine merge to dev from main using: p4 merge -b perforce_software-sdp-dev |
||
| #4 | 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. |
||
| #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/email_pending_user_deletes.py | |||||
| #2 | 10464 | Russell C. Jackson (Rusty) | Corrected typos and added import sys. | ||
| #1 | 10148 | C. Thomas Tyler | Promoted the Perforce Server Deployment Package to The Workshop. | ||