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
.shextension 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
echocommand 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.,
#
- E.g.,
Variables
A 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
- In Bash, the values
Branches and Loops
- two main types of conditional execution:
- branches
- loops
Branches
A branch is an instruction to execute a different sequence of instructions based on the outcome of some logical test.
Loops
A 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 Notation | Switch Notation | Usage |
|---|---|---|
| == | -eq | Is equal to (returns TRUE if both conditions are the same) |
| != | -ne | Is not equal to (returns FALSE if both conditions are the same) |
| < | -lt | Is less than |
| > | -gt | Is greater than |
| ⇐ | -le | Is less than or equal to |
| >= | -ge | Is greater than or equal to |
| && | AND | If both conditions are TRUE, then the whole statement is TRUE |
| || | OR | If 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
- three common ones:
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-Hostsends output to the terminal Read-Hostprompts for user input
- E.g.,
- Windows PowerShell Integrated Scripting Environment (ISE) is used for rapid development
- uses
.PS1extension
VBScript
- based on Visual Basic programming language
- predates PowerShell
- use
.VBSextension - executed by
wscript.exeinterpreter- displays any output from the script in a desktop window or dialog
- can also be run with
cscript.exeto show output in a command prompt
Batch Files
- shell script written for the Windows CMD interpreter
- uses
.BATextension
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
.jsextension wscript.exeandcscript.exesupport 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
- CPython
- use
.pyextention
CPython
- has a console interpreter (
python.exe) and windowed interpreter (pythonw.exe) .pywextension forpythonw.exe
Info
2 major versions of Python
- version 2 and 3
- both can be installed at the same time
- in Linux, using
pythonexecutes script as version 2 andpython3executes 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
mountandunmountcommands
Installation of Applications
- Windows setup file can be executed in silent mode with command switches
- installers are implemented in
.exeor.msipackages- EXE in batch file:
C:\User\Downloads\setup.exe /S /desktopicon=yes - MSI installer with
msiexeccommand:msiexec C:\User\Downloads\install.msi /qn - can also run these directly in PowerShell script
Start-Processcmdlet gives you more options for controlling the installation and handling errors
- EXE in batch file:
- Linux scripts are used to compile apps from source code
- can also automate APT or YUM package managers
Initiating Updates
- Windows:
wusa.exeprocess called from batch file - PowerShell:
PSWindowsUpdatemodule contains cmdlets for managing update process - Linux: call
apt-getoraptoryumfrom Bash script-yflag 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
Getcmdlets for getting data from Windows subsystemGet-NetAdapterfor network adapter propertiesGet-WinEventfor log data- can pipe results into
Where-ObjectandSelect-Objectcmdlets to apply filters
- Bash:
- gather data from output of commands like
psordf - filter using
grep - format using
awkorcut - redirect output to a file
- gather data from output of commands like
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
- if interpreter is not a default feature, enabling it expands the attack surface
- 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