#!/usr/bin/env python3
import base64
import sys

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PASS = "Moli@5404"


def connect(host, user):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(host, username=user, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
    return c


def run(c, cmd, sudo=False):
    if sudo:
        b64 = base64.b64encode(cmd.encode()).decode()
        full = f"echo {PASS!r} | sudo -S -p '' bash -c 'echo {b64} | base64 -d | bash'"
    else:
        full = cmd
    _, o, e = c.exec_command(full, timeout=60, get_pty=True)
    print((o.read() + e.read()).decode("utf-8", "replace"))


app = connect("192.168.10.162", "morteza")
run(
    app,
    "ls -la /home/morteza/torbatyar/frontend/public/78473978.txt; "
    "printf '' > /home/morteza/torbatyar/frontend/public/78473978.txt; "
    "ls -la /home/morteza/torbatyar/frontend/public/78473978.txt; "
    "curl -sS -m 10 -o /dev/null -w 'fe_file=%{http_code}\\n' http://127.0.0.1:3000/78473978.txt",
)
app.close()

ngx = connect("192.168.10.156", "torbatyaruser")
run(ngx, "grep -n 78473978 /etc/nginx/conf.d/torbatyar.ir.conf")
run(ngx, "curl -sS -m 10 -o /dev/null -w http_file=%{http_code} -H 'Host: torbatyar.ir' http://192.168.10.156/78473978.txt; echo")
run(
    ngx,
    "curl -sk -m 10 -o /dev/null -w https_file=%{http_code} --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/78473978.txt; echo",
)
run(
    ngx,
    "curl -sk -m 15 --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/ | tr '\\n' ' ' | grep -oE '<title>[^<]+</title>|name=\"enamad\" content=\"[^\"]+\"'",
)
ngx.close()
