6.11 Basic Shell Scripting
Script mhanje tumhala already yenare commands ek file madhe. Hech automation chi pahili payri – aani security tools pan asech lihile jatat.
#!/bin/bash
# file: sysinfo.sh - print a quick health report
set -uo pipefail # stop on undefined variables and pipe failures
NAME=$(hostname)
echo "Health report for $NAME at $(date)"
echo "---------------------------------"
echo "Uptime : $(uptime -p)"
echo "Disk / : $(df -h / | awk 'NR==2 {print $5 " used"}')"
echo "Memory : $(free -m | awk '/Mem/ {printf "%d/%d MB used", $3, $2}')"
# if-else
if systemctl is-active --quiet nginx; then
echo "Nginx : running"
else
echo "Nginx : NOT running"
fi
# loop
for svc in sshd crond; do
echo "$svc -> $(systemctl is-active $svc 2>/dev/null)"
done
# function with argument
check_port() {
if ss -tln | grep -q ":$1 "; then echo "Port $1 open"; else echo "Port $1 closed"; fi
}
check_port 22
check_port 80
nano sysinfo.sh # paste the script, save with Ctrl+O, exit with Ctrl+X
chmod +x sysinfo.sh
./sysinfo.sh
| Concept | Syntax |
|---|---|
| Variable | NAME="Ruhi", use $NAME or ${NAME} (no spaces around =) |
| Command output | TODAY=$(date +%F) |
| Arguments | $1, $2, all: $@, count: $# |
| Exit status of last command | $? (0 = success) |
| Test file exists | if [ -f /etc/nginx/nginx.conf ]; then ... fi |
| Test directory | [ -d /var/www ] |
| Compare numbers | [ "$a" -gt 10 ] (-eq -ne -lt -le -ge) |
| Compare strings | [ "$a" = "yes" ] |
| Read input | read -p "Enter name: " NAME |
Ravindra Bagale's Tip
Many students write a variable with spaces, like NAME = "Raja" – bash thinks it's a command and gives an error. There must be no space on either side of =. And always use variables inside double quotes: "$NAME".
Ravindra Bagale's Tip – मराठी
Variable लिहिताना NAME = "Raja" असा space ठेवणारे बरेच students आहेत – bash ला ते command वाटतं आणि error येतो. = च्या दोन्ही बाजूला space नको. आणि variable नेहमी double quotes मध्ये वापरा: "$NAME".
Ravindra Bagale's Tip – हिंदी
बहुत से students variable लिखते समय NAME = "Raja" जैसा space रख देते हैं – bash को यह command लगता है और error आता है. = के दोनों तरफ़ space नहीं होना चाहिए. और variable हमेशा double quotes में इस्तेमाल करो: "$NAME".
Lab
Write sshwatch.sh that prints the number of failed SSH logins today and the top three source IPs (use journalctl or auth.log, grep, awk, sort, uniq -c). Make it executable and run it.
Thodkyaat sangaycha tar
- Search:
grep -i/-r/-v/-E,findby name, size, time, permission. - Process text:
awkfor columns,sedfor replace (test before-i). - Combine with pipes;
>overwrites,>>appends;sudo teefor root files. - Services:
sudo service <name> start|stop|restart|reload|status; boot:sudo systemctl enable; logs:journalctl -u. - Network:
ip a,ss -tulnp,curl -I,dig,nc -zv. Disk:df -h,du -sh,lsblk. - Cron schedules jobs (and attackers abuse it for persistence).
ssh/scp/rsyncfor remote work.
Samjla ka? Linux aata tumcha haath aahe. Part 2 sampla – aata pudhe jaauya web servers kade!