This is a machine-translated text that may contain errors!
If you have done the same task for the third time, it’s time to automate it. Scripting is about letting the machine do the tedious work for you, faster and without forgetting anything.
Why Automate?
Some tasks in IT operations are done frequently:
- Updating servers
- Creating users
- Taking backups
- Restarting services after an update
- Checking that services are running
Doing these manually each time takes time, and it is easy to forget a step. A script does the same thing every time, without complaining.
Bash: Scripting in Linux
Bash is the shell (terminal) in most Linux distributions, and it can also run scripts. A Bash script is simply a text file with commands that are executed in sequence.
Your first script
Create a file named oppdater.sh:
#!/bin/bash
# Update the package list and install updates
echo "Updating the system..."
sudo apt update
sudo apt upgrade -y
echo "Done!"
Make the file executable and run it:
chmod +x oppdater.sh
./oppdater.sh
# Makes the script executable
# Runs the script
#!/bin/bash
The first line is called a shebang. It tells the operating system that the file should be executed with Bash. Without it, the system doesn’t know which program should interpret the script.
Variables and Input
For å kunne kjøre en simulering, må vi definere variabler som beskriver systemet vi ønsker å modellere. Disse variablene kan representere alt fra fysiske størrelser som temperatur og trykk, til abstrakte konsepter som etterspørsel og pris. Input er dataene vi gir til modellen for å starte simuleringen.
For eksempel, i en simulering av et værsystem, kan variabler være temperatur, luftfuktighet, vindhastighet og nedbør. Input kan være startverdier for disse variablene, samt eksterne faktorer som solinnstråling og geografisk plassering.
I mange tilfeller vil variabler og input være knyttet sammen. Input kan brukes til å initialisere variabler, eller til å påvirke deres utvikling over tid. Det er viktig å definere variabler og input nøye, slik at modellen blir realistisk og gir meningsfulle resultater.
To define variables, we use the var keyword followed by the variable name and its data type. For example:
var temperature: float = 20.0
var pressure: float = 1013.25
var wind_speed: float = 5.0
Input kan leses fra forskjellige kilder, for eksempel fra en fil, fra en database, eller fra brukeren. I Python kan vi bruke input() funksjonen for å lese input fra brukeren:
name = input("Enter your name: ")
print("Hello, " + name + "!")
It is important to validate the input to ensure that it is in the correct format and within the expected range. This can help to prevent errors and ensure that the simulation runs correctly.
#!/bin/bash
BRUKERNAVN=$1
if [ -z "$BRUKERNAVN" ]; then
echo "Usage: ./lag_bruker.sh <username>"
exit 1
fi
sudo adduser "$BRUKERNAVN"
sudo usermod -aG sudo "$BRUKERNAVN"
echo "User $BRUKERNAVN created with sudo access."
Here, the script takes a username as an argument ($1 is the first argument). If you run ./lag_bruker.sh ola, it will create the user ola and give it sudo access.
Useful Bash Concepts
| Concept | Example | What it does |
|---|---|---|
| Variable | NAME="Ola" | Stores a value |
| Argument | $1, $2 | Input from the command line |
| If-check | if [ -f "file.txt" ]; then | Checks if a file exists |
| For-loop | for f in *.log; do | Does something for each matching file |
| Pipe | cat logg.txt \| grep "ERROR" | Sends output from one command to another |
PowerShell: Scripting in Windows
PowerShell is Windows’ answer to Bash, but it is more object-oriented. It works with objects instead of just text, which makes it powerful for managing Windows systems.
Example: Check Disk Space
For å sjekke hvor mye diskplass som er ledig, kan du bruke kommandoen df -h. Denne kommandoen viser diskplassbruken for alle monterte filsystemer i et lesbart format (f.eks. GB, MB).
For å sjekke diskplassbruken for en spesifikk mappe, kan du bruke kommandoen du -sh <mappenavn>. Dette vil vise den totale størrelsen på mappen.
For eksempel:
df -h
du -sh /home/brukernavn/dokumenter
Disse kommandoene er nyttige for å identifisere store filer eller mapper som tar opp mye plass på disken din.
# Check available disk space
Get-PSDrive -PSProvider FileSystem | Select-Object Name,
@{Name="Used (GB)"; Expression={[math]::Round($_.Used / 1GB, 2)}},
@{Name="Free (GB)"; Expression={[math]::Round($_.Free / 1GB, 2)}}
Example: Installing Software with Winget
# Install multiple programs at once
winget install Mozilla.Firefox
winget install Microsoft.VisualStudioCode
winget install Git.Git
winget install Python.Python.3.12
This is much faster than downloading and installing everything manually. You can save the list in a script and run it every time you set up a new machine.
Task 1 - Create an Update Script
Write a Bash script that:
- Updates the package list
- Installs all available updates
- Restarts Nginx (or another service you are running)
- Prints a message when it is finished
Run it on one of your VMs and see that it works.
Task 2 - Automate Machine Setup
Create a PowerShell script (.ps1) or a simple list of winget install commands for all the programs you need on a new PC. Consider:
- Which programs do you always install?
- Can you also configure some settings with the script?
Next time you set up a machine, just run the script instead of spending an hour on manual installation.
Summary
- If you do something more than two times, consider automating it
- Bash (Linux) and PowerShell (Windows) are the most common tools for scripting
- Bash scripts are text files with commands that are executed in sequence
- PowerShell works with objects and is powerful for Windows administration
- Variables, arguments, if checks and loops are the most important building blocks