Mini Shell

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

#!/opt/imh-python/bin/python3
'''sample_spam written by Michael M. for
sending message samples to spamtrends'''
import argparse
import smtplib
from getpass import getuser
from tempfile import TemporaryFile
import subprocess
from platform import node as hostname
from random import random
from email.mime.text import MIMEText
import rads.color

FROM_ADDR = f"{getuser()}@{hostname()}"
TARGET_ADDR = 'spamtrends@imhadmin.net'


def arg_init():
    '''Parse those args'''
    parsed = argparse.ArgumentParser(
        description='Send a sample spam message for an address/id provided'
    )
    require = parsed.add_mutually_exclusive_group(required=True)
    # fmt: off
    require.add_argument(
        '--id', '-i', metavar='1ZZ3kz-2340bc-L5',
        help='Exim Msg ID to forward',
    )
    require.add_argument(
        '--fr', '-f', metavar='user@domain.com', nargs='+',
        help='Sender address to get a sample of',
    )
    require.add_argument(
        '--re', '-r', metavar='user@domain.com', nargs='+',
        help='Recipient address to get a sample of',
    )
    parsed.add_argument(
        '--subject', '-s', metavar='Spam Example for verizon',
        help='Override subject (default:\"Spam Example for %s\")' % hostname(),
    )
    parsed.add_argument(
        '--quiet', '-q', action='store_true', help='Silence Output'
    )
    parsed.add_argument(
        '--bleach', '-b', action='store_true', help='Bleach Output'
    )
    parsed.add_argument('--debug', '-d', action='store_true')
    # fmt: on
    args = parsed.parse_args()
    if args.bleach:
        red = green = lambda x: x
    else:
        red = rads.color.red
        green = rads.color.green
    return args, red, green


def main():
    tot = 0
    tmpf = TemporaryFile()
    args, red, green = arg_init()
    if not args.subject:
        subject = 'Spam Example for %s' % hostname().split('.')[0]
    else:
        subject = args.subject
    if args.debug:
        print(args)
    if args.fr:
        for addr_str in args.fr:
            tot += address_sample(addr_str, tmpf)
    if args.re:
        for regex_str in args.re:
            tot += address_sample(regex_str, tmpf, regexp=True)
    if args.id:
        add_to([args.id], tmpf)
        tot += 1
    if tot >= 1:
        send_message(subject, tmpf, args.quiet, tot, green)
    else:
        print(red("No Messages found"))


def address_sample(email, tmpf, regexp=False, count=1):
    '''Collect a selection of messages to be updated'''
    if regexp:
        cmd = ['exiqgrep', '-ir', email]
    else:
        cmd = ['exiqgrep', '-if', email]
    results = list(subprocess.check_output(cmd, text=True))
    lngth = len(results)
    pos = int((random() * lngth) - 1)
    if count > lngth and count != 1:
        samp_results = results
    if pos < (lngth - count - 1) and lngth >= pos + count:
        samp_results = results[pos : pos + count]
    elif count > pos:
        samp_results = results[0:count]
    else:
        samp_results = results[pos - count : pos]

    add_to(samp_results, tmpf)

    return len(samp_results)


def exim(*args: str) -> str:
    cmd = ['exim']
    cmd.extend(args)
    return subprocess.check_output(cmd, text=True)


def add_to(results: list[str], tmpf):
    '''add results to temp file'''
    div = '{}{}'.format(''.join(['='] * 40), '\n')
    msg = [''] * 3
    for ids in results:
        m_id = ids.strip(' \t\n\r ').replace(" ", "")
        msg[0] = exim('-Mvl', m_id)
        msg[1] = exim('-Mvh', m_id)
        msg[2] = exim('-Mvb', m_id)
        tmpf.write(f'{div}Example message {ids}')
        for content in msg:
            tmpf.write(f'{div}{{{{{{\n{content}\n}}}}}}\n')


def send_message(subject, tmpf, quiet, tot, green):
    '''send email to spamtrends'''
    tmpf.seek(0)
    msg = MIMEText(tmpf.read())
    msg['Subject'] = subject
    msg['From'] = FROM_ADDR
    msg['To'] = TARGET_ADDR
    conn = smtplib.SMTP('localhost')
    conn.sendmail(FROM_ADDR, TARGET_ADDR, msg.as_string())
    conn.quit()
    if not quiet:
        print(green(f"{tot} Sample(s) Sent"))


if __name__ == "__main__":
    main()

Zerion Mini Shell 1.0