지난  번 특정 경로에 파일이 있는 경우 파일을 이동시키는 스크립트를 만들어 보았다.

[리눅스]특정 경로에 파일이 존재하는 경우 특정 디렉토리에 이동시키기

이번엔 파일이 이동되거나 실패한 경우 문자를 보내서 이벤트를 알려주는 알림서비스를 만들어보자.

Twilio를 사용하여 파일 이동 작업이 완료되었거나 실패했을 때 SMS를 보내는 방법을 설명드리겠습니다. 이를 위해 Twilio Python 라이브러리를 설치하고, file_watch.sh 스크립트 내에서 Python 스크립트를 호출하는 방식으로 구현할 수 있습니다.

1. Twilio Python 라이브러리 설치

먼저, Twilio Python 라이브러리를 설치해야 합니다. 이를 위해 서버에 Python 및 pip이 설치되어 있어야 합니다.

pip install twilio

2. Twilio API 설정

Twilio 계정을 생성한 후, Twilio Console에서 Account SIDAuth Token을 얻어야 합니다. 또한 Twilio에서 제공하는 전화번호가 필요합니다.

3. Python 스크립트 작성

다음으로, Twilio를 사용하여 SMS를 보내는 Python 스크립트를 작성합니다.

send_sms.py

from twilio.rest import Client
import sys

def send_sms(to_number, message):
    # Twilio 계정 정보
    account_sid = 'your_account_sid'
    auth_token = 'your_auth_token'
    client = Client(account_sid, auth_token)

    try:
        # 메시지 발송
        client.messages.create(
            body=message,
            from_='+1234567890',  # Twilio에서 구입한 전화번호
            to=to_number
        )
        print("SMS sent successfully")
    except Exception as e:
        print(f"Failed to send SMS: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python send_sms.py <phone_number> <message>")
        sys.exit(1)

    phone_number = sys.argv[1]
    message = sys.argv[2]
    send_sms(phone_number, message)

이 스크립트는 send_sms.py 파일로 저장됩니다. 이 Python 스크립트는 명령줄 인자로 전화번호와 메시지를 받아 Twilio를 통해 SMS를 발송합니다.

4. file_watch.sh에서 Python 스크립트 호출

file_watch.sh에서 파일이 이동되었거나 실패했을 때 send_sms.py 스크립트를 호출하도록 수정합니다.

수정된 file_watch.sh

#!/bin/bash
WATCH_DIR="/home/download/completed"
DEST_DIR="/completed"
LOG_FILE="/home/file_watch.log"
PIDFILE="/var/run/file_watch.pid"
PHONE_NUMBER="+821012345678"  # 관리자 전화번호

# 로그 함수 정의
log() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" >> "$LOG_FILE"
}

send_sms() {
    local message="$1"
    python3 /path/to/send_sms.py "$PHONE_NUMBER" "$message"
}

# PIDFILE 체크
if [ -f "$PIDFILE" ]; then
    echo "Script is already running with PID $(cat $PIDFILE). Exiting."
    exit 1
fi

# PIDFILE 생성
echo $$ > "$PIDFILE"

# 종료 시 PIDFILE 삭제
trap 'rm -f "$PIDFILE"; exit' INT TERM EXIT

# 무한 루프 시작
while true; do
    # WATCH_DIR이 존재하는지 확인
    if [ ! -d "$WATCH_DIR" ]; then
        log "Watch directory $WATCH_DIR does not exist."
        send_sms "Watch directory $WATCH_DIR does not exist."
        rm -f "$PIDFILE"
        exit 1
    fi
    
    # 현재 디렉토리에서 파일 목록을 가져옴
    find "$WATCH_DIR" -type f | while IFS= read -r file; do
        # 파일이 존재하는지 확인
        if [ ! -e "$file" ]; then
            log "File $file does not exist."
            continue
        fi
        
        # 파일 크기 측정
        initial_size=$(stat -c%s "$file")
        sleep 300
        new_size=$(stat -c%s "$file")
        
        # 파일 크기가 변하지 않으면 이동
        if [ "$initial_size" -eq "$new_size" ];then
            # 파일이 일정 시간 동안 변경되지 않았는지 확인
            if [ $(find "$file" -mmin +5) ]; then
                # 파일 복사
                cp "$file" "$DEST_DIR/"
                if [ $? -eq 0 ]; then
                    # 크기 확인
                    dest_file="$DEST_DIR/$(basename "$file")"
                    if [ "$(stat -c%s "$file")" -eq "$(stat -c%s "$dest_file")" ]; then
                        rm "$file"
                        log "Moved $(basename "$file") to $DEST_DIR"
                        send_sms "File $(basename "$file") moved to $DEST_DIR successfully."
                    else
                        log "Failed to move $(basename "$file"). File sizes do not match."
                        send_sms "Failed to move $(basename "$file"). File sizes do not match."
                    fi
                else
                    log "Failed to copy $(basename "$file") to $DEST_DIR."
                    send_sms "Failed to copy $(basename "$file") to $DEST_DIR."
                fi
            else
                log "File $file is still being modified."
            fi
        else
            log "File $file size changed during wait time."
        fi
    done

    sleep 10
done

5. 스크립트 실행

위 스크립트를 실행할 때 nohup을 사용해 백그라운드에서 지속적으로 실행되도록 설정합니다:

nohup ./file_watch.sh &

이제 파일이 이동되거나 실패할 때마다 설정된 전화번호로 SMS가 전송됩니다.

주의사항

  • Twilio 사용 시, 사용량에 따라 비용이 발생할 수 있으니 사용 전에 가격 정책을 확인하세요.
  • 전화번호 형식에 맞게 입력하도록 주의하세요 (국제 번호 형식, 예: +82).
  • send_sms.py 스크립트의 경로와 Twilio 계정 정보를 정확히 설정해야 합니다.

#리눅스 #우분투 #파이썬 #python #twilio #sms #문자보내기 #문자전송

Author: 모요
댓글

댓글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

*

©2024 MOYO Blog with DAON Consulting Co,LTD.

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

보내는 중입니다..

로그인하세요.

계정 내용을 잊으셨나요 ?