간만에 좋은 코드 하나 올려 드립니다.

Python으로 Daemon을 만드는 예제 코드 입니다.

일단 해당 예제를 실행시키기 위해서 다운로드 받아야 하는 페키지가 있는데 아래와 같이 받으면 됩니다.

python easy_install python-daemon

위의 패키지를 다운로드 하시면 준비는 끝입니다. 

본격적으로 코드는 아래와 같습니다.


# To kick off the script, run the following from the python directory:
#   PYTHONPATH=`pwd` python testdaemon.py start

#standard python libs
import logging
import time

#third party libs
from daemon import runner

class App():
    
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/var/run/testdaemon/testdaemon.pid'
        self.pidfile_timeout = 5
            
    def run(self):
        while True:
            #Main code goes here ...
            #Note that logger level needs to be set to logging.DEBUG before this shows up in the logs
            logger.debug("Debug message")
            logger.info("Info message")
            logger.warn("Warning message")
            logger.error("Error message")
            time.sleep(10)

app = App()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/var/log/testdaemon/testdaemon.log")
handler.setFormatter(formatter)
logger.addHandler(handler)

daemon_runner = runner.DaemonRunner(app)
#This ensures that the logger file handle does not get closed during daemonization
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()

22 ~ 24번째 라인에 Daemon에서 실행시켜야 하는 부분을 넣으면 정상적으로 실행됩니다. 나머지 부분은 크게 어려울이 없을 것으로 예상되어 집니다.

로그 디렉토리(/var/log/testdaemon), PID 디렉토리(/var/run/testdaemon)은 만들어 놓으셔야 합니다. 

아래는 Daemon을 inittab 부분에 넣는 부분입니다.


#! /bin/bash
# Copyright (c) 1996-2012 My Company.
# All rights reserved.
#
# Author: Bob Bobson, 2012
#
# Please send feedback to bob@bob.com
#
# /etc/init.d/testdaemon
#
### BEGIN INIT INFO
# Provides: testdaemon
# Required-Start: 
# Should-Start: 
# Required-Stop: 
# Should-Stop:
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Short-Description: Test daemon process
# Description:    Runs up the test daemon process
### END INIT INFO

# Activate the python virtual environment
    . /path_to_virtualenv/activate

case "$1" in
  start)
    echo "Starting server"
    # Start the daemon 
    python /usr/share/testdaemon/testdaemon.py start
    ;;
  stop)
    echo "Stopping server"
    # Stop the daemon
    python /usr/share/testdaemon/testdaemon.py stop
    ;;
  restart)
    echo "Restarting server"
    python /usr/share/testdaemon/testdaemon.py restart
    ;;
  *)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/testdaemon.sh {start|stop|restart}"
    exit 1
    ;;
esac

exit 0


1. 디렉토리 구조 만들기

├── BOARD
│   ├── BOARD
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── settings.py
│   │   ├── settings.pyc
│   │   ├── urls.py
│   │   ├── urls.pyc
│   │   ├── wsgi.py
│   │   └── wsgi.pyc
│   ├── WEB
│   │   ├── css
│   │   ├── html
│   │   ├── img
│   │   ├── js
│   │   └── less
│   ├── WEB.tar.gz
│   ├── board
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── models.py
│   │   ├── tests.py
│   │   ├── views.py
│   │   └── views.pyc
│   └── manage.py
└── django-admin.py

 [Project Name]/WEB/css : css 파일 모음

 [Project Name]/WEB/js   : js 파일 모음

 [Project Name]/WEB/img : 이미지 파일 모음

 -> 해당 파일들은 첨부 파일의 WEB.tar.gz 파일로 첨부했습니다. Project 폴더에서 tar -xvzf WEB.tar.gz 를 입력하시면 됩니다.

      해당 폴더 안에는 Twitter의 WEB UI Framework인 bootstrap가 들어 있습니다.


2. settings.py 설정

STATIC_ROOT = '/home/nijin39/DEV/BOARD/WEB'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
('css', '/home/nijin39/DEV/BOARD/WEB/css'),
('js', '/home/nijin39/DEV/BOARD/WEB/js'),
('img', '/home/nijin39/DEV/BOARD/WEB/img'),
)

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/nijin39/DEV/BOARD/WEB/html'
)

3. HTML 파일 만들기

    <!DOCTYPE html>
    <html>
    <head>
    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
    </head>
    <body>
    <h1>Hello, world!</h1>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    </body>
    </html>

5. 결과



WEB.tar.gz


서버에서 다른 서버로 특정 포트로 연결이 되는지 확인하는 방법은 아래와 같이 2개가 있습니다.

아래 첫번째 방법은 리눅스에서 nc명령어로 확인하는 방법이고 밑의 두번째는 일반적으로 telnet 명령을 이용하는 방법입니다.

참고하세요.

 

nc -Z <host> <port>; echo $?

connection Success : 0 return

connection Fail : 1 return

 

echo quit | telnet 192.168.X.X 21 2>/dev/null | grep Connected

+ Recent posts