4.11.2 Identify the basics of scripting Part 2

Introduction 

Windows offers scripting environments like PowerShell for complex tasks, VBScript for legacy functions, and Batch Files for simple tasks. JavaScript and Python are cross-platform tools: JavaScript automates web tasks across systems, while Python handles everything from automation to app development. In this part, we'll explore how these languages can be used for various tasks. 

Windows Scripting Environments 

Windows supports several scripting environments, each with unique functionality and use cases. The three most commonly used environments are PowerShell, VBScript, and Batch Files.

Windows PowerShell 

  • PowerShell is a powerful scripting language with hundreds of built-in modules known as cmdlets that allow access to Windows components and features, including Active Directory. 

  • Cmdlet Naming Convention: PowerShell cmdlets follow a Verb-Noun format, such as: 

    • Write-Host - sends output to the terminal. 

    • Read-Host - prompts for user input. 

    • PowerShell ISE (Integrated Scripting Environment): Microsoft provides this environment to support fast script development. PowerShell scripts use the .PS1 file extension. 

Batch Files 

  • Batch Files are scripts written for the basic CMD interpreter in Windows. 

  • File Extension: Batch files use the .BAT extension. 

  • Purpose: Often used for simple automation tasks or legacy support, batch files can contain basic commands for file management, network connections, and system configuration. 

VBScript 

  • VBScript (Visual Basic Script) is based on Microsoft’s Visual Basic language. It is an older scripting tool than PowerShell but is still used for certain Windows tasks. 

  • File Extension: VBScript files use the .VBS extension. 

  • Execution Methods: 

    • wscript.exe - runs VBScript and displays output in a window or dialog box. 

    • cscript.exe - executes VBScript in a command prompt, which can be useful for scripts that require command-line interaction. 

  • Usage: While PowerShell is the standard for Windows automation, VBScript is still relevant for maintaining legacy scripts

Each scripting environment in Windows has specific use cases, with PowerShell being the most powerful and flexible for modern Windows automation, while VBScript and Batch Files provide essential support for legacy and straightforward tasks. 

Platform-Independent Scripting Languages: JavaScript and Python 

While Bash and PowerShell/VBScript are tied closely to Linux and Windows systems, other scripting and programming languages work across various platforms. Two popular platform-independent languages are JavaScript and Python

JavaScript 

  • Purpose: JavaScript is a versatile scripting language primarily used for interactive content on websites and web applications. 

  • Execution: JavaScript runs directly within web browsers and web servers, where it’s interpreted automatically. Code can be embedded in HTML files or linked as separate .JS files.

  • Automation Support: 

    • On Windows, JavaScript can be executed using Windows Script Host tools like wscript.exe and cscript.exe. 

    • On macOS, JavaScript works for system automation alongside AppleScript in a format known as JavaScript for Automation (JXA)

  • Python 

  • Purpose: Python is a general-purpose language, ideal for both automation scripting and creating full software applications. 

  • Execution: Python code can run in two ways: 

    • Interpreted Mode: Python scripts (.PY files) can run directly through an interpreter. 

    • Compiled Mode: Python can also compile code into binary executables for broader software distribution.

  • Python Versions: 

    • Python 2 and Python 3 are the two main versions, though Python 2 is end-of-life (EOL) as of 2020, and new code should use Python 3

    • Interpreters: Common interpreters include CPython (the standard interpreter) and PyPy (an alternative with faster performance). In Windows, CPython can be accessed via two interpreters: 

      • python.exe: Console-based interpreter for terminal work. 

      • pythonw.exe: Windowed interpreter, usually for graphical apps. 

  • Development Environment: Python has an official Integrated Development and Learning Environment (IDLE), which provides: 

    • A script editor and terminal interface. 

    • A debugger for stepping through code and examining variable values.

These languages offer powerful tools across multiple operating systems, allowing developers to create flexible, cross-platform scripts and applications for a wide range of tasks and projects. 

Use Cases for Scripting 

Scripting automates repetitive tasks, saving time and reducing errors by executing series of instructions automatically. Below are some of the key use cases for scripting across different environments. 

Basic Automation 

Scripting enables basic automation, performing routine tasks without manual input: 

  • OS Built-in Commands: Local script environments like Bash (Linux) and PowerShell (Windows) use native commands. 

  • API Calls for Complex Automation: General-purpose languages, such as Python, can interact with OS features using APIs. For example, Python’s os module allows file management and process control across systems. Additional modules, like mod_python, support web server automation. 

Multi-Platform Automation 

Scripts can also interact across platforms. For instance: Python scripts can call Bash and PowerShell scripts to control tasks on both Linux and Windows systems simultaneously. 

 

Common Scripting Tasks 

Restarting Machines

Scripts simplify the restart process, often needed after updates: 

  • PowerShell (Windows): Restart-Computer -Force (uses -Force to override warnings). 

  • Bash (Linux): shutdown -r restarts the system, though Linux typically requires fewer reboots than Windows. 

Network Drive Mapping

Scripts handle network drive assignments efficiently, especially with error handling-which prevents the script from failing unexpectedly, ensuring smooth execution:  

  • PowerShell (Windows): Uses New-PSDrive with an error check to remove pre-existing mappings: 

powershell 

Copy code 

If (Test-Path L:) { Get-PSDrive L | Remove-PSDrive } 
New-PSDrive -Name "L" -Persist -PSProvider FileSystem -Root "\\MS10\LABFILES
 

  • Linux: Mounts drives within the root file system with commands like mount and umount- to unmount, instead of using network drive mapping. 

Application Installation 

In addition to simply installing programs, scripts can install applications automatically in silent mode.  The /qn’ option is often used—particularly with the ‘msiexec’ command to perform a silent installation of an MSI package.  When used, it means “no user interface” will be displayed during the installation process.  This is useful for automated deployments where you do not want any prompts or dialogs to interrupt the installation—this /qn option is specific to the ‘msiexec’ command which is for installing MSI packages on Windows.   

Linux, has its own options for silent or unattended installations, for example you can use   ‘-y’ to automatically answer “yes” to prompts, allowing for a silent installation.: 

  • Windows Batch and PowerShell: here are some of the most common script commands used to automate application installations on Windows.  These commands can be combined and customized to fit your specific needs: 

    • EXE Installers: C:\Path\setup.exe /S /desktopicon=yes 

    • MSI Installers: msiexec /i C:\Path\install.msi 

    • PowerShell Command: Start-Process for additional control. 

  • Linux: With Linux, automating package management or application installation is typically handled by different commands depending on the distro: 

    • 'apt’ command—for Debian-based systems or  

    • ‘yum’ command—for Red Hat-based systems in Bash 

System Updates 

Updating systems automatically keeps software secure and up to date: 

  • Windows Batch and PowerShell: Use wusa.exe in batch or the PSWindowsUpdate module in PowerShell. 

  • Linux Bash: Executes apt-get -y or yum -y to install updates without user confirmation. 

Automated Backups 

Scripts can automate file backups: 

  • Windows: Uses robocopy in Batch or PowerShell to transfer files. 

  • Linux: Combines file-copy commands with cron jobs to schedule backups. 

Data Gathering and Logging 

Scripts can gather system information and create logs for analysis. Example: 

  • PowerShell (Windows): Retrieve data with Get-NetAdapter and Get-WinEvent. The first command retrieves basic properties of network adapters, and the latter retrieves events from the event logs.   Additional filters can be applied using Where-Object and Select-Object. 

  • Bash (Linux): Uses commands like ps, grep, awk, and cut for data manipulation, redirecting the output to a log file.  

 

The ‘ps’ command displays information about the currently running processes (e.g., CPU usage, memory usage); ‘grep’ searches and filters text based on patterns—often used to filter the output of other commands; ‘awk’ is a powerful text processing tool command—it can be used to extract and manipulate data from text files; and ‘cut’ command extracts sections from each line of input.   
 
These commands are often combined in scripts to perform complex data processing tasks. 

Example: 

bash 

Copy code 

printf "Processes run by $1 on $(date +%F) at $(date +%T) \n" >> "ps-$1.log" 
ps -ef | grep "$1" | cut "$((${#1}+9))-" >> "ps-$1.log" 

This example logs the processes run by a specified user, including timestamps. 

Scripting automates essential tasks across platforms, whether handling reboots, mapping drives, managing installations, performing updates, or gathering data. By using scripts, systems become more efficient and can run reliably with less manual intervention. 

Deployment Risks and Best Practices for Scripting 

Deploying scripts, while necessary for automation and efficiency, can introduce vulnerabilities. Following best practices helps mitigate risks, including malware, system-setting errors, and resource mishandling. 

Malware Risks 

Scripts, if not secured, can be vulnerable to malware and unauthorized modifications: 

  • Expanded Attack Surface: Enabling non-default interpreters, such as PowerShell, can create opportunities for fileless malware attacks. 

  • Script Modification: Threat actors may alter scripts to act as Trojans, turning the script into malware. 

  • Unprotected Inputs: Scripts that open network ports or user input forms must handle data securely; otherwise, they risk exploitation. 

Mitigation Steps: 

  • Access Control and Version Management: Secure source code with controlled access and version history to prevent unauthorized modifications. 

  • Vulnerability Scanning and Testing: Run code scans and tests for vulnerabilities before deployment. 

  • Principle of Least Privilege: Limit script privileges to the minimum necessary to complete tasks.

Risks from Unintentional System Changes 

Scripts may unintentionally alter system settings, creating security or functionality issues: 

  • Accidental Denial of Service (DoS): For instance, a script may unintentionally power off rather than restart a system or block remote access by modifying firewall settings. 

  • Security Compromises: Some scripts may require disabling security features to execute successfully, which can create unsafe configurations. 

Best Practices: 

  • Testing in Development Environments: Test all scripts in isolated environments to prevent unintended changes on live systems. 

  • Configuration Baselines: Document any required system changes in updated configuration baselines and monitor these adjustments. 

System Crashes from Resource Mismanagement 

Improper resource management in scripts can lead to unintended denial of service or crashes: 

  • Excessive Disk Usage: Scripts that create unnecessary log or temporary files may fill up disk space. 

  • Faulty Loops: Non-terminating loops can cause scripts to hang. 

  • Faulty API Calls: Incorrect calls to other processes (e.g., a browser) can lead to crashes. 

Mitigation Steps: 

  • Rigorous Testing: Check scripts for errors in resource handling to prevent overuse of system resources. 

  • Continuous Monitoring: Monitor script performance after deployment to detect any issues missed during testing. 

 

Implementing secure and tested scripting practices helps reduce risks, ensuring scripts perform as intended without compromising system security or functionality. 

Summary 

Scripting is an incredible tool that empowers you to automate tasks, boost productivity, and manage systems with ease. By understanding best practices in deployment, you can confidently create and run scripts that are both efficient and secure. With careful testing, access controls, and attention to resource handling, you’ll prevent common issues like malware risks, accidental changes, and system crashes. Embrace scripting as a powerful way to streamline processes, knowing that each step you take to secure and optimize your scripts enhances your skills and safeguards your systems!