Basics of Scripting


Types of Coding Languages

  • A shell scripting language uses commands that are specific to an operating system
  • A general-purpose scripting language uses statements and modules that are independent of the operating system
    • executed by an interpreter
    • interpreter implements the language for a particular OS
  • A programming language is used to compile an executable file that can be installed to an OS and run as an app

Shell Scripts

  • Linux shell script uses the .sh extension by convention
  • Every shell script starts with a shebang line that designates which interpreter to use
    • E.g., Bash or Ksh
  • Each statement comprising the actions that the script will perform
    • typically on separate lines

Example

Script that executes in Bash interpreter to use the echo command to write “Hello World” to the terminal:

#!/bin/bash
echo 'Hello World'
  • In Linux, script file must have the execute permission to run
  • execute a script from the working directory with ./ preceding the file name

Basic Script Constructs

  • Most scripting languages share similar syntax

Comments

  • add comments in code to assist with maintaining it
    • E.g., #

Variables

variable is a label for some value that can change as the script executes.

  • Variables are usually declared, defined as a particular data type, and given an initial value
  • An argument or parameter is a variable that is passed to the script when it is executed
    • In Bash, the values $1$2 , and so on are used to refer to arguments by position

Branches and Loops

  • two main types of conditional execution:
    • branches
    • loops

Branches

branch is an instruction to execute a different sequence of instructions based on the outcome of some logical test.

Loops

loop allows a statement block to be repeated based on some type of condition.

  • For loops
    • for determinate number of loops
  • while and until statements
    • for indeterminate number of loops

Operators

A logical test is one that resolves to a TRUE or FALSE value.

  • basic comparison and logical operators:
Symbol NotationSwitch NotationUsage
==-eqIs equal to (returns TRUE if both conditions are the same)
!=-neIs not equal to (returns FALSE if both conditions are the same)
<-ltIs less than
>-gtIs greater than
-leIs less than or equal to
>=-geIs greater than or equal to
&&ANDIf both conditions are TRUE, then the whole statement is TRUE
||ORIf either condition is TRUE, then the whole statement is TRUE

Windows Scripts

  • Windows supports several distinct shell coding environments
    •  three common ones:
      • PowerShell
      • Visual Basic Script
      • CMD interpreter

PowerShell

Windows PowerShell (PS) combines a script language with hundreds of prebuilt modules called cmdlets that can access and change most components and features of Windows and Active Directory.

  • Cmdlets use a Verb-Noun naming convention
    • E.g., Write-Host sends output to the terminal
    • Read-Host prompts for user input
  • Windows PowerShell Integrated Scripting Environment (ISE) is used for rapid development
  • uses  .PS1 extension

VBScript

  • based on Visual Basic programming language
  • predates PowerShell
  • use .VBS extension
  • executed by wscript.exe interpreter
    • displays any output from the script in a desktop window or dialog
  • can also be run with cscript.exe to show output in a command prompt

Batch Files

  • shell script written for the Windows CMD interpreter
  • uses .BAT extension

Javascript and Python

  • Bash and PowerShell/VBScript are tied to Linux and Windows OS
  • the following are platform-independent

JavaScript

JavaScript is a scripting language that is designed to implement interactive web-based content and web apps.

  • most web servers and browsers are configured with a JavaScript interpreter
    • means js can be executed automatically by placing it in the HTML code for a web page
  • use .js extension
  • wscript.exe and cscript.exe support JavaScript
  • macOS Automator supports JS (and AppleScript)
    • called JavaScript for Automation (JXA)

Python

Python is a general-purpose scripting and programming language that can be used to develop both automation scripts and software apps.

  • can run via interpreter or compiled as binary executable
  • multiple interpreters
    • CPython
      • simplest environment for Windows
    • PyPy
  • use .py extention

CPython

  • has a console interpreter (python.exe) and windowed interpreter (pythonw.exe)
  • .pyw extension for pythonw.exe

Info

2 major versions of Python

  • version 2 and 3
  • both can be installed at the same time
  • in Linux, using python executes script as version 2 and python3 executes v3
  • Python 2 is end of life

Use Cases for Scripting

  • basic automation
    • OS scripting languages can use the built-in commands
    • general-purpose languages have to call them from an API
      • API calls are implemented as modules

Restarting Machines

  • Windows: Restart-Computer -Force
  • Linux: shutdown -r

Remapping Network Drives

  • Windows batch file: net use
  • Windows PowerShell: New-PSDrive
  • requires error handling to ensure drive letter is not already in use
    • use a conditional
  • Windows only concept
  • in Linux, file system is made available by mounting
    • mount and unmount commands

Installation of Applications

  • Windows setup file can be executed in silent mode with command switches
  • installers are implemented in .exe or .msi packages
    • EXE in batch file: C:\User\Downloads\setup.exe /S /desktopicon=yes
    • MSI installer with msiexec command: msiexec C:\User\Downloads\install.msi /qn
    • can also run these directly in PowerShell script
    • Start-Process cmdlet gives you more options for controlling the installation and handling errors
  • Linux scripts are used to compile apps from source code
    • can also automate APT or YUM package managers

Initiating Updates

  • Windows: wusa.exe process called from batch file
  • PowerShell: PSWindowsUpdate module contains cmdlets for managing update process
  • Linux: call apt-get or apt or yum from Bash script
    • -y flag suppress confirmation messages

Automated Backups

  • at command prompt, simple backups can be performed using file-copy tools (robocopy)
  • Windows script: call functions of a backup utility and schedule with Windows Task Scheduler
  • Linux: call functions of backup utility and schedule with cron jobs

Gathering Info/Data

  • PowerShell: many Get cmdlets for getting data from Windows subsystem
    • Get-NetAdapter for network adapter properties
    • Get-WinEvent for log data
    • can pipe results into Where-Object and Select-Object cmdlets to apply filters
  • Bash:
    • gather data from output of commands like ps or df
    • filter using grep
    • format using awk or cut
    • redirect output to a file

Scripting Best Practices and Considerations

  • deploying any type of code comes with risk of vulnerabilities

Malware Risks

  • ways a script can be compromised:
    • if interpreter is not a default feature, enabling it expands the attack surface
      • PowerShell is used to craft fileless malware
    • threat actor could modify the source code (script)
    • script could open a network port or expose input forms
  • mitigate these by
    • access control
    • version controls
    • scan and test code for vulnerabilities and errors
    • run with minimum privileges

Inadvertent System-Settings Changes

  • risk from non-malicious or inadvertent threat
    • script performs unforeseen or unexpected system change

Browser or System Crashes Due to Mishandling of Resources

  • script can cause accidental DoS by mishandling resources
  • programming languages like C/C++ can easily manipulate system RAM
  • scripting languages are considered safe in respect to system memory handling
  • script mistakes can still mishandle computer or storage resources
    • E.g.,
    • creating files that deplete disk storage resources (log or temp files)
    • using faulty loop code that does not terminate and causes script to hang
    • making a faulty API call to some other process that causes a crash
  • test every scrip before deploying
  • monitor script execution