Enhance a Python script to facilitate detection of potential cyber attacks using "execution" techniques. It works by scanning the Windows event logs for specific signs of malicious "execution" activity according to MITRE ATT&CK. The script uses the subprocess module to run PowerShell commands from Python. Events related to PowerShell usage, malicious scripts, cmd interpreter abuse and similar suspicious activities are scanned and detected. The script finds too many events, there should be fewer of them. Suggest an improved and more accurate version of the script. Avoid errors in Python code. Write only Python code in your answer.

import subprocess
import json

def powershell_command(command):
	process = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
	return process.stdout

def scan_event_logs():
	events_to_check = [
		{"log": "Microsoft-Windows-PowerShell/Operational", "id": [400, 4103, 4104]},
		{"log": "Security", "id": [4688]},
		{"log": "System", "id": [1, 6013]}
	]

	detected_threats = []
	for event in events_to_check:
		log_name = event['log']
		for event_id in event['id']:
			command = "Get-WinEvent -FilterHashtable @{" \
				+ f"logname='{log_name}'; id={event_id}" \
				+ "} | Select-Object TimeCreated, Id, Message | ConvertTo-Json"
			output = powershell_command(command)
			if output:
				try:
					events = json.loads(output)
					if type(events) is dict:
						events = [events]
					for event in events:
						detected_threats.append({
							'Time': event["TimeCreated"],
							'EventID': event["Id"],
							'Details': event["Message"]
						})
				except json.JSONDecodeError as e:
					print(f"Error decoding JSON!")
	return detected_threats

threats_found = scan_event_logs()
if threats_found:
	print("Found markers of potential attacks: " + str(len(threats_found)))
	write_to_file = open('threats.txt', 'w')
	for threat in threats_found:
		print(f"Time: {threat['Time']}, Event ID: {threat['EventID']}, Info: {threat['Details']}", file=write_to_file)
else:
	print("No events found.")

You can use information below about execution tactic (TA0002) from MITRE ATT&CK website:

T1651 Cloud Administration Command
Adversaries may abuse cloud management services to execute commands within virtual machines. Resources such as AWS Systems Manager, Azure RunCommand, and Runbooks allow users to remotely run scripts in virtual machines by leveraging installed virtual machine agents. [1][2]

If an adversary gains administrative access to a cloud environment, they may be able to abuse cloud management services to execute commands in the environment’s virtual machines. Additionally, an adversary that compromises a service provider or delegated administrator account may similarly be able to leverage a Trusted Relationship to execute commands in connected virtual machines.[3]

Procedure Examples
ID	Name	Description
S0677	AADInternals	
AADInternals can execute commands on Azure virtual machines using the VM agent.[4]

G0016	APT29	
APT29 has used Azure Run Command and Azure Admin-on-Behalf-of (AOBO) to execute code on virtual machines.[3]

S1091	Pacu	
Pacu can run commands on EC2 instances using AWS Systems Manager Run Command.[5]

Mitigations
ID	Mitigation	Description
M1026	Privileged Account Management	
Limit the number of cloud accounts with permissions to remotely execute commands on virtual machines, and ensure that these are not used for day-to-day operations. In Azure, limit the number of accounts with the roles Azure Virtual Machine Contributer and above, and consider using temporary Just-in-Time (JIT) roles to avoid permanently assigning privileged access to virtual machines.[6]

Detection
ID	Data Source	Data Component	Detects
DS0017	Command	Command Execution	
Monitor commands and scripts executed on virtual machines. In Azure, usage of Azure RunCommand can be identified via the Azure Activity Logs, and additional details on the result of executed jobs are available in the C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows directory on Windows virtual machines.[6]

DS0009	Process	Process Creation	
Monitor virtual machines for the creation of processes associated with cloud virtual machine agents. In Windows-based Azure machines, monitor for the WindowsAzureGuestAgent.exe process.[6]

DS0012	Script	Script Execution	
Monitor commands and scripts executed on virtual machines. In Azure, usage of Azure RunCommand can be identified via the Azure Activity Logs, and additional details on the result of executed jobs are available in the C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows directory on Windows virtual machines.[6]

T1059.001 Command and Scripting Interpreter: PowerShell
Adversaries may abuse PowerShell commands and scripts for execution. PowerShell is a powerful interactive command-line interface and scripting environment included in the Windows operating system.[1] Adversaries can use PowerShell to perform a number of actions, including discovery of information and execution of code. Examples include the Start-Process cmdlet which can be used to run an executable and the Invoke-Command cmdlet which runs a command locally or on a remote computer (though administrator permissions are required to use PowerShell to connect to remote systems).

PowerShell may also be used to download and run executables from the Internet, which can be executed from disk or in memory without touching disk.

A number of PowerShell-based offensive testing tools are available, including Empire, PowerSploit, PoshC2, and PSAttack.[2]

PowerShell commands/scripts can also be executed without directly invoking the powershell.exe binary through interfaces to PowerShell's underlying System.Management.Automation assembly DLL exposed through the .NET framework and Windows Common Language Interface (CLI).[3][4][5]

T1059.003 Command and Scripting Interpreter: Windows Command Shell
Adversaries may abuse the Windows command shell for execution. The Windows command shell (cmd) is the primary command prompt on Windows systems. The Windows command prompt can be used to control almost any aspect of a system, with various permission levels required for different subsets of commands. The command prompt can be invoked remotely via Remote Services such as SSH.[1]

Batch files (ex: .bat or .cmd) also provide the shell with a list of sequential commands to run, as well as normal scripting operations such as conditionals and loops. Common uses of batch files include long or repetitive tasks, or the need to run the same set of commands on multiple systems.

Adversaries may leverage cmd to execute various commands and payloads. Common uses include cmd to execute a single command, or abusing cmd interactively with input and output forwarded over a command and control channel.

T1059.005 Command and Scripting Interpreter: Visual Basic
Adversaries may abuse Visual Basic (VB) for execution. VB is a programming language created by Microsoft with interoperability with many Windows technologies such as Component Object Model and the Native API through the Windows API. Although tagged as legacy with no planned future evolutions, VB is integrated and supported in the .NET Framework and cross-platform .NET Core.[1][2]

Derivative languages based on VB have also been created, such as Visual Basic for Applications (VBA) and VBScript. VBA is an event-driven programming language built into Microsoft Office, as well as several third-party applications.[3][4] VBA enables documents to contain macros used to automate the execution of tasks and other functionality on the host. VBScript is a default scripting language on Windows hosts and can also be used in place of JavaScript on HTML Application (HTA) webpages served to Internet Explorer (though most modern browsers do not come with VBScript support).[5]

Adversaries may use VB payloads to execute malicious commands. Common malicious usage includes automating execution of behaviors with VBScript or embedding VBA content into Spearphishing Attachment payloads (which may also involve Mark-of-the-Web Bypass to enable execution).[6]

T1059.006 Command and Scripting Interpreter: Python
Adversaries may abuse Python commands and scripts for execution. Python is a very popular scripting/programming language, with capabilities to perform many functions. Python can be executed interactively from the command-line (via the python.exe interpreter) or via scripts (.py) that can be written and distributed to different systems. Python code can also be compiled into binary executables.[1]

Python comes with many built-in packages to interact with the underlying system, such as file operations and device I/O. Adversaries can use these libraries to download and execute commands or other scripts as well as perform various malicious behaviors.

T1059.007 Command and Scripting Interpreter: JavaScript
Adversaries may abuse various implementations of JavaScript for execution. JavaScript (JS) is a platform-independent scripting language (compiled just-in-time at runtime) commonly associated with scripts in webpages, though JS can be executed in runtime environments outside the browser.[1]

JScript is the Microsoft implementation of the same scripting standard. JScript is interpreted via the Windows Script engine and thus integrated with many components of Windows such as the Component Object Model and Internet Explorer HTML Application (HTA) pages.[2][3][4]

JavaScript for Automation (JXA) is a macOS scripting language based on JavaScript, included as part of Apple’s Open Scripting Architecture (OSA), that was introduced in OSX 10.10. Apple’s OSA provides scripting capabilities to control applications, interface with the operating system, and bridge access into the rest of Apple’s internal APIs. As of OSX 10.10, OSA only supports two languages, JXA and AppleScript. Scripts can be executed via the command line utility osascript, they can be compiled into applications or script files via osacompile, and they can be compiled and executed in memory of other programs by leveraging the OSAKit Framework.[5][6][7][8][9]

Adversaries may abuse various implementations of JavaScript to execute various behaviors. Common uses include hosting malicious scripts on websites as part of a Drive-by Compromise or downloading and executing these script files as secondary payloads. Since these payloads are text-based, it is also very common for adversaries to obfuscate their content as part of Obfuscated Files or Information.

T1053 Scheduled Task/Job
Adversaries may abuse task scheduling functionality to facilitate initial or recurring execution of malicious code. Utilities exist within all major operating systems to schedule programs or scripts to be executed at a specified date and time. A task can also be scheduled on a remote system, provided the proper authentication is met (ex: RPC and file and printer sharing in Windows environments). Scheduling a task on a remote system typically may require being a member of an admin or otherwise privileged group on the remote system.[1]

Adversaries may use task scheduling to execute programs at system startup or on a scheduled basis for persistence. These mechanisms can also be abused to run a process under the context of a specified account (such as one with elevated permissions/privileges). Similar to System Binary Proxy Execution, adversaries have also abused task scheduling to potentially mask one-time execution under a trusted system process.[2]

T1053.005 Scheduled Task/Job: Scheduled Task
Adversaries may abuse the Windows Task Scheduler to perform task scheduling for initial or recurring execution of malicious code. There are multiple ways to access the Task Scheduler in Windows. The schtasks utility can be run directly on the command line, or the Task Scheduler can be opened through the GUI within the Administrator Tools section of the Control Panel. In some cases, adversaries have used a .NET wrapper for the Windows Task Scheduler, and alternatively, adversaries have used the Windows netapi32 library to create a scheduled task.

The deprecated at utility could also be abused by adversaries (ex: At), though at.exe can not access tasks created with schtasks or the Control Panel.

An adversary may use Windows Task Scheduler to execute programs at system startup or on a scheduled basis for persistence. The Windows Task Scheduler can also be abused to conduct remote Execution as part of Lateral Movement and/or to run a process under the context of a specified account (such as SYSTEM). Similar to System Binary Proxy Execution, adversaries have also abused the Windows Task Scheduler to potentially mask one-time execution under signed/trusted system processes.[1]

Adversaries may also create "hidden" scheduled tasks (i.e. Hide Artifacts) that may not be visible to defender tools and manual queries used to enumerate tasks. Specifically, an adversary may hide a task from schtasks /query and the Task Scheduler by deleting the associated Security Descriptor (SD) registry value (where deletion of this value must be completed using SYSTEM permissions).[2][3] Adversaries may also employ alternate methods to hide tasks, such as altering the metadata (e.g., Index value) within associated registry keys.[4]

T1204 User Execution
An adversary may rely upon specific actions by a user in order to gain execution. Users may be subjected to social engineering to get them to execute malicious code by, for example, opening a malicious document file or link. These user actions will typically be observed as follow-on behavior from forms of Phishing.

While User Execution frequently occurs shortly after Initial Access it may occur at other phases of an intrusion, such as when an adversary places a file in a shared directory or on a user's desktop hoping that a user will click on it. This activity may also be seen shortly after Internal Spearphishing.

Adversaries may also deceive users into performing actions such as enabling Remote Access Software, allowing direct control of the system to the adversary; running malicious JavaScript in their browser, allowing adversaries to Steal Web Session Cookies; or downloading and executing malware for User Execution.[1][2]

For example, tech support scams can be facilitated through Phishing, vishing, or various forms of user interaction. Adversaries can use a combination of these methods, such as spoofing and promoting toll-free numbers or call centers that are used to direct victims to malicious websites, to deliver and execute payloads containing malware or Remote Access Software.[3]

T1204.001 User Execution: Malicious Link
An adversary may rely upon a user clicking a malicious link in order to gain execution. Users may be subjected to social engineering to get them to click on a link that will lead to code execution. This user action will typically be observed as follow-on behavior from Spearphishing Link. Clicking on a link may also lead to other execution techniques such as exploitation of a browser or application vulnerability via Exploitation for Client Execution. Links may also lead users to download files that require execution via Malicious File.

T1204.002 User Execution: Malicious File
An adversary may rely upon a user opening a malicious file in order to gain execution. Users may be subjected to social engineering to get them to open a file that will lead to code execution. This user action will typically be observed as follow-on behavior from Spearphishing Attachment. Adversaries may use several types of files that require a user to execute them, including .doc, .pdf, .xls, .rtf, .scr, .exe, .lnk, .pif, and .cpl.

Adversaries may employ various forms of Masquerading and Obfuscated Files or Information to increase the likelihood that a user will open and successfully execute a malicious file. These methods may include using a familiar naming convention and/or password protecting the file and supplying instructions to a user on how to open it.[1]

While Malicious File frequently occurs shortly after Initial Access it may occur at other phases of an intrusion, such as when an adversary places a file in a shared directory or on a user's desktop hoping that a user will click on it. This activity may also be seen shortly after Internal Spearphishing.