2025年7月16日 星期三

[shell script] 建立一個瀏覽每位使用者的網頁,使用者的網頁在user/www/的目錄下

方法一:使用 awk 生成 HTML 頁面


 

awk -F: 'BEGIN{
    print "User Directory"
    print "

User Web Pages

    " } { if($1 !~ /^#/ && $7 != "/usr/sbin/nologin" && $7 != "/bin/false") { printf "
  • %s - %s
  • \n", $1, $1, $5 } } END{ print "
" }' /etc/passwd > user_directory.html

方法二:使用 awk 生成 HTML 頁面

#!/bin/bash


# 生成使用者網頁目錄的 HTML 頁面

OUTPUT_FILE="user_directory.html"

WWW_DIR="user/www"


# 開始 HTML 結構

cat > "$OUTPUT_FILE" << 'EOF'

<!DOCTYPE html>

<html lang="zh-TW">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>使用者網頁目錄</title>

    <style>

        body { font-family: Arial, sans-serif; margin: 20px; }

        .user-list { list-style-type: none; padding: 0; }

        .user-item { 

            margin: 10px 0; 

            padding: 10px; 

            border: 1px solid #ddd; 

            border-radius: 5px; 

        }

        .user-item a { 

            text-decoration: none; 

            color: #0066cc; 

            font-weight: bold; 

        }

        .user-item a:hover { text-decoration: underline; }

        .user-info { color: #666; margin-left: 10px; }

    </style>

</head>

<body>

    <h1>使用者網頁目錄</h1>

    <ul class="user-list">

EOF


# 處理 /etc/passwd 檔案,生成使用者連結

while IFS=: read -r username password uid gid gecos home shell; do

    # 跳過註解行和系統帳號

    if [[ ! "$username" =~ ^# ]] && [[ "$uid" -ge 1000 ]] && [[ "$shell" != "/usr/sbin/nologin" ]] && [[ "$shell" != "/bin/false" ]]; then

        # 檢查使用者網頁目錄是否存在

        if [[ -d "$WWW_DIR/$username" ]]; then

            status="✓ 網頁存在"

            link_class="active"

        else

            status="✗ 網頁不存在"

            link_class="inactive"

        fi

        

        # 生成 HTML 項目

        cat >> "$OUTPUT_FILE" << EOF

        <li class="user-item">

            <a href="$WWW_DIR/$username" target="_blank" class="$link_class">$username</a>

            <span class="user-info">- $gecos ($status)</span>

        </li>

EOF

    fi

done < /etc/passwd


# 結束 HTML 結構

cat >> "$OUTPUT_FILE" << 'EOF'

    </ul>

    <hr>

    <p><small>生成時間: $(date)</small></p>

</body>

</html>

EOF


# 替換日期

sed -i "s/\$(date)/$(date)/" "$OUTPUT_FILE"


echo "使用者目錄頁面已生成:$OUTPUT_FILE"

echo "可用瀏覽器開啟查看"

沒有留言:

熱門文章