Mini Shell

Direktori : /opt/sharedrads/
Upload File :
Current File : //opt/sharedrads/strmailer

#!/opt/imh-python/bin/python3
"""Send email to STR based on stdin or file input.
Optionally, direct that mail elsewhere."""
from platform import node
import argparse
import sys
import yaml
import rads

STR_EMAIL = "str@imhadmin.net"


def get_args():
    '''Get arguments:
    --email(s) - email to send to if not str@
    --user - user for which we're generating the str
    --file - file containing the STR information'''
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '-e',
        '--email',
        type=str,
        dest='emails',
        nargs='*',
        default=[STR_EMAIL],
        help="""
            Provide a different email address for the STR message to be sent.
            If one is not provided, this script will send to {}.
            """.format(
            STR_EMAIL
        ),
    )
    parser.add_argument(
        '-f',
        '--file',
        type=argparse.FileType('r'),
        dest='infile',
        metavar='strinfo.txt',
        nargs=1,
        default=[sys.stdin],
        help="Provide STR information via file",
    )
    parser.add_argument(
        '-u',
        '--user',
        dest='user',
        help="User for which the STR is being generated",
        required=True,
    )
    args = parser.parse_args()
    return args


def get_user_owners() -> dict[str, str]:
    """Get user -> owner map"""
    with open('/etc/trueuserowners', encoding='utf-8') as handle:
        data = yaml.load(handle, rads.DumbYamlLoader)
        if data is None:
            data = {}
    return data


def main():
    '''Main function:
    Get args, get the platform, find the reseller if this is the STR for
    a child account, email STR'''
    args = get_args()
    message = args.infile[0].read()
    # get the shortname by cutting node() at the first .'s index
    hostname = node()[: node().find(".")]
    emails = args.emails
    user = args.user
    subject = f"{user} @ {hostname}"  # "userna5 @ hostname"
    if rads.IMH_CLASS == 'reseller':
        # check reseller ownership from /etc/trueuserowners
        # (faster than whmapi1)
        owner = get_user_owners().get(user, 'root')
        if owner not in rads.OUR_RESELLERS:
            # "child (reseller) @ shortname"
            subject = f"{user} ({owner}) @ {hostname}"

    if not rads.send_email(emails, subject, message):
        print("Failed sending STR. Please try sending the old-fashioned way.")
    else:
        print(f"STR successfully sent with subject '{subject}'.")


if __name__ == "__main__":
    main()

Zerion Mini Shell 1.0