id oracle | sed 's/^uid=//;s/(.*$//'

#!/bin/bash


echo "SHOW SERVERS"

su - oracle -c "sqlplus '/as sysdba'" << END

set pagesize 0 feedback off ver off heading off echo off

CONN 아이디/패스워드

쿼리

exit;

END



1) Configuration of both log server and log client:

Check if there is an entry in /etc/services regarding port 514 (default for syslog).

grep 514 /etc/services

syslog 514/udp

Enable communication on this port by setting proper rule on firewall:

-A RH-Firewall-1-INPUT -p udp –dport 514 -j ACCEPT

Syslog by default is not configured to send logs to remote hosts or receive them from network. You have to change startup options in /etc/sysconfig/syslog by adding ‘-r’ to SYSLOG_OPTS.

Now we are prepared to configure syslog! Configuration is stored in /etc/syslog.conf . Entries are different on log server and log client.

2) Configuration of log server:

You have to provide information about log client and destination where logs from client will be written. To do this you have to add two lines to the /etc/syslog.conf:

+LOG_CLIENT
log_source.log_type log_file

where:

  • LOG_CLIENT could be hostname or IP adress. If you are using hostname it have to be resolved by DNS or written in /etc/hosts.
  • log_source.log_type – here you can specify subsystems from which information will be logged and message types. Here are a few examples: user.notice -> information from users; kernel.warn -> warnings from kernel; *.* -> all messages from all subsystems.
  • log_file – logs will be written here.

Example:

+log_client
user.* /var/log/log_client.log

In above example logs from user subsystem from host ‘log_client‘ will be written in /var/log/log_client.log


3) Configuration of log client:

In /etc/syslog.conf you have to specify which logs will be copied on log server:

log_source.log_type @LOG_SERVER

where:

  • log_source.log_type – here you can specify subsystems from which information will be logged and message types. Here are a few examples: user.notice -> information from users; kernel.warn -> warnings from kernel; *.* -> all messages from all subsystems.
  • LOG_SERVER could be hostname or IP adress. If you are using hostname it have to be resolved by DNS or written in /etc/hosts.

Example:

user.* @log_server

In above example logs from user subsystem will be sent to ‘log_server’ host.

Remember to restart syslog service after making any changes in /etc/syslog.conf!

service syslog restart

'서버관리' 카테고리의 다른 글

[쉘스크립트] user SID 가져오기  (0) 2013.08.13
[쉘스크립트] 쉘에서 DB 쿼리하기  (0) 2013.08.07
[LInux Connection Check]  (0) 2013.04.08
[넷백업 Active 폴리시 구하기]  (0) 2013.03.15
우분투 원격터미널 접속  (0) 2013.01.04

ALTER TABLE django_admin_log CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

제가 모든 것을 소개 하기에는 역량이 부족하고

아래 2개의 사이트를 소개해드립니다.

Django tutorial 예제는 twitter bootstarp를 적용하여 제작하고 있습니다.




많은 도움이 되었으면 합니다.

'Open Source 소개' 카테고리의 다른 글

[CHATTING API LINK]  (0) 2014.07.29
JQUERY TABLE - DATATABLE  (0) 2012.11.16

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

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

1. 프로젝트 아래 APP만들기

root@ubuntu:~/django/FIRST# python manage.py startapp board

→ 이전에 우리는 FIRST라는 프로젝트를 생성했는데 이제 그 아래 board라는 어플리케이션을 만듭니다. 해당 어플리케이션이 정상적으로 생셩이 되었다면 아래와 같은 구조의 디렉토리와 파일들이 자동적으로 생성될 것입니다.

root@ubuntu:~/django# ls -R FIRST
FIRST:
board  __init__.py  __init__.pyc  manage.py  settings.py  settings.pyc  urls.py

FIRST/board:
__init__.py  models.py  tests.py  views.py

root@ubuntu:~/django#

→ 이제 우리는 위의 파일들 중 FIRST/urls.py, FIRST/board/views.py를 이용하여 주소가 있는 페이지를 만들어 볼것입니다.

 

2. urls.py 편집

from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'FIRST.views.home', name='home'),
    # url(r'^FIRST/', include('FIRST.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

처음 기본적으로 Django를 설치하면 위의 파일은 지금 보는 것처럼 설정되어 있습니다. urls.py를 간단히 설명하면

우리가 입력하는 주소를 누가 처리할지를 정해주는 곳이라고 보면됩니다. (JAVA의 DISPATCHER라고나 할까요?)

 

위의 주소를 아래과 같이 바꾸어봅니다.

from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'FIRST.views.home', name='home'),
    # url(r'^FIRST/', include('FIRST.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'board.views.index'),
)

위의 라인에 대해 설명을 드리자면 설명을 드리지 않겠습니다. 17라인에 대해 설명을 드리면 r'^$'이라는 부분은 주소를 나타내는 마지막 / 뒤에 아무것도 붙지 않으면 즉 '/' 입력을 나타내는 것입니다. 

만약 주소로 0.0.0.0/ 을 입력한다면 이전에 우리가 만들었던 board/views.py의 index 메소드에서 처리한 결과를 출력한다 

 

3. /board/views.py 편집

# Create your views here.

from django.http import HttpResponse

def index(request):
        return HttpResponse('HELLO')

위의 라인에 대해서 설명을 드리면 request를 입력으로 받는 index메소드는 HttpResponse('HELLO')를 리턴한다 입니다.

나를 부르면 나는 웹에다가 HELLO를 찍겠다.

 

4. 결과

 위의 결과가 나온다면 정상입니다 .오늘은 여기까지 집에 가야지. ㅎㅎㅎ

1. 프로젝트 생성

cd /root
mkdir django
cd django
cp /usr/lib/python2.7/dist-packages/django/bin/django-admin.py .
python django-admin.py startproject FIRST

 → 위의 명령어을 정상적으로 수행했다면 아래와 같은 구조의 디렉토리가 생셩되게 됩니다.

root@ubuntu:~/django# ls -R FIRST
FIRST:
__init__.py  __init__.pyc  manage.py  settings.py  settings.pyc  urls.py  urls.pyc

 

2. DB생성

root@ubuntu:~/django# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.5.29-0ubuntu0.12.04.2 (Ubuntu)

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database board;

 

3. DB 및 환경설정

root@ubuntu:~/django/FIRST# vi settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',         # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'board',                                        # Or path to database file if using sqlite3.
        'USER': 'root',                                           # Not used with sqlite3.
        'PASSWORD': '설정하고싶은 비밀번호',      # Not used with sqlite3.
        'HOST': 'localhost',                                   # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                                          # Set to empty string for default. Not used with sqlite3.
    }
}

TIME_ZONE = 'Asia/Seoul'

→ 위와 같이 DB정보와 함께 TIME_ZONE을 설정하도록 합니다.

 

4. DB 동기화

root@ubuntu02:~/django/FIRST# python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site

 

5. 서비스 시작

root@ubuntu:~/django/FIRST# python manage.py runserver 0.0.0.0:80
Validating models...

0 errors found
Django version 1.3.1, using settings 'board.settings'
Development server is running at http://0.0.0.0:80/
Quit the server with CONTROL-C.

 

6. 서비스 확인

위의 사진이 보인다면 정상적으로 세팅이 된것입니다. 안되었다면 연락주세요..

'DJANGO' 카테고리의 다른 글

DJANGO #6. Template 적용하기  (0) 2013.05.17
DJANGO #5. 어플생성 및 기본 작동 방법 설명  (0) 2013.04.05
DJANGO #3. Python, Django 설치  (0) 2013.04.03
DJANGO #2. Tutorial 설명  (0) 2013.04.03
DJANGO #1. Django 정의 및 특징  (0) 2013.04.03

+ Recent posts