Fix script execution on windows #4

Merged
nserrano merged 1 commits from windows-fixes into ogagent-macos 2024-07-19 10:45:19 +02:00
3 changed files with 17 additions and 4 deletions

0
src/OGAgentUser.py Normal file → Executable file
View File

View File

@ -1 +1 @@
1.3.2 1.3.3

View File

@ -149,6 +149,7 @@ class OpenGnSysWorker(ServerWorker):
break break
# Raise error after timeout # Raise error after timeout
if not self.interface: if not self.interface:
## UnboundLocalError: cannot access local variable 'e' where it is not associated with a value
raise e raise e
# Loop to send initialization message # Loop to send initialization message
@ -332,11 +333,23 @@ class OpenGnSysWorker(ServerWorker):
:return: JSON object {"op": "launched"} :return: JSON object {"op": "launched"}
""" """
logger.debug('Processing script request') logger.debug('Processing script request')
# Decoding script (Windows scripts need a subprocess call per line) # Decoding script
script = urllib.parse.unquote(base64.b64decode(post_params.get('script')).decode('utf-8')) script = urllib.parse.unquote(base64.b64decode(post_params.get('script')).decode('utf-8'))
logger.debug('received script {}'.format(script))
if operations.os_type == 'Windows': if operations.os_type == 'Windows':
script = 'import subprocess; {0}'.format( ## for windows, we turn the script into utf16le, then to b64 again, and feed the blob to powershell
';'.join(['subprocess.check_output({0},shell=True)'.format(repr(c)) for c in script.split('\n')])) u16 = script.encode ('utf-16le') ## utf16
b64 = base64.b64encode (u16).decode ('utf-8') ## b64 (which returns bytes, so we need an additional decode(utf8))
script = """
import os
import tempfile
import subprocess
cp = subprocess.run ("powershell -WindowStyle Hidden -EncodedCommand {}", capture_output=True)
subprocs_log = os.path.join (tempfile.gettempdir(), 'opengnsys-subprocs.log')
with open (subprocs_log, 'ab') as fd: ## TODO improve this logging
fd.write (cp.stdout)
fd.write (cp.stderr)
""".format (b64)
else: else:
script = 'import subprocess; subprocess.check_output("""{0}""",shell=True)'.format(script) script = 'import subprocess; subprocess.check_output("""{0}""",shell=True)'.format(script)
# Executing script. # Executing script.