05 Command Line
05 Command Line
Learn the command line and MS PowerShell in Windows by practising various essential
commands. Then, discover the use of Bash in the Linux OS.
Understanding command-line interfaces (CLI) is essential, as many security tools and tasks
require their configuration and usage through them. CLIs are imperative for scripting and
automation and can prove very helpful in carrying out penetration testing and incident
analysis. This module will teach us how to use the command line and PowerShell in
Windows and Bash in Linux.
Windows PowerShell
Discover the "Power" in PowerShell and learn the basics.
Linux Shells
Learn about scripting and the different types of Linux shells.
Windows Command Line
Learn the essential Windows commands.
Task 1 Introduction
Task 6 Conclusions
Task 1 Introduction
Everyone prefers a graphical user interface (GUI) until they master a command-
line interface (CLI). There are many reasons for that. One reason is that GUIs are
usually intuitive. If someone offers you a GUI interface you are unfamiliar with,
you can quickly poke around and discover a non-trivial part. Compare this with
dealing with a CLI, i.e., a prompt.
CLI interfaces usually have a learning curve; however, as you master the
command line, you will find it faster and more efficient. Consider this trivial
example: How many clicks do you need to find your IP address using the
graphical desktop? Using the command-line interface, you don’t even need to
raise your hands off the keyboard. Let’s say you want to recheck your IP address.
You need to issue the same command instead of moving the mouse pointer to
every corner of your screen.
There are many other advantages to using a CLI besides speed and efficiency.
We will mention a few:
• Lower resource usage: CLIs require fewer system resources than graphics-
intensive GUIs. In other words, you can run your CLI system on older
hardware or systems with limited memory. If you are using cloud computing,
your system will require lower resources, which in turn will lower your bill.
• Automation: While you can automate GUI tasks, creating a batch file or script
with the commands you need to repeat is much easier.
Task 1 Introduction
• Remote management: CLI makes it very convenient to use SSH to manage a
remote system such as a server, router, or an IoT device. This approach works
well on slow network speeds and systems with limited resources.
Learning Objectives
The purpose of this room is to teach you how to use MS Windows Command
Prompt [Link], the default command-line interpreter in the Windows
environment. We will learn how to use the command line to:
Room Prerequisites
Before starting this room, you should have finished the Windows and AD
Fundamentals module.
Before issuing commands, we should note that we can only issue the commands
within the Windows Path. You can issue the command set to check your path
from the command line. The terminal output below shows the path where MS
Windows will execute commands, as indicated by the line starting with Path=.
Task 2 Basic System Information
Let’s use the ver command to determine the operating system (OS) version. The
terminal below shows an example output.
Enough warming up. Let’s discover more in-depth information about the system.
We can run the systeminfo command to list various information about the
system such as OS information, system details, processor and memory. The
terminal below shows a snippet of the displayed output.
Task 2 Basic System Information
Before moving on, it is good to mention a couple of tricks.
First, you can pipe it through more if the output is too long. Then, you can view it
page after page by pressing the space bar button. To demonstrate this, try
running driverquery and compare it with running driverquery | more. In the
latter, you can display the output page by page and you can exit it using CTRL +
C.
Network Configuration
You can check your network information using ipconfig. The terminal output
below shows our IP address, subnet mask, and default gateway.
You can also use ipconfig /all for more information about your network
configuration. As shown in the terminal below, we can view our DNS servers and
confirm that DHCP is enabled.
Task3 Network Troubleshooting
Network Troubleshooting
One common troubleshooting task is checking if the server can access a
particular server on the Internet. The command syntax is ping target_name.
Inspired by ping-pong, we send a specific ICMP packet and listen for a response.
If a response is received, we know that we can reach the target and that the
target can reach us.
Let’s find out if we reach [Link]. In the terminal output below, we can see
that we have successfully received four replies. Furthermore, we got some
statistics; for instance, the average round trip time is 78 milliseconds.
Task3 Network Troubleshooting
Another valuable tool for troubleshooting is tracert, which stands for trace route.
The command tracert target_name traces the network route traversed to reach
the target. Without getting into more details, it expects the routers on the path to
notify us if they drop a packet because its time-to-live (TTL) has reached zero.
The terminal output below shows that we passed through 15 routers before
reaching our target.
Task3 Network Troubleshooting
The final networking command we will cover in this room is netstat. This
command displays current network connections and listening ports. A basic
netstat command with no arguments will show you established connections, as
shown below. In this case, we only have one SSH connection; we figured out it is
SSH because it is bound to port 22.
Task3 Network Troubleshooting
If you are curious about the other options, you can run netstat -h, where -h
displays the help page. We opted for the following options:
You can change to any directory by using the command cd target_directory; this
is equivalent to double-clicking the target_directory on your desktop.
Furthermore, you can use cd .. to go up one level. An example is shown in the
terminal output below.
Task 4 File and Disk Management
more will display a single page and wait for you to press Spacebar to move by
one page (flip the page) or Enter to move by one line.
The copy command allows you to copy files from one location to another. The
following terminal output provides an example.
Task 4 File and Disk Management
Similarly, you can move files using the move command. An example is shown in
the terminal output below.
We can use the wildcard character * to refer to multiple files. For example, copy
*.md C:\Markdown will copy all files with the extension md to the directory
C:\Markdown.
Answer the questions below
What are the file’s contents in C:\Treasure\Hunt?
***{***_*****}
Task 5 Task and Process Management
You must be familiar with MS Windows Task Manager and might be familiar with
killing non-responsive processes. Let’s discover how to achieve a similar
functionality using the command line.
We can list the running processes using tasklist.
Some filtering is helpful because the output is expected to be very long. You can
check all available filters by displaying the help page using tasklist /?. Let’s say
that we want to search for tasks related to [Link], we can do that with the
command tasklist /FI "imagename eq [Link]". Note that /FI is used to set the
filter image name equals [Link].
Task 5 Task and Process Management
With the process ID (PID) known, we can terminate any task using taskkill /PID
target_pid. For example, if we want to kill the process with PID 4567, we would
issue the command taskkill /PID 4567.
What command can you use to kill the process with PID 1516?
taskkill /PID 1516
Task 6 Conclusion
In this room, we focused on the most practical commands for accessing a
networked system over the command line.
• chkdsk: checks the file system and disk volumes for errors and bad sectors.
• driverquery: displays a list of installed device drivers.
• sfc /scannow: scans system files for corruption and repairs them if possible.
It is important to remember all the commands covered in the previous tasks;
moreover, it is equally important to know that /? can be used with most
commands to display a help page.
Now that you know the Windows command line, it is time to move to the Windows
PowerShell room.
Task 6 Conclusion
Answer the questions below
The command shutdown /s can shut down a system. What is the command you
can use to restart a system?
******** /*
Task 1 Introduction
Task 2 What Is PowerShell
Task 3 PowerShell Basics
Task 4 Navigating the File System and Working with Files
Task 5 Piping, Filtering, and Sorting Data
Task 6 System and Network Information
Task 7 Real-Time System Analysis
Task 8 Scripting
Task 9 Conclusions
Task 1 Introduction
Ahoy there! If you’re here, you’ve either heard whispers of the marvels of
PowerShell and want to discover more, or you’ve sailed over from the first room
of the Command Line module—Windows Command Line. Either way, you’re
about to embark on a journey to discover the marvels of this powerful shell,
learning how to use it to uncover the secrets of any Windows system. Avast,
then—on board!
Learning Objectives
This is the second room in the Command Line module. It is an introductory room
to PowerShell, the second—only historically—command-line utility built for the
Windows operating system.
Room Prerequisites
Before approaching this room, it’s recommended that you have understood the
concepts in the Windows and AD Fundamentals module and the Windows
Command Line room.
Task 2 What Is PowerShell
PowerShell is a powerful tool from Microsoft designed for task automation and
configuration management. It combines a command-line interface and a scripting
language built on the .NET framework. Unlike older text-based command-line
tools, PowerShell is object-oriented, which means it can handle complex data
types and interact with system components more effectively. Initially exclusive to
Windows, PowerShell has lately expanded to support macOS and Linux, making
it a versatile option for IT professionals across different operating systems.
Jeffrey Snover, a Microsoft engineer, realised that Windows and Unix handled
system operations differently—Windows used structured data and APIs, while
Unix treated everything as text files. This difference made porting Unix tools to
Windows impractical. Snover’s solution was to develop an object-oriented
approach, combining scripting simplicity with the power of the .NET framework.
Released in 2006, PowerShell allowed administrators to automate tasks more
effectively by manipulating objects, offering deeper integration with Windows
systems.
We will explore more about PowerShell’s cmdlets and their capabilities in the
upcoming sections.
You can follow the steps below to connect to the target VM via SSH using the
Remmina client.
3. Select the SSH option from the dropdown (number 1 in the screenshot below),
then paste the target IP: MACHINE_IP in the bar at the top (number 2). Finally,
click Enter.
Task 3 PowerShell Basics
4. In the next window, enter the credentials found in the card below, then click on
OK.
Launching PowerShell
PowerShell can be launched in several ways, depending on your needs and
environment. If you are working on a Windows system from the graphical
interface (GUI), these are some of the possible ways to launch it:
• Start Menu: Type powershell in the Windows Start Menu search bar, then
click on Windows PowerShell or PowerShell from the results.
• Run Dialog: Press Win + R to open the Run dialog, type powershell, and hit
Enter.
• File Explorer: Navigate to any folder, then type powershell in the address
bar, and press Enter. This opens PowerShell in that specific directory.
• Task Manager: Open the Task Manager, go to File > Run new task, type
powershell, and press Enter.
Alternatively, PowerShell can be launched from a Command Prompt ([Link]) by
typing powershell, and pressing Enter.
In our case, where we only have access to the target VM’s Command Prompt,
this is the method we’ll use.
Task 3 PowerShell Basics
Basic Cmdlets
To list all available cmdlets, functions, aliases, and scripts that can be executed in
the current PowerShell session, we can use Get-Command. It’s an essential tool
for discovering what commands one can use.
We will learn more efficient ways to filter output from cmdlets in the upcoming
tasks.
Another essential cmdlet to keep in our tool belt is Get-Help: it provides detailed
information about cmdlets, including usage, parameters, and examples. It’s the
go-to cmdlet for learning how to use PowerShell commands.
NOTE: Please note that the cmdlets listed in this section require a working
internet connection to query online repositories. The attached machine doesn't
have access to the internet, therefore these commands won't work in this
environment.
Once identified, the modules can be downloaded and installed from the repository
with Install-Module, making new cmdlets contained in the module available for
use.
With these essential tools in our belt, we can now start exploring PowerShell’s
capabilities.
What is the command to retrieve some example usage for the cmdlet New-
LocalUser?
Similar to the dir command in Command Prompt (or ls in Unix-like systems), Get-
ChildItem lists the files and directories in a location specified with the -Path
parameter. It can be used to explore directories and view their contents. If no
Path is specified, the cmdlet will display the content of the current working
directory.
Task 4 Navigating the File System and Working with Files
To navigate to a different directory, we can use the Set-Location cmdlet. It
changes the current directory, bringing us to the specified path, akin to the cd
command in Command Prompt.
While the traditional Windows CLI uses separate commands to create and
manage different items like directories and files, PowerShell simplifies this
process by providing a single set of cmdlets to handle the creation and
management of both files and directories.
Similarly, the Remove-Item cmdlet removes both directories and files, whereas in
Windows CLI we have separate commands rmdir and del.
We can copy or move files and directories alike, using respectively Copy-Item
(equivalent to copy) and Move-Item (equivalent to move).
Task 4 Navigating the File System and Working with Files
Finally, to read and display the contents of a file, we can use the Get-Content
cmdlet, which works similarly to the type command in Command Prompt (or cat
in Unix-like systems).
Task 4 Navigating the File System and Working with Files
Answer the questions below
What cmdlet can you use instead of the traditional Windows command type?
Get-Content
What PowerShell command would you use to display the content of the
"C:\Users" directory? [for the sake of this question, avoid the use of quotes (" or ')
in your answer]
Get-ChildItem -Path C:\Users
How many items are displayed by the command described in the previous
question?
*
Task 5 Piping, Filtering, and Sorting Data
Piping is a technique used in command-line environments that allows the output
of one command to be used as the input for another. This creates a sequence of
operations where the data flows from one command to the next. Represented by
the | symbol, piping is widely used in the Windows CLI, as introduced earlier in
this module, as well as in Unix-based shells.
For example, if you want to get a list of files in a directory and then sort them by
size, you could use the following command in PowerShell:
Task 5 Piping, Filtering, and Sorting Data
Here, Get-ChildItem retrieves the files (as objects), and the pipe (|) sends those
file objects to Sort-Object, which then sorts them by their Length (size) property.
This object-based approach allows for more detailed and flexible command
sequences.
In the example above, we have leveraged the Sort-Object cmdlet to sort objects
based on specified properties. Beyond sorting, PowerShell provides a set of
cmdlets that, when combined with piping, allow for advanced data manipulation
and analysis.
To filter objects based on specified conditions, returning only those that meet the
criteria, we can use the Where-Object cmdlet. For instance, to list only .txt files
in a directory, we can use:
Task 5 Piping, Filtering, and Sorting Data
Here, Where-Object filters the files by their Extension property, ensuring that
only files with extension equal (-eq) to .txt are listed.
The operator -eq (i.e. "equal to") is part of a set of comparison operators that
are shared with other scripting languages (e.g. Bash, Python). To show the
potentiality of the PowerShell's filtering, we have selected some of the most
useful operators from that list:
-ne: "not equal". This operator can be used to exclude objects from the results
based on specified criteria.
-gt: "greater than". This operator will filter only objects which exceed a specified
value. It is important to note that this is a strict comparison, meaning that objects
that are equal to the specified value will be excluded from the results.
-ge: "greater than or equal to". This is the non-strict version of the previous
operator. A combination of -gt and -eq.
-lt: "less than". Like its counterpart, "greater than", this is a strict operator. It will
include only objects which are strictly below a certain value.
-le: "less than or equal to". Just like its counterpart -ge, this is the non-strict
version of the previous operator. A combination of -lt and -eq.
Below, another example shows that objects can also be filtered by selecting
properties that match (-like) a specified pattern:
Task 5 Piping, Filtering, and Sorting Data
The next filtering cmdlet, Select-Object, is used to select specific properties from
objects or limit the number of objects returned. It’s useful for refining the output to
show only the details one needs.
The cmdlets pipeline can be extended by adding more commands, as the feature
isn’t limited to just piping between two cmdlets. As an exercise, try and build a
pipeline of cmdlets to sort and filter the output with the goal of displaying the
largest file in the C:\Users\captain\Documents\captain-cabin directory.
Task 5 Piping, Filtering, and Sorting Data
Click here to look at a possible solution. Don’t cheat!
The last in this set of filtering cmdlets is Select-String. This cmdlet searches for
text patterns within files, similar to grep in Unix-based systems or findstr in
Windows Command Prompt. It’s commonly used for finding specific content
within log files or documents.
The Select-String cmdlet fully supports the use of regular expressions (regex).
This advanced feature allows for complex pattern matching within files, making it
a powerful tool for searching and analysing text data.
Essential for managing user accounts and understanding the machine’s security
configuration, Get-LocalUser lists all the local user accounts on the system. The
default output displays, for each user, username, account status, and description.
Task 6 System and Network Information
Similar to the traditional ipconfig command, the following two cmdlets can be
used to retrieve detailed information about the system’s network configuration.
Get-NetIPConfiguration provides detailed information about the network
interfaces on the system, including IP addresses, DNS servers, and gateway
configurations.
Task 6 System and Network Information
In case we need specific details about the IP addresses assigned to the network
interfaces, the Get-NetIPAddress cmdlet will show details for all IP addresses
configured on the system, including those that are not currently active.
Task 6 System and Network Information
These cmdlets give IT professionals the ability to quickly access crucial system
and network information directly from the command line, making it easier to
monitor and manage both local and remote machines.
This lad has hidden his account among the others with no regard for our beloved
captain! What is the motto he has so bluntly put as his account's description?
* ****** **** *** * ***** ***.
Now a small challenge to put it all together. This shady lad that we just found
hidden among the local users has his own home folder in the "C:\Users" directory.
Can you navigate the filesystem and find the hidden treasure inside this pirate's
home?
***{*************}
Task 7 Real-Time System Analysis
To gather more advanced system information, especially concerning dynamic
aspects like running processes, services, and active network connections, we can
leverage a set of cmdlets that go beyond static machine details.
1. $DATA is the default data stream of every NTFS file. It contains the normal file
contents and is not an ADS.
Note: The ADS example shown above is from a file of a different machine and will
not be available to you in the attached VM.
It's time for another small challenge. Some vital service has been installed on this
pirate ship to guarantee that the captain can always navigate safely. But
something isn't working as expected, and the captain wonders why. Investigating,
they find out the truth, at last: the service has been tampered with! The shady lad
from before has modified the service DisplayName to reflect his very own motto,
the same that he put in his user description.
With this information and the PowerShell knowledge you have built so far, can
you find the service name?
******-s-******
Task 8 Scriptting
Scripting is the process of writing and executing a series of commands
contained in a text file, known as a script, to automate tasks that one would
generally perform manually in a shell, like PowerShell.
Simply speaking, scripting is like giving a computer a to-do list, where each line in
the script is a task that the computer will carry out automatically. This saves time,
reduces the chance of errors, and allows to perform tasks that are too complex or
tedious to do manually. As you learn more about shells and scripting, you’ll
discover that scripts can be powerful tools for managing systems, processing
data, and much more.
Learning scripting with PowerShell goes beyond the scope of this room.
Nonetheless, we must understand that its power makes it a crucial skill across all
cyber security roles.
The first example shows how the cmdlet can be very easily combined with any
custom script to automate tasks on remote computers.
The second example demonstrates that we don't need to know how to script to
benefit from the power of Invoke-Command. In fact, by appending the -
ScriptBlock { ... } parameter to the cmdlet's syntax, we can execute any
command (or sequence of commands) on the remote computer. The result would
be the same as if we were typing the commands in a local PowerShell session on
the remote computer itself.
With these tools in your belt, you’re well-equipped to explore even the most
guarded corners of any Windows system.
Remember, a true pirate never stops seeking treasure—so keep honing your
skills, and who knows what pearls you’ll discover in the next adventure? Until
then, may your cmdlets be sharp and your scripts swift. Fair winds, and happy
hunting!
To continue building up your command line skills, proceed to the Linux Command
Line room, up next in the module.
Task 7 Conclusions
Task 1 Introduction to Linux Shells
As regular users of operating systems, we all extensively use the Graphical User
Interface (GUI) to carry out most operations. It takes a few clicks on different
options, and your task is done. However, you can perform almost every task by
writing commands in the CLI of your operating system rather than using the GUI.
The shells give you some great features for the commands you write in your CLI.
This way of interacting with the OS is more efficient and resource-friendly.
Suppose you are in a restaurant and have two options for your food. The first
option is to order food from the menu, and the waiter will serve it. The second
option is to cook your desired dish yourself in the kitchen. In terms of a Linux
system, the kitchen here is the OS, and using the GUI of the OS is just like
ordering the food from the menu, and the waiter will serve it for you. However,
using the CLI means you would have to go to the kitchen (OS) and cook your
desired food. In this example, Shell would help you cook your desired dish by
giving you some recipe suggestions. Using CLI to perform operations in a Linux
system gives you more power and control while carrying out the tasks.
You may have seen hacking scenes in movies that show cool terminals with
many commands getting executed. This is because most Linux users prefer to
perform operations by writing commands on the CLI using shells instead of using
the GUI. This room will teach us how to interact with a Linux shell. We will also
explore different shells available in Linux and write some shell scripts in the end.
Task 1 Introduction to Linux Shells
Learning Objectives
Room Prerequisites
Linux Fundamentals module
Most Linux distributions use Bash (Bourne Again Shell) as their default shell.
However, the default shell displayed when you open the terminal depends on
your Linux distribution.
You would have already explored the basic Linux commands in the Linux
Fundamentals module mentioned in this room’s prerequisites. Let’s briefly
discuss some of the most important ones we use in the shell.
When interacting with a shell, you must be in the directory where you want to
perform operations. By default, when you open a shell in most of the Linux
distributions, you will be in your home directory. To see your current working
directory, you can execute pwd, which stands for Print Working Directory, as
shown in the terminal below:
Task 2 How To Interact With a Shell?
Introduction to Linux Shells
In the results of the above command, you can see that your current working
directory is /home/ubuntu
However, you can change your directory as well. To do that, you can use cd
(short for Change Directory), as shown in the terminal below:
While using the GUI of an OS, you can see the contents of a directory on the
screen. However, while using the shell, to see the contents of a directory, you
must enter the following command:
Task 2 How To Interact With a Shell?
Introduction
If you want totoread
Linux
theShells
contents of a file, you can type the following command in
your shell:
The grep command is a very popular command among Linux users. This powerful
command can search for any word or pattern inside a file. Suppose you want to
search for specific entries in a huge file. You can use the grep command along
with the pattern of those entries, which will extract them for you. It also helps you
to search for a specific keyword in a big file.
The following terminal shows us how to use the grep command to search for the
word "THM" inside a big text file. The output displays the specific line of that text
file containing this word.
Task 2 How To Interact With a Shell?
Introduction to Linux below
Answer the questions Shells
What is the default shell in most Linux distributions?
****
Which command utility can help you search for anything in a file?
****
Multiple shells are installed in different Linux distributions. To see which shell you
are using, type the following command:
You can also list down the available shells in your Linux OS. The file /etc/shells
contains all the installed shells on a Linux system. You can list down the available
shells in your Linux OS by typing cat /etc/shells in the terminal:
Task 3 Types of Linux Shells
To switch between these shells, you can type the shell name that is present on
your OS, and it will open for you, as can be seen below:
If you want to permanently change your default shell, you can use the command:
chsh -s /usr/bin/zsh. This will make this shell as the default shell for your
terminal.
There are many types of Linux shells. We will discuss a few of them and their
features.
Bourne Again Shell (Bash) is the default shell for most Linux distributions. When
you open the terminal, bash is present for you to enter commands. Before bash,
some shells like sh, ksh, and csh had different capabilities. Bash came as an
enhanced replacement for these shells, borrowing capabilities from all of them.
This means that it has many of the features of these old shells and some of its
unique abilities. Some of the key features provided by bash are listed below:
Task 3 Types of Linux Shells
• Bash is a widely used shell with scripting capabilities.
• It offers a tab completion feature, which means if you are in the middle of
completing a command, you can press the tab key on your keyboard. It will
automatically complete the command based on a possible match or give you
multiple suggestions for completing it.
• Bash keeps a history file and logs all of your commands. You can use the up
and down arrow keys to use the previous commands without typing them
again. You can also type history to display all your previous commands.
Friendly Interactive Shell (Fish) is also not default in most Linux distributions. As
its name suggests, it focuses more on user-friendliness than other shells. Some
of the key features provided by fish are listed below:
• Zsh provides advanced tab completion and is also capable of writing scripts.
• Just like fish, it also provides auto spell correction for the commands.
• It offers extensive customization that may make it slower than other shells.
• It also provides tab completion, command history functionality, and several
other features.
Selecting the best Linux shell depends on your usage and its features. The shells
discussed in this task are some of the many different shells available in Linux.
You can compare the features of these different shells and choose the best one
based on your tasks.
Which command displays all the previously executed commands of the current
session?
*******
The first step is to open the terminal and select a shell. Let’s go with the bash
shell, the default, and widely used shell in most distributions.
Unlike the other commands we type in the shell, we first need to create a file
using any text editor for the script. The file must be named with an extension .sh,
the default extension for bash scripts. The following terminal shows the script file
creation:
Task 4 Shell Scripting and Components
Every script should start from shebang. Shebang is a combination of some
characters that are added at the beginning of a script, starting with #! followed by
the name of the interpreter to use while executing the script. As we are writing our
script in bash, let’s define it as the interpreter in the shebang.
We are all set to write our first script now. There are some fundamental building
blocks of a script that together make an efficient script. Let’s learn and utilize
these script constructs to write one script ourselves.
Variables
A variable stores a value inside it. Suppose you need to use some complex
values, like a URL, a file path, etc., several times in your script. Instead of
memorizing and writing them repeatedly, you can store them in a variable and
use the variable name wherever you need it.
The script below displays a string on the screen: "Hey, what’s your name?” This is
done by echo command. The second line of the script contains the code read
name. read is used to take input from the user, and name is the variable in which
the input would be stored. The last line uses echo to display the welcome line for
the user, along with its name stored in the variable.
Task 4 Shell Scripting and Components
Now, save the script by pressing CTRL+X. Confirm by pressing Y and then
ENTER.
To execute the script, we first need to make sure that the script has execution
permissions. To give these permissions to the script, we can type the following
command in our terminal:
Now that the script has execution permissions use ./ before the script name to
execute it. We use ./ before the script to run rather than typing the script name
directly because ./ tells the shell to execute the file that is present in the current
directory. If you don't define ./ before the script name, the shell will search the
script in the PATH environment variable (that contains all the directories except
the current one), and it will not find the defined script in any of those directories
and generate an error. The below terminal shows the script in which we utilized
the variables:
Task 4 Shell Scripting and Components
Loops
Loop, as the name suggests, is something that is repeating. For example, you
have a list of many friends, and you want to send them the same message.
Instead of sending them individually, you can make a loop in your script, give your
friend list to the loop and the message, and it will send that message to all your
friends.
For a general explanation of loops, let’s write a loop that will display all numbers
starting from 1 to 10 on the screen. First, create a new file named
loop_script.sh, then enter the code below. Save your file by pressing CRTL+X,
then confirm with y and then ENTER.
Task 4 Shell Scripting and Components
The first line has the variable i that will iterate from 1 to 10 and execute the below
code every time. do indicates the start of the loop code, and done indicates the
end. In between them, the code we want to execute in the loop is to be written.
The for loop will take each number in the brackets and assign it to the variable i in
each iteration. The echo $i will display this variable’s value every iteration.
Now, let’s execute the script after giving it the execution permission.
The output of the above terminal is cut to 3 numbers only for demonstration.
However, when executed according to the script's logic, it would display the
numbers from 1 to 10.
Conditional Statements
Conditional statements are an essential part of scripting. They help you execute a
specific code only when a condition is satisfied; otherwise, you can execute
another code. Suppose you want to make a script that shows the user a secret.
Task 4 Shell Scripting and Components
However, you want it to be shown to only some users, only to the high-authority
user. You will create a conditional statement that will first ask the user their name,
and if that name matches the high authority user’s name, it will display the secret.
First, create a new file named conditional_script.sh, then enter the code below.
Save your file by pressing CRTL+X, then confirm with y and then ENTER.
The above script takes the user’s name as input and stores it into a variable
(studied in the Variables section). The conditional statement starts with if and
compares the value of that variable with the string Stewart; if it’s a match, it will
display the secret to the user, or else it will not. The fi is used to end the condition.
Following is the terminal showing the script execution when the user name
matches the authorized one defined in the script:
Task 4 Shell Scripting and Components
However, the following terminal shows the script execution when the user name
does not match the authorized one defined in the script:
Comments
Sometimes, the code can be very lengthy. In this scenario, the code might
confuse you when you look at it after some time or share it with somebody. An
easy way to resolve this problem is to use comments in different parts of the
code. A comment is a sentence that we write in our code just for the sake of our
understanding. It is written with a # sign followed by a space and the sentence
you need to write. For example, let’s rewrite the script we discussed in the
conditional statements section and add comments to it. Open the
conditional_script.sh with nano, then add the comments starting with a # sign.
Save your file by pressing CRTL+X, then confirm with y and then ENTER.
See how easy a script looks with comments. Comments don’t affect the working
of any script. A good script always has some comments. The example shown
above contains a comment for each line.
Task 4 Shell Scripting and Components
This is just a better explanation of its concept. However, the best way to include
comments is to define them in the major and complex areas of the script.
Note: Other types of variables, loops, and conditional statements can also be
used to achieve different tasks. Moreover, multiple lines of comments can also be
added within a single comment. However, it is not the scope of this room.
Task 4 Shell Scripting and Components
Answer the questions below
Requirement
A user has a locker in a bank. To secure the locker, we have to have a script in
place that verifies the user before opening it. When executed, the script should
ask the user for their name, company name, and PIN. If the user enters the
following details, they should be allowed to enter, or else they should be denied
access.
• Username: John
• Company name: Tryhackme
• PIN: 7385
Task 5 The Locker Script
Script
Task 5 The Locker Script
Script Execution
Note: Some changes are required inside the script file before you execute it.
When you open the machine according to the instructions in task #2, you will be
able to gain the session as a normal user. However, we recommend you to
become the root user in order to search for the flag in all the files of the given
directory. To become one, you only need to type the following command and
enter the password of the user (The credentials are included in Task 2):
You can make the changes in the script file by keeping in view the following
details:
Flag: thm-flag01-script
Directory: /var/log
Hint: Look for empty double quotes " " inside the script file and fill them. Make
sure not to leave any space between them.
Task 6 Practical Exercise
Answer the questions below
Task 7 Conclusion
In this room, we studied the importance of shells and flew to the world of Linux
shells, exploring their major types. We gained a good understanding of shell
scripting and its role in automating tasks. In the end, we created some cool shell
scripts and solved a practical lab pertaining to a script that finds mysterious things
out of different directories.