https://github.com/nayeo2/KDT_2nd_log_shell
GitHub - nayeo2/KDT_2nd_log_shell
Contribute to nayeo2/KDT_2nd_log_shell development by creating an account on GitHub.
github.com
- 깃에서 shell script 클론 > 젠킨스에서 웹 서버에 해당 sh들 배포 후 실행 > 실행된 후 Log File들을 Log Server에 전송
- Log File을 Email로 전송
1. 로그 찍기
- log_resource_usage.sh (로그 찍어주는 스크립트)
#!/bin/bash
# 로그 파일 위치 설정
LOG_FILE="resource_usage.log"
# 현재 시간 가져오기
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
# CPU 사용량 가져오기
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1"%"}')
# 메모리 사용량 가져오기
MEMORY_USAGE=$(free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3, $2, $3*100/$2 }')
# 디스크 사용량 가져오기
DISK_USAGE=$(df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3, $2, $5}')
# 로그 파일에 기록
echo "$CURRENT_TIME CPU Usage: $CPU_USAGE, $MEMORY_USAGE, $DISK_USAGE" >> $LOG_FILE
- Jenkins Pipeline
pipeline {
agent any
stages {
stage('Clone') {
steps {
git 'https://github.com/nayeo2/KDT_log_shell.git'
}
}
stage('Update Crontab') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh './log_resource_usage.sh'
}
}
stage('Build') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh 'sudo ./log_resource_usage.sh'
}
}
stage('Deploy') {
when {
expression { currentBuild.result == null || currentBuild.result == 'SUCCESS' }
}
steps {
sshagent(['A-jenkins-key']) {
script {
def servers = [
'10.0.2.99',
'10.0.2.83'
]
servers.each { server ->
echo "Deploying to ${server}"
// Copy the script to the remote server
sh "scp -o StrictHostKeyChecking=no log_resource_usage.sh ubuntu@${server}:/home/ubuntu"
// Execute the script on the remote server
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'chmod +x /home/ubuntu/log_resource_usage.sh && /home/ubuntu/log_resource_usage.sh'"
}
}
}
}
}
}
post {
success {
echo "Deployment succeeded"
}
failure {
echo "Deployment failed"
}
}
}
2. 크론잡
- update_crontab.sh
#!/bin/bash
# 제거할 기존 크론잡 구문
OLD_CRON_JOB="*/5 * * * * sudo /home/ubuntu/log_resource_usage.sh"
# 새 크론잡 구문 (1분마다 실행)
NEW_CRON_JOB="* * * * * sudo /home/ubuntu/log_resource_usage.sh"
# 추가할 SCP 크론잡 (3시간마다)
SCP_CRON_JOB="0 */3 * * * scp -o StrictHostKeyChecking=no /home/ubuntu/resource_usage.sh ubuntu@10.0.10.63:/home/ubuntu/"
# 현재 사용자 크론탭을 임시 파일에 백업
crontab -l > current_crontab.txt 2>/dev/null
# 임시 파일에서 특정 구문을 포함하지 않는 라인만을 새로운 파일로 저장
grep -v -F "$OLD_CRON_JOB" current_crontab.txt > new_crontab.txt
# 새로운 크론탭 파일에 새 구문을 추가 (중복 확인 필요)
if ! grep -Fq "$NEW_CRON_JOB" new_crontab.txt; then
echo "$NEW_CRON_JOB" >> new_crontab.txt
fi
# SCP 크론잡 추가 (중복 확인 필요)
if ! grep -Fq "$SCP_CRON_JOB" new_crontab.txt; then
echo "$SCP_CRON_JOB" >> new_crontab.txt
fi
# 새로운 크론탭 파일을 적용
crontab new_crontab.txt
# 임시 파일 삭제
rm current_crontab.txt new_crontab.txt
echo "크론탭에서 '$OLD_CRON_JOB' 구문을 제거하고 '$NEW_CRON_JOB' 및 '$SCP_CRON_JOB' 구문을 추가했습니다."
- Jenkins Pipeline
pipeline {
agent any
stages {
stage('Clone') {
steps {
git 'https://github.com/nayeo2/KDT_log_shell.git'
}
}
stage('Update Crontab') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh './log_resource_usage.sh'
}
}
stage('Build') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh 'sudo ./log_resource_usage.sh'
}
}
stage('Deploy') {
when {
expression { currentBuild.result == null || currentBuild.result == 'SUCCESS' }
}
steps {
sshagent(['A-jenkins-key']) {
script {
def servers = [
'10.0.2.99',
'10.0.2.83'
]
servers.each { server ->
echo "Deploying to ${server}"
// Copy the script to the remote server
sh "scp -o StrictHostKeyChecking=no log_resource_usage.sh ubuntu@${server}:/home/ubuntu/"
sh "scp -o StrictHostKeyChecking=no update_crontab.sh ubuntu@${server}:/home/ubuntu/"
// Execute the script on the remote server
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'chmod +x /home/ubuntu/log_resource_usage.sh && /home/ubuntu/log_resource_usage.sh'"
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'chmod +x /home/ubuntu/update_crontab.sh && /home/ubuntu/update_crontab.sh'"
}
// Additional server for SCP every 3 hours
def additionalServer = '10.0.10.63'
echo "Sending resource_usage.log to ${additionalServer} every 3 hours"
// Copy the script to the additional server
sh "scp -o StrictHostKeyChecking=no resource_usage.log ubuntu@${additionalServer}:/home/ubuntu/"
}
}
}
}
}
post {
success {
echo "Pipeline completed successfully."
}
failure {
echo "Pipeline failed."
}
}
}
3. 로그 로테이트
- Jenkins Pipeline
pipeline {
agent any
stages {
stage('Clone') {
steps {
git 'https://github.com/nayeo2/KDT_log_shell.git'
}
}
stage('Update Crontab') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh './log_resource_usage.sh'
}
}
stage('Build') {
steps {
sh 'chmod +x log_resource_usage.sh'
sh 'sudo ./log_resource_usage.sh'
}
}
stage('Deploy') {
when {
expression { currentBuild.result == null || currentBuild.result == 'SUCCESS' }
}
steps {
sshagent(['A-jenkins-key']) {
script {
def servers = [
'10.0.2.99',
'10.0.2.83'
]
servers.each { server ->
echo "Deploying to ${server}"
// Copy the scripts and config to the remote server
sh "scp -o StrictHostKeyChecking=no log_resource_usage.sh ubuntu@${server}:/home/ubuntu/"
sh "scp -o StrictHostKeyChecking=no update_crontab.sh ubuntu@${server}:/home/ubuntu/"
sh "scp -o StrictHostKeyChecking=no logrotate.conf ubuntu@${server}:/home/ubuntu/"
// Execute the scripts on the remote server
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'chmod +x /home/ubuntu/log_resource_usage.sh && /home/ubuntu/log_resource_usage.sh'"
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'chmod +x /home/ubuntu/update_crontab.sh && /home/ubuntu/update_crontab.sh'"
sh "ssh -o StrictHostKeyChecking=no ubuntu@${server} 'sudo mv /home/ubuntu/logrotate.conf /etc/logrotate.d/resource_usage && sudo logrotate /etc/logrotate.d/resource_usage'"
}
// Additional server for SCP every 3 hours
def additionalServer = '10.0.10.63'
echo "Sending log_resource_usage.sh to ${additionalServer} every 3 hours"
// Schedule the script to be sent every 3 hours using cron
sh """
(crontab -l 2>/dev/null; echo "0 */3 * * * scp -o StrictHostKeyChecking=no log_resource_usage.sh ubuntu@${additionalServer}:/home/ubuntu/") | crontab -
"""
}
}
}
}
}
post {
success {
echo "Pipeline completed successfully."
}
failure {
echo "Pipeline failed."
}
}
}
- logrotage.conf
/home/ubuntu/resource_usage.log {
size 1M
copytruncate
rotate 7
compress
missingok
notifempty
daily
create 0644 root root
}
4. 이메일 보내기
- (관리자) 로그 서버에서 ssmtp 설치
sudo apt-get update
sudo apt-get install ssmtp
- ssmtp 환경설정
sudo vi /etc/ssmtp/ssmtp.conf
root=yourmail@gmail.com
mailhub=smtp.gmail.com:587
FromLineOverride=YES
UseSTARTTLS=YES
UseTSL=YES
AuthUser=yourmail
AuthPass=app password (16자리 문자)
- 이 때의 AuthPass는 gmail 앱 비밀번호 설정을 해야한다.
앱 비밀번호로 로그인 - Google 계정 고객센터
중요: 앱 비밀번호 사용은 권장되지 않으며 대부분의 경우 필요하지 않습니다. 계정을 안전하게 보호하려면 'Google 계정으로 로그인'을 사용하여 앱을 Google 계정에 연결하세요. 앱 비밀번호란 보
support.google.com
- send_log_email.sh
#!/bin/bash
LOG_FILE="/home/ubuntu/resource_usage.log"
EMAIL="your_email@gmail.com"
SUBJECT="Resource Usage Log"
BODY="Please find the attached resource usage log."
# 이메일 본문 생성
{
echo "Subject: $SUBJECT"
echo "To: $EMAIL"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Disposition: inline"
echo
echo "$BODY"
echo
cat "$LOG_FILE"
} | ssmtp "$EMAIL"
echo "로그 파일을 이메일로 전송했습니다."
- 자정마다 메일 보내는 크론잡도 등록 해줘야지!
crontab -e
0 0 * * * /home/ubuntu/send_log_email.sh