# DevOps Training Session 3: OS - Scripting with ps & bash
###### tags: `devops` `research` `reliable`
Hello BTB from diary of DevOps intern, today and tomorrow i will research and implement script about OS with powershell and bash. This is lab to day --> [LAB3](https://drive.google.com/file/d/1XLLCjB0pePB8lguirKABN0hf7kU0ElKx/view?usp=sharing)
## Practice Scripting - Research
1. Write a Powershell function and a Shell Script function that:
- Take a string input as a date (i.e. Thursday, July 21, 2022)
- Check if the date is in the right format “dddd,MM dd,YYYY”
(using regex)
- Check if the year is a leap year
- Check if it is a weekend
Bash
```
#!/bin/bash
ChallengeName="P1 - Bash"
echo "Hey this is my first $ChallengeName"
read -p "Which day you want to check: " Daytoday
if [[ $Daytoday =~ ^[A-Za-z]{6,9},[[:space:]]*[A-Za-z]{3,9}[[:space:]]*[0-3]{1}[0-9]{1},[[:space:]]*[1-9]{1}[0-9]{1}[0-9]{1}[0-9]{1}$ ]]
then
echo "Right Format"
Year=$(echo $Daytoday | cut -d "," -f 3 | tr -d " ")
Day=$(echo $Daytoday | cut -d "," -f 1)
if [[ $(($Year % 400)) = 0 && $(($Year % 100)) = 0 ]]
then
echo "$Year is a leap year"
elif [[ $(($Year % 400)) = 0 && $(($Year % 100)) != 0 ]]
then
echo "$Year is not a leap year"
else
echo "$Year is not a leap year"
fi
if [ $Day == "Sunday" ]
then
echo "$Daytoday is the weekend"
else
echo "$Daytoday is not the weekend"
fi
else
echo "Not Right format"
fi
```
Powershell
```
#!/usr/bin/pwsh
# 1. Write a Powershell function and a Shell Script function that:
# - Take a string input as a date (i.e. Thursday, July 21, 2022)
# - Check if the date is in the right format “dddd,MM dd,YYYY”
# (using regex)
# - Check if the year is a leap year
# - Check if it is a weekend
$ChallengeName="P1 - Powershell"
Write-Host "Hey this is my first $ChallengeName"
$Daytoday = Read-Host -Prompt "Which day you want to check"
if ($Daytoday -match '[A-Za-z]{6,9}, [A-Za-z]{3,9} [0-3]{1}[0-9]{1}, [1-9]{1}[0-9]{1}[0-9]{1}[0-9]{1}')
{
Write-Host "Right format"
$Day, $Year = ($Daytoday -replace " " -split ",")[0,-1]
if ((($Year % 4) -eq 0 -And ($Year % 100) -ne 0) -Or (($Year % 400) -eq 0 ))
{
Write-Host "$Year is the leap year"
}
else
{
Write-Host "$Year is not the leap year"
}
if (($Day -eq "Sunday"))
{
Write-Host "$Daytoday is the weekend"
}
else
{
Write-Host "$Daytoday is not the weekend"
}
}
else
{
Write-Host "Not right format"
}
```
---
2. Write a Powershell script and a Bash script that:
- List all files in the current directory, sorts the output, remove file extensions
- List only show .txt files
- List files and folders that have been created within 1 day
Bash
```
#!/bin/bash
echo "List all files in the current directory, sorts the output, remove file
extensions"
ls | sort | cut -d "." -f 1
echo ""
echo ""
echo "Show only txt file"
echo "Method 1 using ls"
ls | egrep '\.txt'
echo "Method 2 using find"
find . -iregex '.*\.\(txt\)' -printf '%f\n'
echo ""
echo ""
echo "List files and folders that have been created within 1 day"
find . -maxdepth 1 -mtime -1
```
Powershell
```
#!/usr/bin/env pwsh
# 2. Write a Powershell script and a Bash script that:
# - List all files in the current directory, sorts the output, remove file
# extensions
# - List only show .txt files
# - List files and folders that have been created within 1 day
Write-Host "List all files in the current directory, sorts the output, remove file extensions"
$list = (Get-Item *).Basename | Sort-Object
Write-Host $list
Write-Host ""
Write-Host ""
Write-Host "List only show .txt files"
$txtList = (Get-ChildItem -Path $dir -Filter *.txt | Select-Object -First 1).Name
Write-Host $txtList
Write-Host ""
Write-Host ""
Write-Host "List files and folders that have been created within 1 day"
$day_today = (Get-Date).AddDays(-1)
$1_day_create = Get-ChildItem -Path $dir -Force -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt $day_today } |
Sort-Object -Descending
Write-Host $1_day_create
```
---
3. Write a Powershell script and a Bash script that:
- Take your input
- Check if the input is empty
- Create a new script (Check if the file exists) that prints out your input and the new script name/full path
- Execute that new script
Bash
```
#!/bin/bash
# 3. Write a Powershell script and a Bash script that:
# - Take your input
# - Check if the input is empty
# - Create a new script (Check if the file exists) that prints out your
# input and the new script name/full path
# - Execute that new script
read -p "Type your input: " input
if [[ $input == "" ]]
then
echo "Your input is empty | Ending here"
else
read -p "What script you want to excute, Remember give it to a file: " newscript
name_newfile=$(echo $newscript | cut -d ">" -f 2 | tr -d " ")
script=$(echo $newscript | cut -d ">" -f 1)
if [[ -f $name_newfile ]]
then
echo "file really exist !! Ending here"
exit 1
else
echo "The input is : $input"
pathoffile="$PWD/$name_newfile"
echo "Name: $name_newfile"
echo "Fullpath: $pathoffile"
echo "Script:" > $name_newfile
echo "$script" >> $name_newfile
echo "Result: " >> $name_newfile
# $(<blockcommand>) --> Execuatable
command=$($script >> $name_newfile)
cat $name_newfile
fi
fi
```
Powershell
```
#!/usr/bin/env pwsh
# 3. Write a Powershell script and a Bash script that:
# - Take your input
# - Check if the input is empty
# - Create a new script (Check if the file exists) that prints out your
# input and the new script name/full path
# - Execute that new script
$input = Read-Host -Prompt "Put your input here"
if ($input -eq "")
{
Write-Host "This is empty !! Do type right again"
}
else
{
$newscript = Read-Host -Prompt "What is your new script"
$script, $namefile = ($newscript -split " | ")[0,-1]
$current_Dir = Get-Location
$namefile = $namefile.replace(".\", "/")
$location_file = [string]$current_Dir + [string]$namefile
if (Test-Path -Path $location_file -PathType Leaf)
{
Write-Host "This is existed file | Do type right again"
}
else
{
Write-Host "Input: " $input
Write-Host "Name: " $namefile
Write-Host "FullPath: " $location_file
#Invoke-Command -ScriptBlock { <blockcommand> }--> Executable ? Really work on terminal but not with script
#Anotherway: iex $command alias for Invoke-Expression --> It work with source powershell script
iex $newscript
Get-Content $location_file
}
}
```
---
4. Create a text file, and open it by an app. Write a Powershell script and a Bash script that checks which process is opening that file then kill that process
Bash
```
#!/bin/bash
# 4. Create a text file, and open it by an app. Write a Powershell script
# and a Bash script that checks which process is opening that file then
# kill that process
read -p "what find you want to kill: " filename
command=$(ps -aux | grep nano | grep $filename | cut -d " " -f 3)
echo $command
kill $command
```
Powershell
```
#!/usr/bin/env pwsh
# 4. Create a text file, and open it by an app. Write a Powershell script
# and a Bash script that checks which process is opening that file then
# kill that process
$namefile = Read-Host -Prompt "What name of file you want to kill"
$ID = (Get-Process | Select-Object ID,CommandLine | Where-Object CommandLine -EQ "/usr/bin/nano./$namefile").Id
echo $ID
Stop-Process -ID $ID -Force
```
---
5. Write a Powershell script and a Bash script that download a compressed file and then decompress it into a folder
Bash
```
#!/bin/bash
# 5. Write a Powershell script and a Bash script that download a
# compressed file and then decompress it into a folder
sudo apt install -y unzip
read -p "URL you want to download : " URL
command=$(wget $URL)
file=$(ls | egrep '\.zip')
namefolder=$(echo $file | cut -d "." -f 1)
mkdir $namefolder
command_unzip=$(unzip $file -d $namefolder)
echo $command_unzip
```
Powershell
```
#!/usr/bin/env pwsh
# 5. Write a Powershell script and a Bash script that download a
# compressed file and then decompress it into a folder
$URL = Read-Host -prompt "URL you want to download"
$Path = $URL.split("/")[-1]
$Store_Path = $Path.split('.')[0]
Invoke-WebRequest -URI $URL -OutFile $Path
Expand-Archive -Path $Path -Destination $Store_Path
```
---
6. Delete everything in a folder, mute all outputs and continue if any error
Bash
```
#!/bin/bash
# 6. Delete everything in a folder, mute all outputs and continue if any error
read -p "What the folder you want to delete: " folder
# Run with one command
# if [[ -d $folder ]]
# then
# command=$(rm -rf $folder)
# echo "delete complete"
# else
# echo "This folder is not existed"
# fi
# Run with remove stderr ignore and dev/null
if [[ -d $folder ]]
then
for filename in $folder/*
do
if [[ -d $filename ]]
then
for sub_filename in $filename/*
do
rm $sub_filename 2> /dev/null || continue
done
rmdir $filename 2> /dev/null || continue
else
rm $filename 2> /dev/null || continue
fi
done
rmdir $folder 2> /dev/null || exit 0
fi
```
Powershell
```
#!/usr/bin/env pwsh
# 6. Delete everything in a folder, mute all outputs and continue if any error
$folder = Read-Host -prompt "What folder you want to delete"
$current_Dir = Get-Location
$location_file= [string]$current_Dir + "/" + [string]$folder
if (Test-Path -Path $location_file)
{
Remove-Item $location_file -Force -Confirm:$false
}
else
{
Write-Host "The folder is not exist "
}
```
---
7.
![](https://i.imgur.com/Un5Eapo.png)
Write a Powershell script and a Bash script that:
- Count “image” length
- Print an image name in the image list if the resolution is square
Bash
```
#!/bin/bash
#- Count “image” length
#- Print an image name in the image list if the resolution is square
image_Length=$(cat image.json | jq '.Image | length')
echo "The image Length: $image_Length"
echo "Name the image is square shape: "
for((i=0;i<$image_Length;i++)); do
o_hoffset=$(cat image.json | jq '.Image['$i'].hoffset')
o_woffset=$(cat image.json | jq '.Image['$i'].woffset')
if [[ $o_hoffset -eq $o_woffset ]]
then
echo $(cat image.json | jq '.Image['$i'].name')
else
continue
fi
done
```
Powershell
```
#!/usr/bin/env pwsh
#- Count “image” length
#- Print an image name in the image list if the resolution is square
$length_Image = ((Get-Content .\image.json | ConvertFrom-Json).Image).Length
Write-Host "Length of Image in json file is: $length_Image"
$Image_objects = (Get-Content .\image.json | ConvertFrom-Json).Image
($Image_objects | Where-Object {$_.hoffset -eq $_.woffset}).name
```
---
8. Write a Powershell script and a Bash script that check open ports in `www.orientsoftware.com`
Bash
```
#!/bin/bash
#8. Write a Powershell script and a Bash script that check open ports in `www.orientsoftware.com`
read -p "What port you want to check to open: " port
for i in $(echo $port | tr " " "\n")
do
# process
$(timeout 1 bash -c 'cat < /dev/null > /dev/tcp/www.orientsoftware.com/'$i'')
if [[ $? -eq 0 ]]
then
echo "This port $i is open"
else
echo "This port $i is not established by the timeout"
fi
done
```
Powershell
```
#!/usr/bin/env pwsh
#8. Write a Powershell script and a Bash script that check open ports in `www.orientsoftware.com`
$port = Read-Host "What port you want to check in www.orientsoftware.com"
for ($i = 0; $i -lt $port.Split(" ").Length; $i++)
{
if ((Test-NetConnection -ComputerName www.orientsoftware.com -Port $port.Split(" ")[$i]).TcpTestSucceeded -eq "True")
{
Write-Host $port.Split(" ")[$i] "is Open"
}
}
```
---
9. Write a Powershell script and a Bash script that enable/disable SSH on a Windows/Linux machine
Bash
```
#!/bin/bash
# 9. Write a Powershell script and a Bash script that enable/disable SSH on a Windows/Linux machine
read -p "which mode do you want to apply ssh: " ssh_mode
if [[ $ssh_mode = "enable" ]]
then
command=$(sudo -i systemctl start ssh)
echo "enable for ssh"
fi
if [[ $ssh_mode = "disable" ]]
then
command=$(sudo -i systemctl stop ssh)
echo "stop for ssh"
fi
```
Powershell
```
#!/usr/bin/env pwsh
# 9. Write a Powershell script and a Bash script that enable/disable SSH on a Windows/Linux machine
param([switch]$Elevated)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated) {
# tried to elevate, did not work, aborting
exit 1
} else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
$mode = Read-Host -prompt "Enable/Disable SSH"
if ($mode -eq "Enable" -or $mode -eq "enable")
{
Start-Service -name SSDPSRV -force
Set-Service -name SSDPSRV -StartupType Manual
Get-Service SSDPSRV
}
if ($mode -eq "Disable" -or $mode -eq "disable")
{
Stop-Service -name SSDPSRV -force
Set-Service -name SSDPSRV -StartupType Disabled
Get-Service SSDPSRV
}
```
---
10. Write a Powershell script and a Bash script that generate a self-signed SSL certificate
Bash
```
#!/bin/bash
# Write a Powershell script and a Bash script that generate a self-signed SSL certificate
DOMAIN="$1"
if [ -z "$DOMAIN" ]; then
echo "Usage: $(basename $0) <domain>"
exit 11
fi
fail_if_error() {
[ $1 != 0 ] && {
unset PASSPHRASE
exit 10
}
}
# Generate a passphrase
export PASSPHRASE=$(head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 128; echo)
# Certificate details; replace items in angle brackets with your own info
subj="
C=US
ST=OR
O=Blah
localityName=vietnam
commonName=$DOMAIN
organizationalUnitName=Blah
emailAddress=admin@example.com
"
# Generate the server private key
openssl genrsa -des3 -out $DOMAIN.key -passout env:PASSPHRASE 2048
fail_if_error $?
# Generate the CSR
openssl req \
-new \
-batch \
-subj "$(echo -n "$subj" | tr "\n" "/")" \
-key $DOMAIN.key \
-out $DOMAIN.csr \
-passin env:PASSPHRASE
fail_if_error $?
cp $DOMAIN.key $DOMAIN.key.org
fail_if_error $?
# Strip the password so we don't have to type it every time we restart Apache
openssl rsa -in $DOMAIN.key.org -out $DOMAIN.key -passin env:PASSPHRASE
fail_if_error $?
# Generate the cert (good for 10 years)
openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt
fail_if_error $?
## Read the key below
echo "-----KEY GENERATE----"
cat $DOMAIN.key
```
![](https://i.imgur.com/SJFOxCF.png)
![](https://i.imgur.com/BaBKkEV.png)
![](https://i.imgur.com/7p2Lc7w.png)
Powershell
```
#!/usr/bin/env pwsh
# Write a Powershell script and a Bash script that generate a self-signed SSL certificate
param([switch]$Elevated)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated) {
# tried to elevate, did not work, aborting
exit 1
} else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
$dns = Read-Host -prompt "What is the name of the domain u want to generate a self-signed SSL certificate"
$location = Read-Host -prompt "Where is the location to store the certificate"
New-SelfSignedCertificate -DnsName $dns -CertStoreLocation $location
```
![](https://i.imgur.com/W9GP8ua.png)
![](https://i.imgur.com/H2YYFqC.png)
## Conclusion
## Reference
[Bash Assign Output of Shell Command To Variable](https://www.cyberciti.biz/faq/unix-linux-bsd-appleosx-bash-assign-variable-command-output/)
[Using Bash's regular expressions](https://www.networkworld.com/article/2693361/unix-tip-using-bash-s-regular-expressions.html)
[if-else statement in bash](https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php)
[Basic operators](https://www.geeksforgeeks.org/basic-operators-in-shell-scripting/)
[Bash while loop](https://www.cyberciti.biz/faq/bash-while-loop/)
[How To Check If File or Directory Exists in Bash](https://devconnected.com/how-to-check-if-file-or-directory-exists-in-bash/#:~:text=your%20Bash%20shell.-,In%20order%20to%20check%20if%20a%20file%20exists%20in%20Bash,echo%20%22This%20file%20exists!%22&text=%5B%5B%20%2Df%20%2Fetc%2Fpasswd,echo%20%22This%20file%20exists!%22)
[How To Convert String To Script Block Using PowerShell](https://www.improvescripting.com/how-to-convert-string-to-script-block-using-powershell/)
[Execuatable Powershell Script with native string](https://stackoverflow.com/questions/6338015/how-do-you-execute-an-arbitrary-native-command-from-a-string)
[How To Get Detailed Information on Your Server's Processes with PowerShell](https://redmondmag.com/articles/2016/11/17/get-info-on-server-processes.aspx)
[Stdin-stdout-stderr in linux](https://khaidantri.net/stdin-stdout-va-stderr-tren-linux-la-gi)
[Try&Catch](https://stackoverflow.com/questions/22009364/is-there-a-try-catch-command-in-bash)