2011-07-27

Ubuntu 10.04 LTS + NginX + Django 1.3 (FastCGI) + Python 2.7.2

이번에는 Ubuntu 10.04 (LTS) 에서 NginX + Django 1.3 (FastCGI) + Python 2.7.2 를 구성해보았다. Python 을 설치하기 전에 zlibc 를 먼저 설치해주어야 distribute 가 제대로 설치되는 삽질이 있었긴 했지만, CentOS에서 설치했던 것처럼 대체적으로 무난하게 설정이 되었다.


  1. Install Python
    # aptitude install zlibc zlib1g-dev
    # echo 'export PYTHONBREW_ROOT=/opt/pythonbrew' >> /etc/profile; source /etc/profile
    # curl -kLO http://xrl.us/pythonbrewinstall; chmod +x pythonbrewinstall; ./pythonbrewinstall
    # echo 'source /opt/pythonbrew/etc/bashrc' >> /etc/profile; source /etc/profile
    # pythonbrew install --force --no-test 2.7.2
    # pythonbrew switch 2.7.2
  2. Install Django
    # pip install django flup
  3. Create Project
    # mkdir -p /opt/project
    # cd /opt/project
    # django-admin.py startproject sample_project
    # cd sample_project
    # mkdir media
  4. Run Project
    # cd /opt/project/sample_project
    # python manage.py runfcgi method=threaded pidfile=/tmp/django_sample.pid host=127.0.0.1 port=8000
  5. Install NginX
    # aptitude install nginx
  6. Configure NginX
    # cd /etc/nginx/sites-available
    # vi django 
    server {
        listen 80;
        server_name 도메인주소;
        location /site_media  {
            root /opt/project/sample_project/media/;
        }
        location / {
            # host and port to fastcgi server
            fastcgi_pass 127.0.0.1:8000;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            fastcgi_param REQUEST_METHOD $request_method;
            fastcgi_param QUERY_STRING $query_string;
            fastcgi_param CONTENT_TYPE $content_type;
            fastcgi_param CONTENT_LENGTH $content_length;
            fastcgi_pass_header Authorization;
            fastcgi_intercept_errors off;
        }
    }
    # cd /etc/nginx/sites-enabled
    # ln -s /etc/nginx/sites-available/django django
  7. Run NginX
    # /etc/init.d/nginx restart


2011-07-26

CentOS 5.6 + NginX 0.8.54 + Django 1.3 (FastCGI) + Python 2.7.2

Python 으로 가장 많이 이용되는 웹프레임워크는 Django 이다. 최근 가벼움과 성능으로 인정을 받고 있는 NginX 와 FastCGI 로 연동하여 설치하는 방법을 간단하게 정리해보았다. CentOS 6.0 이 나오긴 했지만, 아직 5.x 환경도 많이 이용되고 있으리라 생각하여 CentOS 5.6 에서 테스트하였으며, 아마 6.0 에서도 무리없이 설치될 것으로 믿는다.

  1. Install Python
    # echo 'export PYTHONBREW_ROOT=/opt/pythonbrew' >> /etc/profile; source /etc/profile
    # curl -kLO http://xrl.us/pythonbrewinstall; chmod +x pythonbrewinstall; ./pythonbrewinstall
    # echo 'source /opt/pythonbrew/etc/bashrc' >> /etc/profile; source /etc/profile
    # pythonbrew install --force --no-test 2.7.2
    # pythonbrew switch 2.7.2
  2. Install Django
    # pip install django flup
  3. Create Project
    # mkdir -p /opt/project
    # cd /opt/project
    # django-admin.py startproject sample_project
    # cd sample_project
    # mkdir media
  4. Run Project
    # cd /opt/project/sample_project
    # python manage.py runfcgi method=prefork pidfile=/tmp/django_sample.pid host=127.0.0.1 port=8000
  5. Install NginX
    # yum install nginx
  6. Configure NginX
    # cd /etc/nginx
    # vi nginx.conf
    ...
        server {
            server_name 도메인주소;
            location /site_media  {
                root /opt/project/sample_project/media/;
            }
            location / {
                # host and port to fastcgi server
                fastcgi_pass 127.0.0.1:8000;
                fastcgi_param PATH_INFO $fastcgi_script_name;
                fastcgi_param REQUEST_METHOD $request_method;
                fastcgi_param QUERY_STRING $query_string;
                fastcgi_param CONTENT_TYPE $content_type;
                fastcgi_param CONTENT_LENGTH $content_length;
                fastcgi_pass_header Authorization;
                fastcgi_intercept_errors off;
            }
        }
    ...
  7. Run NginX
    # /etc/init.d/nginx restart



2011-07-14

Install Scala

JVM에서 사용할 수 있는 언어들이 많이 나온 상태이다. 아직도 Java 만이 JVM 에서 돌아간다고 생각하시는 분들이 계시다. 잠깐만 생각해봐도, Java, Groovy, Scala, Clojure, Jython, Jruby 등등이 줄줄 나온다. 이 중에서도 요즘 Scala 의 인기가 치솟고(?) 있다. PlayFramework 와 함께 쓰면 웹개발도 아주 신속하게 개발할 수 있다. Java 와 연계성도 괜찮으며, 성능도 보장된다. Twitter 에서도 Ruby 기반의 백앤드를 Scala로 바꾸었단다.

아무튼 모든 것이 그렇듯, 일단 설치부터 해야, 시작할 수 있으니, 간단하게 OS별로 설치하는 법을 보도록 하자.


  • 먼저, JDK는 설치되어있어야 한다.
  • Windows
    1. http://www.scala-lang.org/downloads에서 scala-w.x.y.z.zip 파일을 다운로드 받는다.
    2. 적당한 곳에 압축을 푼다. (예) C:\scala
    3. 환경변수 path 에 C:\scala\bin 을 등록한다.
  • CentOS
    • 6.0 에도 scala 가 패키지에 없으므로, 직접 다운로드하여 설치해야 한다.
    1. scala-w.x.y.z.tgz 파일을 다운로드 받는다.
      # wget http://www.scala-lang.org/downloads/distrib/files/scala-2.9.0.1.tgz
    2. 적당한 곳에 앞축을 푼다. (예) /opt/scala
      # mkdir -p /opt; tar xvfz scala-2.9.0.1.tgz -C /opt; mv /opt/scala-2.9.0.1 /opt/scala
    3. 환경변수 PATH 에 등록한다.
      # echo 'export PATH=/opt/scala/bin:$PATH' >> /etc/profile; source /etc/profile
  • Debian/Ubuntu
    • 패키지로 설치한다.
      # sudo apt-get install scala



2011-07-13

Python : 딕셔너리, 값으로 정렬하기

Python 에서 Dictionary라는 자료구조가 제공되는데, 이것은 Key 와 Value 로 요소가 이루어진다. 이번에 간단한 프로그램을 만들다가 Value 를 기준으로 Dictionary를 정렬할 필요가 생겼는데, 그 방법을 찾아보니 아래와 같았다. 이는 Python 2.4 이상에서 지원이 된다고 한다.


  • 소스
    #!/usr/bin/env python
    # filename : dict_sort.py
    from operator import itemgetter
     
    dict = {}
    dict['a'] = 2
    dict['b'] = 1
    dict['c'] = 5
     
    print(sorted(dict.iteritems(), key=itemgetter(1), reverse=True))
  • 결과
    # python dict_sort.py
    [('c', 5), ('a', 2), ('b', 1)]


2011-07-12

Python : 10MB 이상의 파일중에서 중복된 파일 찾기

PHP, Ruby 에 이어서, Python 에서도 중복파일 찾기를 만들어보았다.


# -*- coding: cp949 -*-
from operator import itemgetter
from hashlib import md5
import os
 
 
TARGET_DIR   = "M:\\USER\\특정디렉토리"
LIMITED_SIZE = 100*(1024*1024) # 100MB
 
 
def md5sum(filename, buf_size=8192):
    m = md5()
    with open(filename) as f:
        data = f.read(buf_size)
        while data:
            m.update(data)
            data = f.read(buf_size)
    return m.hexdigest()
 
 
def main():
    hash_cnt  = {}
    file_list = []
    for p, ds, fs in os.walk(TARGET_DIR):
        for f in fs:
            filename = os.path.join(p, f)
            if os.path.islink(filename) : continue
            if not os.path.isfile(filename) : continue
            filesize = os.path.getsize(filename)
            if filesize < LIMITED_SIZE: continue
 
            crc = md5sum(filename)
            if hash_cnt.has_key(crc):
                hash_cnt[crc] = hash_cnt[crc] + 1
            else:
                hash_cnt[crc] = 1
 
            item = crc+"|"+filename
            file_list.append(item)
 
    for hash, cnt in sorted(hash_cnt.iteritems(), key=itemgetter(1), reverse=True):
        if cnt < 2: continue
        print("\n["+hash+"]")
        for item in file_list:
            (hash2, filename) = item.split("|")
            if hash == hash2 : print(filename)
 
 
if __name__ == '__main__':
    main()


2011-07-09

FreeBSD 8.2 설치후 작업



FreeBSD를 설치한 후에 작업을 편하게 하게 위해서, 몇가지 필요한 패키지를 설치하고, 설정할 것들이 있다. 이렇게만 해 놓으면 리눅스와 비교를 해도 어떤 차이가 있는지 제대로 알아차리지 못할 것이다. ^^


  1. sshd 부팅시 자동시작 설정 : /etc/rc.conf
    sshd_enable="yes"
  2. sshd_config 수정 / 재시작 : root로 로그인하는 것은 보안상 문제가 있지만, 편의를 위히 일단 이렇게 해놓자.
    # vi /etc/ssh/sshd_config
    PasswordAuthentication yes
    PermitRootLogin yes
    # /etc/rc.d/sshd restart
    이제, ssh 로 원격 접속한다.
  3. root, toor 계정쉘을 bash로 변경
    # pkg_add -r bash; rehash; chsh -s bash root; chsh -s bash toor
    쉘을 바꾸었으니, 로그아웃하고 다시 로그인하자.
  4. /etc/profile 에 PACKAGESITE 설정한다.
    export PACKAGESITE="ftp://ftp8.kr.freebsd.org/FreeBSD/ports/i386/packages-8.2-release/Latest/"
    # export PACKAGESITE="http://ftp2.kr.freebsd.org/FreeBSD/ports/i386/packages-8.2-release/Latest/"
    # export PACKAGESITE="http://mirror.yongbok.net/FreeBSD/ports/i386/packages-8.2-release/Latest/"
    # export PACKAGESITE="http://ftp.kaist.ac.kr/FreeBSD/ports/i386/packages-8.2-release/Latest/"
    # export PACKAGESITE="ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-8.2-release/Latest/"
    profile 적용
    # source /etc/profile
  5. Linux Emulation 적용 (htop 에서 Linux 의 /proc 을 이용한다)
    # echo 'linux_enable="YES"' >> /etc/rc.conf
    # kldload linux; pkg_add -r linux_base-f10
    # echo 'linproc /compat/linux/proc linprocfs rw 0 0' >> /etc/fstab; mount linproc
  6. 필요한 패키지 설치
    # pkg_add -r tmux vim-lite ntp gnuls htop git curl
  7. ntpd 적용/실행
    # echo 'ntpd_enable="yes"' >> /etc/rc.conf
    # /etc/rc.d/ntpd start
  8. gnuls alias 적용
    # echo 'alias ls="gnuls --color=always"' >> /etc/profile; source /etc/profile
  9. vim 적용
    # echo 'alias vi="vim"' >> /etc/profile; source /etc/profile
  10. 언어 설정
    # echo 'export LANG=ko_KR.UTF-8' >> /etc/profile; source /etc/profile



2011-07-06

(Freeware for Business) 포토스케이프 : 국산 이미지 편집기


이미지 편집을 위해서 보통 포토샵, 라이트룸 등을 많이 사용한다. 이는 상용 제품인데다가 덩치도 커서 사양이 낮은 PC에서는 운용하기 쉽지 않다. 대부분은 이미지 편집 프로그램을 사진 보정을 위해서 이용하며, 보정을 위한 기능도 간단하고 빠르게 몇가지만 사용하게 된다. RAW 이미지를 반드시 다루어야 하는 상황이 아니라면, 포토스케이프가 그 대안이 될 수 있을 것이다. 이것도 역시 모든 사람이 자유롭게 사용할 수 있는 프리웨어이며, 국산이다. 필자도 이 프로그램을 주요 이미지 편집프로그램으로 사용하고 있다. ^^

아래와 같은 기능들이 있으며, 상당히 많은 기능을 제공하고 있다. 이정도의 프로그램이면, 엄청난 시간과 노력이 들어갔을 텐데, 어떻게 이렇게 무료 봉사를 할 수 있는지 궁금하지만, 많이 사용해주고 좋아해주면 보답하는 것이 될 것이라 생각한다. ^^;
  • 사진뷰어: 폴더의 사진을 한눈에 보기, 슬라이드쇼
  • 사진편집: 크기/밝기/색상 조절, 역광보정, 액자, 말풍선, 모자이크, 글쓰기, 그리기, 자르기, 필터, 적목보정, 뽀샤시, 복제도장툴
  • 일괄편집: 여러 장을 한번에 변환하는 일괄처리
  • 페이지: 여러장을 템플릿 한장으로 만들기
  • 이어붙이기: 아래로, 옆으로, 바둑판으로 여러장을 한장으로 이어 붙이기
  • GIF애니메이션: 움직이는 GIF 사진으로 만들기
  • 인쇄: 증명사진,명함사진,여권사진이나 썸네일 인쇄
  • 사진분할: 한장의 사진을 여러장으로 분할
  • 화면캡쳐: 화면을 캡쳐해서 편집,저장하는 기능
  • 색상검출: 사진이나 웹상의 화면을 확대해서 색상을 알아내는 색상검출 기능
  • 이름변환: 사진이름 일괄변환
  • RAW변환: RAW 파일을 JPG 파일로 일괄변환
  • 종이: 줄노트,모눈종이,오선지,달력 출력
  • 얼굴검색: 인터넷에서 동일하거나 비슷한 얼굴을 검색
  • 사진북마크: 사진전문 즐겨찾기
사이트 주소는 http://www.photoscape.co.kr 이며, 마음껏 다운로드 받아서 설치하면 된다.


2011-07-04

SSHD 보안

SSHD를 어쩔 수 없이 외부에 공개를 해야하는 경우, 반드시 보안처리를 해야한다. 예상하는 것보다 상당히 많은 해킹시도를 하기 때문이다. 최소한 아래 2가지 처리는 해주면 그나마 좀 낫지 않을까? 그러나, 가능하다면, SSHD 포트를 열어주지 말고, VPN을 이용하기 바란다.


  • root 로그인 막기
    # vi /etc/ssh/sshd_config
    PermitRootLogin no
    # /etc/init.d/sshd restart
  • DenyHosts
    • Install (CentOS)
      # yum install denyhosts
    • 동작 확인 : 어떤 IP를 통해서 로그인 실패하였는지 확인, 사실, denyhosts는 /var/log/secure 로그를 확인하여 처리하지만, lastb 로 확인하여도 그다지 상관없을 것이다.
      # lastb -i
      root     ssh:notty    123.140.148.160  Mon Jul  4 06:49 - 06:49  (00:00)
      root     ssh:notty    123.140.148.160  Mon Jul  4 06:49 - 06:49  (00:00)
      root     ssh:notty    123.140.148.160  Mon Jul  4 06:49 - 06:49  (00:00)
      root     ssh:notty    123.140.148.160  Mon Jul  4 06:49 - 06:49  (00:00)
      root     ssh:notty    123.140.148.160  Mon Jul  4 06:49 - 06:49  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:17 - 14:17  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:17 - 14:17  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:17 - 14:17  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:16 - 14:16  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:16 - 14:16  (00:00)
      root     ssh:notty    178.18.19.114    Sun Jul  3 14:16 - 14:16  (00:00)
      root     ssh:notty    211.214.218.118  Sun Jul  3 10:00 - 10:00  (00:00)
      root     ssh:notty    211.214.218.118  Sun Jul  3 10:00 - 10:00  (00:00)
      root     ssh:notty    193.253.228.193  Sun Jul  3 06:05 - 06:05  (00:00)
      root     ssh:notty    193.253.228.193  Sun Jul  3 06:04 - 06:04  (00:00)
      wcostiga ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      wcostiga ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      root     ssh:notty    221.10.252.53    Sun Jul  3 01:14 - 01:14  (00:00)
      jroyds   ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      jroyds   ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      root     ssh:notty    221.10.252.53    Sun Jul  3 01:14 - 01:14  (00:00)
      cdimasci ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      cdimasci ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      root     ssh:notty    221.10.252.53    Sun Jul  3 01:14 - 01:14  (00:00)
      goodrich ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      root     ssh:notty    221.10.252.53    Sun Jul  3 01:14 - 01:14  (00:00)
      goodrich ssh:notty    195.70.27.20     Sun Jul  3 01:14 - 01:14  (00:00)
      root     ssh:notty    221.10.252.53    Sun Jul  3 01:14 - 01:14  (00:00)
      
      btmp begins Sun Jul  3 01:14:34 2011
      차단 등록된 IP 확인
      # cat /etc/hosts.deny
      #
      # hosts.deny    This file describes the names of the hosts which are
      #               *not* allowed to use the local INET services, as decided
      #               by the '/usr/sbin/tcpd' server.
      #
      # The portmap line is redundant, but it is left to remind you that
      # the new secure portmap uses hosts.deny and hosts.allow.  In particular
      # you should know that NFS uses portmap!
      
      
      sshd: 221.10.252.53
      sshd: 195.70.27.20
      sshd: 193.253.228.193
      sshd: 211.214.218.118
      sshd: 178.18.19.114
      sshd: 123.140.148.160