리눅스 조건 테스트

LinuxBeginner
지금 연습하기

소개

이 랩에서는 Linux 조건 테스트를 사용하여 시스템 검사 및 유효성 검사를 자동화하는 방법을 배우게 됩니다. Linux 는 조건 평가 및 결과에 따라 작업을 실행할 수 있는 강력한 test 명령을 제공합니다. 이 명령을 사용하는 방법을 이해하는 것은 결정을 내리고 다양한 조건에 대응할 수 있는 쉘 스크립트를 작성하는 데 필수적입니다.

이 랩을 통해 파일 테스트, 문자열 비교 및 숫자 평가를 포함하여 test 명령의 다양한 측면을 다루게 됩니다. 이 세션이 끝나면 시스템에서 자동화된 검사를 수행하고 무결성을 유지하는 데 도움이 되는 스크립트를 작성할 수 있게 됩니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 초급 레벨의 실험이며 완료율은 81%입니다.학습자들로부터 98%의 긍정적인 리뷰율을 받았습니다.

test 명령어 기본 이해

Linux 의 test 명령은 쉘 스크립트에서 조건을 평가하는 데 중요한 도구입니다. 파일 속성을 확인하고, 문자열을 비교하고, 숫자 값을 평가하는 등의 작업을 수행할 수 있습니다. 테스트 중인 조건이 참이면 test는 0 의 종료 상태를 반환하고, 그렇지 않으면 0 이 아닌 종료 상태를 반환합니다.

기본 사항부터 시작해 보겠습니다. 먼저, 프로젝트 디렉토리로 이동합니다.

cd ~/project

test 명령은 두 가지 방법으로 작성할 수 있습니다.

  1. test 단어 다음에 조건을 사용합니다.
  2. 조건 주위에 대괄호 [ ]를 사용합니다.

두 가지 방법을 모두 사용하여 디렉토리가 존재하는지 확인해 보겠습니다.

## Method 1: Using the word 'test'
test -d ~/project && echo "The project directory exists."

## Method 2: Using square brackets
[ -d ~/project ] && echo "The project directory exists."

두 명령 모두 다음 출력을 볼 수 있습니다.

The project directory exists.

-d 옵션은 디렉토리가 존재하는지 확인합니다. && 연산자는 테스트 조건이 참인 경우에만 echo 명령을 실행하는 데 사용됩니다.

일부 일반적인 파일 테스트 옵션은 다음과 같습니다.

  • -d file: 파일이 존재하고 디렉토리인 경우 참
  • -e file: 파일이 존재하는 경우 참
  • -f file: 파일이 존재하고 일반 파일인 경우 참
  • -r file: 파일이 존재하고 읽을 수 있는 경우 참
  • -w file: 파일이 존재하고 쓸 수 있는 경우 참
  • -x file: 파일이 존재하고 실행 가능한 경우 참
  • -s file: 파일이 존재하고 크기가 0 보다 큰 경우 참

테스트 파일을 만들고 속성을 확인해 보겠습니다.

## Create a test file
echo "Hello, Linux condition testing!" > test_file.txt

## Check if the file exists
test -e test_file.txt && echo "The file exists."

## Check if the file is readable
[ -r test_file.txt ] && echo "The file is readable."

## Check if the file is empty
[ -s test_file.txt ] && echo "The file is not empty."

이러한 명령은 다음 출력을 생성해야 합니다.

The file exists.
The file is readable.
The file is not empty.

이제 test 명령을 사용하여 파일이 존재하는지 확인하고, 존재하지 않으면 파일을 생성하는 간단한 쉘 스크립트를 만들어 보겠습니다.

## Create a script file
cat > check_file.sh << 'EOF'
#!/bin/bash

FILENAME="status.txt"

if [ ! -e "$FILENAME" ]; then
  echo "File $FILENAME does not exist. Creating it now."
  echo "This is a status file." > "$FILENAME"
else
  echo "File $FILENAME already exists."
fi

## Display file content
echo "Content of $FILENAME:"
cat "$FILENAME"
EOF

## Make the script executable
chmod +x check_file.sh

## Run the script
./check_file.sh

스크립트를 실행하면 다음과 유사한 출력을 볼 수 있습니다.

File status.txt does not exist. Creating it now.
Content of status.txt:
This is a status file.

스크립트를 다시 실행하면 다음을 볼 수 있습니다.

File status.txt already exists.
Content of status.txt:
This is a status file.

이것은 test 명령을 사용하여 파일 존재 여부를 확인하고 결과에 따라 다른 작업을 수행하는 방법을 보여줍니다.

문자열 조건 테스트

이 단계에서는 test 명령을 사용하여 문자열을 비교하는 방법을 배우게 됩니다. 이는 사용자 입력을 검증하고, 환경 변수를 확인하거나, 텍스트 내용을 기반으로 결정을 내릴 때 유용합니다.

일반적인 문자열 비교 연산자는 다음과 같습니다.

  • ==: 같음
  • !=: 같지 않음
  • -z: 문자열이 비어 있으면 참
  • -n: 문자열이 비어 있지 않으면 참

다양한 문자열 조건을 테스트해 보겠습니다.

## Test if two strings are equal
str1="linux"
str2="linux"
[ "$str1" == "$str2" ] && echo "The strings are equal."

## Test if two strings are different
str3="ubuntu"
[ "$str1" != "$str3" ] && echo "The strings are different."

## Test if a string is empty
empty_str=""
[ -z "$empty_str" ] && echo "The string is empty."

## Test if a string is not empty
[ -n "$str1" ] && echo "The string is not empty."

출력은 다음과 같아야 합니다.

The strings are equal.
The strings are different.
The string is empty.
The string is not empty.

이제 비밀번호를 요청하고 특정 기준을 충족하는지 확인하는 스크립트를 만들어 보겠습니다.

## Create a password validation script
cat > password_check.sh << 'EOF'
#!/bin/bash

echo "Enter a password:"
read -s password

## Check if password is empty
if [ -z "$password" ]; then
  echo "Error: Password cannot be empty."
  exit 1
fi

## Check password length
if [ ${#password} -lt 8 ]; then
  echo "Error: Password must be at least 8 characters long."
  exit 1
fi

## Check if password contains the word "password"
if [[ "$password" == *password* ]]; then
  echo "Error: Password cannot contain the word 'password'."
  exit 1
fi

echo "Password is valid!"
EOF

## Make the script executable
chmod +x password_check.sh

## Run the script
echo "You can test the script by running: ./password_check.sh"

다양한 비밀번호로 스크립트를 실행하여 입력이 어떻게 검증되는지 확인해 보세요.

## Test with a short password
echo "short" | ./password_check.sh

## Test with a password containing "password"
echo "mypassword123" | ./password_check.sh

## Test with a valid password
echo "SecurePass123" | ./password_check.sh

처음 두 테스트는 실패해야 하고, 세 번째 테스트는 성공해야 합니다.

텍스트 입력을 기반으로 시스템 상태를 처리하는 다른 스크립트를 만들어 보겠습니다.

## Create a system status script
cat > system_status.sh << 'EOF'
#!/bin/bash

echo "Enter system status (normal, warning, critical):"
read status

if [ -z "$status" ]; then
  echo "No status provided. Assuming normal operation."
  status="normal"
fi

case "$status" in
  "normal")
    echo "System is operating normally. No action required."
    ;;
  "warning")
    echo "Warning: System requires attention. Check log files."
    ;;
  "critical")
    echo "CRITICAL: Immediate action required! System stability at risk."
    ;;
  *)
    echo "Unknown status: $status. Please use normal, warning, or critical."
    ;;
esac
EOF

## Make the script executable
chmod +x system_status.sh

## Run the script
echo "You can test the script by running: ./system_status.sh"

다양한 상태 입력을 사용하여 스크립트를 실행해 보세요.

## Test with "normal" status
echo "normal" | ./system_status.sh

## Test with "warning" status
echo "warning" | ./system_status.sh

## Test with "critical" status
echo "critical" | ./system_status.sh

## Test with an invalid status
echo "unstable" | ./system_status.sh

## Test with empty input
echo "" | ./system_status.sh

각 입력은 스크립트의 조건부 로직에 따라 다른 출력을 생성해야 합니다.

숫자 조건 테스트

이 단계에서는 숫자 비교를 위해 test 명령을 사용하는 방법을 배우게 됩니다. 이는 리소스 사용량을 확인하고, 사용자 입력을 검증하거나, 숫자 값을 기반으로 결정을 내릴 때 유용합니다.

일반적인 숫자 비교 연산자는 다음과 같습니다.

  • -eq: 같음 (Equal to)
  • -ne: 같지 않음 (Not equal to)
  • -lt: 작음 (Less than)
  • -le: 작거나 같음 (Less than or equal to)
  • -gt: 큼 (Greater than)
  • -ge: 크거나 같음 (Greater than or equal to)

몇 가지 기본적인 숫자 비교부터 시작해 보겠습니다.

## Compare two numbers
num1=10
num2=20

## Equal to
[ $num1 -eq 10 ] && echo "$num1 is equal to 10"

## Not equal to
[ $num1 -ne $num2 ] && echo "$num1 is not equal to $num2"

## Less than
[ $num1 -lt $num2 ] && echo "$num1 is less than $num2"

## Greater than
[ $num2 -gt $num1 ] && echo "$num2 is greater than $num1"

## Less than or equal to
[ $num1 -le 10 ] && echo "$num1 is less than or equal to 10"

## Greater than or equal to
[ $num2 -ge 20 ] && echo "$num2 is greater than or equal to 20"

출력은 다음과 같아야 합니다.

10 is equal to 10
10 is not equal to 20
10 is less than 20
20 is greater than 10
10 is less than or equal to 10
20 is greater than or equal to 20

이제 디스크 공간을 확인하고 특정 임계값 미만일 때 경고하는 스크립트를 만들어 보겠습니다.

## Create a disk space check script
cat > disk_check.sh << 'EOF'
#!/bin/bash

## Get disk usage percentage (removing the % sign)
DISK_USAGE=$(df -h / | grep / | awk '{print $5}' | sed 's/%//')

## Set thresholds
WARNING_THRESHOLD=70
CRITICAL_THRESHOLD=90

echo "Current disk usage: $DISK_USAGE%"

if [ $DISK_USAGE -ge $CRITICAL_THRESHOLD ]; then
  echo "CRITICAL: Disk usage is critically high!"
  echo "Action: Clean up unnecessary files immediately."
elif [ $DISK_USAGE -ge $WARNING_THRESHOLD ]; then
  echo "WARNING: Disk usage is getting high."
  echo "Action: Consider cleaning up some files soon."
else
  echo "OK: Disk usage is normal."
  echo "No action required."
fi
EOF

## Make the script executable
chmod +x disk_check.sh

## Run the script
./disk_check.sh

이 스크립트는 현재 디스크 사용량을 표시하고 디스크가 얼마나 찼는지에 따라 다른 메시지를 출력합니다.

온도 모니터링 시스템을 시뮬레이션하는 다른 스크립트를 만들어 보겠습니다.

## Create a temperature monitoring script
cat > temp_monitor.sh << 'EOF'
#!/bin/bash

## Function to generate a random temperature between 15 and 35
generate_temp() {
  echo $((RANDOM % 21 + 15))
}

## Generate random temperature
TEMP=$(generate_temp)
echo "Current temperature: ${TEMP}°C"

## Temperature thresholds
MIN_TEMP=18
MAX_TEMP=26

if [ $TEMP -lt $MIN_TEMP ]; then
  echo "Action: Increase heating. Temperature is below minimum threshold."
elif [ $TEMP -gt $MAX_TEMP ]; then
  echo "Action: Activate cooling. Temperature is above maximum threshold."
else
  echo "Status: Temperature is within acceptable range."
fi

## Additional check for extreme temperatures
if [ $TEMP -ge 30 ]; then
  echo "WARNING: Temperature is very high. Check cooling systems."
fi
if [ $TEMP -le 17 ]; then
  echo "WARNING: Temperature is very low. Check heating systems."
fi
EOF

## Make the script executable
chmod +x temp_monitor.sh

## Run the script
./temp_monitor.sh

이 스크립트를 실행할 때마다 임의의 온도를 생성하고 그에 따라 응답합니다. 여러 번 실행하여 다른 결과를 확인해 보세요.

## Run the temperature monitor script multiple times
./temp_monitor.sh
./temp_monitor.sh
./temp_monitor.sh

이러한 예제는 숫자 조건을 사용하여 시스템 매개변수를 모니터링하고 임계값 값을 기반으로 적절한 조치를 취하는 방법을 보여줍니다.

논리 연산자를 사용한 조건 결합

이 단계에서는 논리 연산자를 사용하여 여러 조건을 결합하는 방법을 배우게 됩니다. 이는 스크립트에서 복잡한 의사 결정 로직을 생성하는 데 필수적입니다.

세 가지 주요 논리 연산자는 다음과 같습니다.

  • && (AND): 두 조건이 모두 참이면 참
  • || (OR): 최소한 하나의 조건이 참이면 참
  • ! (NOT): 조건이 거짓이면 참

몇 가지 기본 예제부터 시작해 보겠습니다.

## Create a test file
touch test_file.txt
chmod 644 test_file.txt

## AND operator - both conditions must be true
[ -f test_file.txt ] && [ -r test_file.txt ] && echo "The file exists and is readable."

## OR operator - at least one condition must be true
[ -x test_file.txt ] || [ -w test_file.txt ] && echo "The file is either executable or writable."

## NOT operator - inverts the condition
[ ! -x test_file.txt ] && echo "The file is not executable."

## Combining multiple operators
[ -f test_file.txt ] && [ -r test_file.txt ] && [ ! -x test_file.txt ] && echo "The file exists, is readable, but is not executable."

다음과 유사한 출력을 볼 수 있습니다.

The file exists and is readable.
The file is either executable or writable.
The file is not executable.
The file exists, is readable, but is not executable.

test 명령은 또한 이러한 연산자를 사용하여 단일 괄호 세트 내에서 조건을 결합할 수 있습니다.

  • -a (AND)
  • -o (OR)

예를 들어:

## AND within a single test command
[ -f test_file.txt -a -r test_file.txt ] && echo "The file exists and is readable."

## OR within a single test command
[ -x test_file.txt -o -w test_file.txt ] && echo "The file is either executable or writable."

시스템 리소스를 확인하는 더 복잡한 스크립트를 만들어 보겠습니다.

## Create a system resource check script
cat > resource_check.sh << 'EOF'
#!/bin/bash

echo "Checking system resources..."

## Check memory usage
MEM_THRESHOLD=80
MEM_USED=$(free | grep Mem | awk '{print int($3/$2 * 100)}')

echo "Memory usage: ${MEM_USED}%"

## Check disk space
DISK_THRESHOLD=70
DISK_USED=$(df -h / | grep / | awk '{print $5}' | sed 's/%//')

echo "Disk usage: ${DISK_USED}%"

## Check CPU load (1-minute average)
LOAD_THRESHOLD=1.0
CPU_LOAD=$(cat /proc/loadavg | awk '{print $1}')

echo "CPU load average: ${CPU_LOAD}"

## Combined condition checking
if [ $MEM_USED -gt $MEM_THRESHOLD ] && [ $DISK_USED -gt $DISK_THRESHOLD ]; then
  echo "CRITICAL: Both memory and disk usage are high!"
  echo "Action: Free up resources immediately."
elif [ $MEM_USED -gt $MEM_THRESHOLD ] || [ $DISK_USED -gt $DISK_THRESHOLD ]; then
  echo "WARNING: Either memory or disk usage is high."
  echo "Action: Monitor system closely."
else
  echo "OK: Memory and disk usage are within acceptable limits."
fi

## Check if load is numeric before comparing
if [[ $CPU_LOAD =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
  ## We need to use bc for floating point comparison
  if (( $(echo "$CPU_LOAD > $LOAD_THRESHOLD" | bc -l) )); then
    echo "WARNING: CPU load is high. Check for resource-intensive processes."
  else
    echo "OK: CPU load is normal."
  fi
else
  echo "Error: Could not parse CPU load value."
fi
EOF

## Make the script executable
chmod +x resource_check.sh

## Run the script
./resource_check.sh

이 스크립트는 메모리 사용량, 디스크 공간 및 CPU 부하를 확인한 다음 이러한 조건의 조합을 기반으로 다른 출력을 제공합니다.

마지막으로, 여러 조건으로 사용자 입력을 검증하는 스크립트를 만들어 보겠습니다.

## Create an input validation script
cat > validate_input.sh << 'EOF'
#!/bin/bash

echo "Enter a username (lowercase letters only, 3-8 characters):"
read username

echo "Enter your age (must be 18 or older):"
read age

## Username validation
is_valid_username=true

## Check if username is empty
if [ -z "$username" ]; then
  echo "Error: Username cannot be empty."
  is_valid_username=false
fi

## Check username length
if [ ${#username} -lt 3 ] || [ ${#username} -gt 8 ]; then
  echo "Error: Username must be between 3 and 8 characters."
  is_valid_username=false
fi

## Check if username contains only lowercase letters
if [[ ! "$username" =~ ^[a-z]+$ ]]; then
  echo "Error: Username must contain only lowercase letters."
  is_valid_username=false
fi

## Age validation
is_valid_age=true

## Check if age is a number
if [[ ! "$age" =~ ^[0-9]+$ ]]; then
  echo "Error: Age must be a number."
  is_valid_age=false
fi

## Check if age is at least 18
if [ "$is_valid_age" = true ] && [ $age -lt 18 ]; then
  echo "Error: You must be at least 18 years old."
  is_valid_age=false
fi

## Final validation
if [ "$is_valid_username" = true ] && [ "$is_valid_age" = true ]; then
  echo "Registration successful!"
  echo "Welcome, $username. Your account has been created."
else
  echo "Registration failed. Please correct the errors and try again."
fi
EOF

## Make the script executable
chmod +x validate_input.sh

## Run the script
echo "You can test the script by running: ./validate_input.sh"

다양한 입력을 사용하여 스크립트를 실행하여 결합된 조건이 사용자 입력을 검증하기 위해 어떻게 함께 작동하는지 확인해 보세요.

## Test with valid input
echo -e "john\n25" | ./validate_input.sh

## Test with invalid username (too short)
echo -e "jo\n25" | ./validate_input.sh

## Test with invalid username (contains uppercase)
echo -e "John\n25" | ./validate_input.sh

## Test with invalid age (under 18)
echo -e "john\n17" | ./validate_input.sh

## Test with invalid age (not a number)
echo -e "john\nabc" | ./validate_input.sh

이러한 예제는 스크립트에서 복잡한 유효성 검사 로직을 생성하기 위해 여러 조건을 결합하는 방법을 보여줍니다.

종합 시스템 모니터링 스크립트 생성

이 마지막 단계에서는 지금까지 배운 모든 것을 결합하여 포괄적인 시스템 모니터링 스크립트를 만들 것입니다. 이 스크립트는 다양한 시스템 매개변수를 확인하고 요약 보고서를 제공합니다.

여러 시스템 측면을 모니터링하는 스크립트를 만들어 보겠습니다.

## Create a system monitoring script
cat > system_monitor.sh << 'EOF'
#!/bin/bash

echo "========================================"
echo "    System Monitoring Report"
echo "    $(date)"
echo "========================================"
echo

## 1. Check if important system files exist
echo "1. System Files Check:"
important_files=("/etc/passwd" "/etc/hosts" "/etc/resolv.conf")
all_files_exist=true

for file in "${important_files[@]}"; do
  if [ -e "$file" ]; then
    echo "   [OK] $file exists"
    
    ## Check if file is empty
    if [ ! -s "$file" ]; then
      echo "   [WARNING] $file is empty"
    fi
    
    ## Check if file is readable
    if [ ! -r "$file" ]; then
      echo "   [WARNING] $file is not readable"
    fi
  else
    echo "   [ERROR] $file does not exist"
    all_files_exist=false
  fi
done

if [ "$all_files_exist" = true ]; then
  echo "   All system files are present."
else
  echo "   Some system files are missing. Check the errors above."
fi
echo

## 2. Check disk space
echo "2. Disk Space Check:"
disk_usage=$(df -h / | grep / | awk '{print $5}' | sed 's/%//')
echo "   Root partition usage: ${disk_usage}%"

if [ $disk_usage -ge 90 ]; then
  echo "   [CRITICAL] Disk usage is critically high!"
elif [ $disk_usage -ge 70 ]; then
  echo "   [WARNING] Disk usage is getting high."
else
  echo "   [OK] Disk usage is normal."
fi
echo

## 3. Check memory usage
echo "3. Memory Usage Check:"
mem_total=$(free -m | grep Mem | awk '{print $2}')
mem_used=$(free -m | grep Mem | awk '{print $3}')
mem_percentage=$((mem_used * 100 / mem_total))

echo "   Memory usage: ${mem_percentage}% (${mem_used}MB used out of ${mem_total}MB)"

if [ $mem_percentage -ge 90 ]; then
  echo "   [CRITICAL] Memory usage is critically high!"
elif [ $mem_percentage -ge 70 ]; then
  echo "   [WARNING] Memory usage is getting high."
else
  echo "   [OK] Memory usage is normal."
fi
echo

## 4. Check for active processes
echo "4. Process Check:"
critical_processes=("sshd" "cron")
for process in "${critical_processes[@]}"; do
  if pgrep -x "$process" > /dev/null; then
    echo "   [OK] $process is running"
  else
    echo "   [ERROR] $process is not running"
  fi
done
echo

## 5. Check system load
echo "5. System Load Check:"
load_1min=$(cat /proc/loadavg | awk '{print $1}')
load_5min=$(cat /proc/loadavg | awk '{print $2}')
load_15min=$(cat /proc/loadavg | awk '{print $3}')

echo "   Load average: $load_1min (1 min), $load_5min (5 min), $load_15min (15 min)"

## Determine number of CPU cores
num_cores=$(grep -c ^processor /proc/cpuinfo)
load_threshold=$(echo "scale=2; $num_cores * 0.7" | bc)

if (( $(echo "$load_1min > $load_threshold" | bc -l) )); then
  echo "   [WARNING] High load detected. The system might be under stress."
else
  echo "   [OK] System load is normal."
fi
echo

## 6. Check for recent failed login attempts
echo "6. Security Check:"
if [ -f /var/log/auth.log ]; then
  failed_logins=$(grep "Failed password" /var/log/auth.log | wc -l)
  echo "   Failed login attempts: $failed_logins"
  
  if [ $failed_logins -gt 10 ]; then
    echo "   [WARNING] High number of failed login attempts detected."
  else
    echo "   [OK] Normal login activity."
  fi
else
  echo "   [INFO] Cannot check login attempts (auth.log not accessible)"
fi
echo

## 7. Summary
echo "7. System Status Summary:"
critical_count=$(grep -c "\[CRITICAL\]" <<< "$(cat /dev/stdin)")
warning_count=$(grep -c "\[WARNING\]" <<< "$(cat /dev/stdin)")
error_count=$(grep -c "\[ERROR\]" <<< "$(cat /dev/stdin)")

if [ $critical_count -gt 0 ]; then
  echo "   [CRITICAL] System has critical issues that need immediate attention!"
elif [ $warning_count -gt 0 ] || [ $error_count -gt 0 ]; then
  echo "   [WARNING] System has some issues that should be addressed soon."
else
  echo "   [OK] System is operating normally. No significant issues detected."
fi

echo
echo "========================================"
echo "    End of System Monitoring Report"
echo "========================================"
EOF

## Make the script executable
chmod +x system_monitor.sh

## Run the script
./system_monitor.sh

이 포괄적인 스크립트는 다음 검사를 수행합니다.

  1. 중요한 시스템 파일이 있는지 확인하고 읽을 수 있는지 확인합니다.
  2. 디스크 공간 사용량을 확인합니다.
  3. 메모리 사용량을 모니터링합니다.
  4. 중요한 프로세스가 실행 중인지 확인합니다.
  5. 시스템 부하를 평가합니다.
  6. 실패한 로그인 시도를 위해 보안 로그를 검사합니다.
  7. 전반적인 시스템 상태 요약을 제공합니다.

출력은 시스템의 현재 상태에 따라 다르지만 시스템의 상태에 대한 포괄적인 개요를 제공합니다.

이 스크립트를 더욱 유용하게 만들려면 다음을 수행할 수 있습니다.

  1. cron 을 사용하여 정기적으로 실행하도록 예약합니다.
  2. 중요한 문제가 감지되면 이메일을 통해 알림을 보내도록 구성합니다.
  3. 시스템과 관련된 더 구체적인 검사를 추가합니다.

정기적으로 실행하도록 예약할 수 있는 더 간단한 버전을 만들어 보겠습니다.

## Create a simplified monitoring script for scheduling
cat > daily_check.sh << 'EOF'
#!/bin/bash

## Set up log file
LOG_FILE="/tmp/system_check_$(date +%Y%m%d).log"

## Start logging
echo "System Check: $(date)" > $LOG_FILE
echo "--------------------------------" >> $LOG_FILE

## Check disk space
disk_usage=$(df -h / | grep / | awk '{print $5}' | sed 's/%//')
echo "Disk usage: ${disk_usage}%" >> $LOG_FILE

if [ $disk_usage -ge 90 ]; then
  echo "CRITICAL: Disk usage is critically high!" >> $LOG_FILE
elif [ $disk_usage -ge 70 ]; then
  echo "WARNING: Disk usage is getting high." >> $LOG_FILE
else
  echo "OK: Disk usage is normal." >> $LOG_FILE
fi

## Check memory
mem_total=$(free -m | grep Mem | awk '{print $2}')
mem_used=$(free -m | grep Mem | awk '{print $3}')
mem_percentage=$((mem_used * 100 / mem_total))
echo "Memory usage: ${mem_percentage}%" >> $LOG_FILE

if [ $mem_percentage -ge 90 ]; then
  echo "CRITICAL: Memory usage is critically high!" >> $LOG_FILE
elif [ $mem_percentage -ge 70 ]; then
  echo "WARNING: Memory usage is getting high." >> $LOG_FILE
else
  echo "OK: Memory usage is normal." >> $LOG_FILE
fi

## Check for critical services
for service in sshd cron; do
  if pgrep -x "$service" > /dev/null; then
    echo "$service is running" >> $LOG_FILE
  else
    echo "WARNING: $service is not running" >> $LOG_FILE
  fi
done

## End log
echo "--------------------------------" >> $LOG_FILE
echo "Check completed at $(date)" >> $LOG_FILE

## Display log location
echo "System check completed. Log saved to $LOG_FILE"
EOF

## Make the script executable
chmod +x daily_check.sh

## Run the script
./daily_check.sh

이 스크립트를 매일 실행하도록 예약하려면 일반적으로 cron 시스템을 사용합니다. 설정 방법은 다음과 같습니다.

## Show how to set up a cron job (don't actually create it in this lab environment)
echo "To schedule this script to run daily at 9 AM, you would use:"
echo "crontab -e"
echo "And add the line:"
echo "0 9 * * * /home/labex/project/daily_check.sh"

이것은 배운 Linux 조건 테스트 명령을 실용적인 시스템 모니터링 도구를 만드는 데 적용할 수 있는 방법을 보여줍니다.

요약

이 랩에서는 Linux 조건 테스트를 사용하여 다양한 유형의 조건을 평가하고 결과에 따라 결정을 내리는 방법을 배웠습니다. 다음은 수행한 작업에 대한 요약입니다.

  1. test 명령의 기본 사항과 존재 여부, 읽기 가능성 및 크기와 같은 파일 속성을 확인하는 방법을 배웠습니다.

  2. ==, !=, -z, -n과 같은 연산자를 사용하여 문자열 비교를 탐색하여 입력을 검증하고 텍스트 내용을 기반으로 결정을 내렸습니다.

  3. -eq, -ne, -lt, -gt, -le, -ge와 같은 연산자를 사용하여 숫자 값을 평가하는 숫자 비교를 사용했습니다.

  4. 논리 연산자 (&&, ||, !) 를 사용하여 여러 조건을 결합하여 복잡한 의사 결정 로직을 만들었습니다.

  5. 이러한 모든 기술을 적용하여 다양한 시스템 매개변수를 확인하고 상태 보고서를 제공할 수 있는 포괄적인 시스템 모니터링 스크립트를 만들었습니다.

이러한 기술은 Linux 에서 셸 스크립팅 및 시스템 관리에 필수적입니다. 조건을 테스트하고 결과에 따라 다른 작업을 수행하는 기능은 작업을 자동화하고, 입력을 검증하고, 오류를 처리하고, 시스템 상태를 모니터링할 수 있는 스크립트를 만들 수 있도록 해줍니다.

배운 내용의 몇 가지 실용적인 응용 프로그램은 다음과 같습니다.

  • 진행하기 전에 사용 가능한 공간을 확인하는 자동 백업 스크립트 생성
  • 사용자 대상 스크립트에 대한 입력 유효성 검사 개발
  • 잠재적인 문제에 대해 관리자에게 알리는 시스템 모니터링 도구 구축
  • 조건부 로직을 사용하여 일상적인 시스템 유지 관리 작업 자동화

Linux 를 계속 사용하면서 조건 테스트가 생성하거나 유지 관리하는 거의 모든 셸 스크립트의 필수적인 부분임을 알게 될 것입니다.