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

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


import time
t=time.localtime()
print t
time.struct_time(tm_year=2012, tm_mon=11, tm_mday=15, tm_hour=9, tm_min=53, tm_sec=20, tm_wday=3, tm_yday=320,tm_isdst=0)
print t.tm_year
print t.tm_mon
print t.tm_mday
print t.tm_hour
print t.tm_min
print t.tm_sec

'PYTHON > CODE' 카테고리의 다른 글

[CODE] 간단한 파일 서버 만들기  (0) 2012.11.23
[CODE] 파이썬 윈도우 서비스 등록  (0) 2012.11.15
[CODE] 오늘날짜 얻어오기  (0) 2012.11.14
[CODE] MySQLdb select 예제  (0) 2012.11.01
[CODE] PYTHON SSH 접속 작업하기  (1) 2012.10.19

paramiko라는 python 모듈을 사용하시면

SSH를 이용하여 원하는 서버에 접속 후 명령어를 실행시켜 결과를 가져올 수 있습니다.

사용법 이전에 설치에 대해서 알아보면 일단 2가지 파일을 다운로드 받으셔야 합니다.

pycrypto, paramiko 다운로드 링크는 꼭 달아드리도록 하겠습니다.

파이썬 모듈의 기본적인 설치 방법은 아래와 같습니다. 설치파일의 압축을 풀고 해당 디렉토리에서

아래의 명령을 수행하시면 설치가 됩니다.

먼저 pycrypto, paramiko를 순서대로 설치하시면 됩니다.

python setup.py build
python setup.py install 

해당 모듈의 사용법은 아래와 같습니다.

from paramiko import SSHClient,AutoAddPolicy

client = SSHClient()
client.load_system_host_keys()

client.set_missing_host_key_policy(AutoAddPolicy()) 

client.connect('192.168.137.101', username='admin', password='admin')
stdin, stdout, stderr = client.exec_command('list')
                                                                               
for line in stdout:
    print '... ' + line.strip('\n')
                                                                             
client.close()

특정 디렉토리를 입력하면 하위디렉토리의 리스트를 나타내는 코드입니다.

예를 들어 디렉토리명에 '/'을 입력하면 root디렉토리 하위의 모든 디렉토리명을 리스트로 반환하고

'/root'를 입력하면 /root 밑의 모든 하위 디렉토리를 리스트로 반환합니다. 인용은 stackoverflow.com입니다

import os 

def listdir_fullpath(d):
   
return [os.path.join(d, f) for f in os.listdir(d)]

listdir_fullpath('/')

이번엔 간단히 소켓 프로그래밍을 만들어 보겠습니다.

방법은 다른 OS들의 C라이브러리를 사용하는 것과 크게 다르지 않고 설정하는 부분도 대부분 동일한 형태입니다.

기본적으로 서버는 응답을 기다리고 응답이 오면 다시 해당 응답을 클라이언트로 전달하는 ECHO서버 예제입니다.

일단 Server쪽 먼저 만들어 보겠습니다. (소스는 python doc에서 인용하였습니다.)

# Echo server program
import socket

HOST = ''                   # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

크게 어렵지 않은 부분이라고 생각되어 집니다. 사실 몰라도 되죠 그냥 저렇게 써 주면 됩니다.

나중에 시간이 되면 라인 단위로 설명을 드리도록 하겠습니다.

다음 부분은 클라이언트 부분입니다.

# Echo client program
import socket

HOST = 'IP '                # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

위의 IP부분에 서버의 IP를 입력해주면 바로 동작이 되는 것을 확인할 수 있습니다.

이상입니다. 결과는 소스를 바로 가져 가시면 확인이 가능합니다. 제가 확인을 해보았습니다.

>> import py_compile

>> py_compile.compile('test.py')

>> quit

+ Recent posts