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

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


os.path.exists(path)

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

 

a=[1,2,3,3,3,3,4]
print set(a)
set([1, 2, 3, 4])

import os

for directoryName in os.listdir("C:\\temp"):
    print  directoryName

 

파이썬을 이용하여 간단하게 사용할 수 있는 파일 서버 만들기 입니다.

전송하고자 하는 폴더에서 아래와 같은 명령어를 입력하도록 합니다.

   python -m SimpleHTTPSever 8000

이렇게 하시면 8000으로 웹서버가 열리게 되고 파일목록이 보이며 다운로드 받을 수 있도록 되어 있습니다.



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

[CODE]Unique 리스트 값 찾기  (0) 2012.12.14
[CODE] 디렉토리 리스트 가져오기  (0) 2012.12.13
[CODE] 파이썬 윈도우 서비스 등록  (0) 2012.11.15
[CODE] 지금 시간 얻어오기  (0) 2012.11.15
[CODE] 오늘날짜 얻어오기  (0) 2012.11.14

python Win32모듈 다운로드 후 아래 코드 작성

다운로드

아래 코드 작성 저장후 서비스 등록은 python filename.py install, 서비스 시작은 python filename.py start

### Run Python scripts as a service example (ryrobes.com)
### Usage : python aservice.py install (or / then start, stop, remove)

import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time

class aservice(win32serviceutil.ServiceFramework):
    _svc_name_ = "Service short Name"
    _svc_display_name_ = "Service Display Name"
    _svc_description_ = "Service description


    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        import servicemanager
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

       self.timeout = 640000    #640 seconds / 10 minutes (value is in milliseconds)
       #self.timeout = 120000     #120 seconds / 2 minutes
       # This is how long the service will wait to run / refresh itself (see script below)

       while 1:
          # Wait for service stop signal, if I timeout, loop again
          rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
          # Check to see if self.hWaitStop happened
          if rc == win32event.WAIT_OBJECT_0:
            # Stop signal encountered
            servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!")  #For Event Log
            break
          else:
            t=time.localtime()
            if t.tm_min==0 or t.tm_min==30:
                #Ok, here's the real money shot right here.
                #[actual service code between rests]
                try:
                    file_path = "C:\PYTHON\filename.py"
                    execfile(file_path)             #Execute the script
                except:
                    pass
                #[actual service code between rests]
            else:
                pass


def ctrlHandler(ctrlType):
    return True

if __name__ == '__main__':
   win32api.SetConsoleCtrlHandler(ctrlHandler, True)
   win32serviceutil.HandleCommandLine(aservice)

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

[CODE] 디렉토리 리스트 가져오기  (0) 2012.12.13
[CODE] 간단한 파일 서버 만들기  (0) 2012.11.23
[CODE] 지금 시간 얻어오기  (0) 2012.11.15
[CODE] 오늘날짜 얻어오기  (0) 2012.11.14
[CODE] MySQLdb select 예제  (0) 2012.11.01

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

import datetime
s=datetime.datetime.now()
bk_date=s.strftime('%Y%m%d')

import MySQLdb


def db():
    sqldb=MySQLdb.connect(db='mydb',user='root',passwd='imsi00',host='localhost')
    mysql_cursor=sqldb.cursor()
    mysql_cursor.execute('select * from mydb.custom')
    print mysql_cursor.fetchmany(10)
    print mysql_cursor.fetchmany(10)
    print mysql_cursor.fetchmany(10)
    sqldb.close()

def main():
    db()

if __name__ == '__main__':
    main()

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()

+ Recent posts