다음카페 같은데 보면 방문자 정보를 10개씩 뿌려주는데 그거 긁어오는거..
스크립트를 cron 에 등록시키고 매 1분마다 실행시킨다.
데이터를 긁어와 특정한 곳에 파일 또는 DB로 저장한다.
url 정보가 바뀌진 않지만 만약, 디자인 레이아웃이 바뀌면 말짱 도루묵.. 고로 그때그때 맞게 수정해야 된다.
charset도 시스템에 맞게 적절히 수정..


#!/usr/bin/perl -w

#####################################################################################
# author : gogisnim (gogisnim@gmail.com)
# file   : getCafe.pl
# date   : 2009.10.05
# desc   : LWP 모듈 테스트용, perl 감각익히기
#         : 다음카페의 방문자 목록을 얻는 perl script
#         : 단, cron으로 돌릴땐 local::lib 모듈을 지정해 주어야 한다.
#          : perl -I$HOME/perl5/lib/perl5 -Mlocal::lib ~/perl/getCafe.pl 이런식으로...
#####################################################################################

use strict;
use warnings;
use LWP::Simple;    # LWP 모듈

# 변수선언
my ($url, $html, $html2, $div1, $div2, $dir, $prev_txt, $old_txt, $new_txt, $data, $file_name) = ();
my (@nick,@tmp) = ();

$dir = "/home/xxx/perl/fun";
$url = "html긁어올url";
$html = get($url);

# html을 얻어오지 못하면 종료한다.
exit if ( !$html );

# $div1으로 나눈 2번째 요소를 취하고 $div2로 나눈 첫번째 요소를 취한다.
$div1 = "<div class=\"component_list group\">";
$div2 = "</div>";
($html2) = ( split $div2, (split $div1,$html)[1] )[0];

# 필요한 html을 \n 으로 분리해서 @tmp 배열에 넣는다.
@tmp = split("\n", $html2);

open (FH, $dir."/curr") or die("curr file error");
#binmode FH, ':encoding(UTF-8)';
binmode FH, ':encoding(euc-kr)';

# 문자열 초기화
$prev_txt = $old_txt = $new_txt = "";


# curr 파일의 내용을 읽어서 $prev_txt에 저장
# 주의. UTF-8로 인코딩 해야한다.
while ( <FH> ) {
   $prev_txt .= $_;
}
close(FH);


# 얻은 html 정보를 라인별로 읽어 정규표현식 <li title=\"(.+)\"> 에 만족하는 부분의 괄호부분($1)을 $old_txt에 저장
# 그중에서 이전 데이터($prev_txt)에 없는 정보(새로운 닉네임)은 $new_txt에 저장한다.
foreach ( @tmp ) {
   if ( /<li title=\"(.+)\">/ ) {
       $old_txt .= $1.",";
       if ( index($prev_txt,$1) == -1 ) {
           $new_txt .= $1.",";
       }
   }    
}

# curr 파일을 쓰기모드로 열고 UTF-8로 인코딩한다음 $old_txt 내용을 저장한다.
open (FH, ">".$dir."/curr") or die("curr file error");
#binmode FH, ':encoding(UTF-8)';
binmode FH, ':encoding(euc-kr)';
print FH $old_txt;
close(FH);


# 하루에 해당하는 파일 "년월일" $file_name 을 구한다.  예) 20091006
my ( $sec, $min, $hour, $mday, $mon, $year ) = ();
($sec, $min, $hour, $mday, $mon, $year) = localtime(time);
$year = $year + 1900;
$mon = $mon + 1;
if(length($mon)==1)     { $mon  = '0'.$mon; }
if(length($mday)==1)    { $mday = '0'.$mday; }
if(length($hour)==1)    { $hour = '0'.$hour; }
if(length($min)==1)     { $min  = '0'.$min; }
$file_name = $year.$mon.$mday;


# 새로운 닉네임($new_txt) 내용을 $file_name에 저장한다.
open (FH, ">>".$dir."/$file_name") or die("data file error");
$data = "\n".$hour.":".$min." ==> ".$new_txt;
#binmode FH, ':encoding(UTF-8)';
binmode FH, ':encoding(euc-kr)';
print FH $data;
close(FH);

Angel은 Perl로 만든 간단하지만 유용한 네트워크 모니터링툴이다.
conf에서 지정한 호스트,옵션정보를 기준으로 angel 스크립트와 plugins 디렉토리의 모니터링할 항목의 perl script를 실행시키고 결과를 html문서로 생성한다.
plugins에 들어갈 항목은 기본적으로 ping, disk, ftp, http, load, mysql, smtp 이다.
해당 운영체제의 시스템관련 명령을 Proc::Simple 모듈에서 실행하는것이기 때문에 필요한 항목은 cmdline을 만들어 결과문자열을 파싱해서 만들면 된다.
다른 서버와의 통신은 rsh를 사용하는데 rsh 서비스를 하지않는 입장에서 이게 좀 흠이라면 흠인듯..

보통 일정시간마다 cron으로 등록해서 사용한다.
모든 운영체제를 지원하지만 해당 명령어의 결과문자열이 미세한 차이를 보이기 때문에 확인이 필요하다.
(예를들어, 리눅스의 df에서 사용가능한 디스크용량은 Available로 표시되는데 반해 FreeBSD에서는 Avail로 표시된다)

사용자 삽입 이미지


그외 웹으로 확인하기위한 아파치설정이나 기타내용은 http://www.paganini.net/angel/ 에서 확인한다.

2009년 계획

살기/일상 2009/01/05 11:11
1. 담배을 줄이자.
언젠가 3개월가량 담배를 피우지않은 적이 있었는데 엄청난 업무량의 스트레스 해소용(?)으로
다시 물었던 적이 있다.
차마 끈는다는 말은 못하겠고..
좀 줄여보자.


2. 체중을 늘리자.
만화 "쿵후보이 친미"를 보면 친미가 요센도사의 죽음을 담보로한 수련의 마지막 과정이 "통배권"의 연마였다.
통배권은 자신보다 훨씬 파워나 체중이 많은 적을 물리치기 위한 강(强)의 권법..
따라서 통배권을 연마하기 위한 제1관문이 자신의 체중을 몇배로 늘리는 것이다.
목욕탕 가본지 꽤 되었는데 대략 60~61정도... 올핸 기필고 마의 65를 돌파해야겠다.


3. perl 관련 활동
재작년에 처음 접하고 작년부터 본격적인 활동을 하다가 컨퍼런스 끝나고 잠시 주춤..
올해는 seoul pm 적극적인 활동 및 홍보에 주력.. 개인적인 스킬도 쌓아야 겠다...
근데...사놓고 보지못해 산더미처럼 쌓인 책만보면 한숨부터..ㅠ


4. 영어 좀 해보자.
올 계획중 하나가 34년 처음으로 해외에 가보는 것..
단순여행일 수도 있고 컨퍼런스 참석차 가는걸 수도 있고, 환율땜에 걸리긴 하지만 어쨌든 올해안으로 한번쯤 갈것같다.
말하기,듣기위주로 수련계획중..


5. 지키자
위 계획들을 반드시 실천에 옮긴다.



어찌어찌하여 2008년이 지나갔고 2009년이 시작되었다.

지금까지 살아오면서 신년에 계획을 세워보기도 했었고 무계획으로 일관했던 적도 있었지만 하나같이 탐탁치 않은 결과뿐이었다.

곰곰히 생각해보면 계획을 세웠을때는 너무나 방대하고 실행하기 어려운 것들이 많았던거 같다.

해서 파이를 좀 줄였다.

올해 계획은 눈으로 보이는 것보다 약간 두리뭉실한 부분이 좀 있는것 같다.

잘될수 있을까?



올 한해도 무사히 넘어가길 ...

끝나는 날까지 신이여 나를 지켜 주소서 ...
사용자 삽입 이미지

Korean Perl Wrokshop 2008 이 성대히(?) 막을 내렸다.

나는 STAFF로 참석해 이것저것 거들었다.
참, 티셔츠와 기념품(액정클리너)를 직접 작업했다.
물론, 디자인은 친구 용발이한테 맞겼고 나는 작업추이를 지켜보다가 물건 가져오는 정도..

역시나 쟁쟁한 분들의 발표는 언제봐도 멋있다.
기억에 남는 발표자는 perl 1세대분이신 KOBIC의 박종화 박사님..
말씀을 너무나 재밌게 하시고 특히나 bioperl 라이센스가 충격적으로 다가왔다.
또다른 perl 1세대분이자 perl.or.kr의 주인장이신 전종필님과 스터디에 함께 하시는 aero님의 발표는 STAFF 역할에 충실(?)하느라 직접 듣지못한게 참 아쉬웠다.

동민님의 "Location Prediction for indoor sensor networks", 코퍼스님의 "언어학을 위한 perl", 현승님의 "perl을 이용한 영상 오브젝트 추출" 은 perl이 얼마나 범용적인 언어인가를 실감할 수 있는 발표였다.

워크샵 참석차 일본에서 오신 한송이님의 Catalyst 발표도 구미를 당기는 발표였다.
국내에 Catalyst Framework 으로 개발된 웹사이트가 거의 전무하다할 정도인데 스터디에는 Catalyst가 자주 거론되지만 실제로 써먹기위해선 공부를 좀 해야 할거 같다.

기석님의 "Web2RSS with Perl"과 lightning talk에서의 aero님의 rss 관련 내용도 굉장히 유용할거 같다.
개인적으로 시스템/보안에 관심이 많은지라 배상우님과 혁진님의 보안관련 주제도 좋았다.
도형님의 GTK2-Perl도 재미있었고 특히나 명찰만들기와 추첨이 압권이었다.

유니님과 민영님이 참석하지 못한게 아쉬웠지만 첫번째 workshop 치고는 상당히 분위기/반응이 좋았던거 같다.

열심히 공부해서 내년에는 speaker로 참석해야겠다..ㅋ
perl에서 데이터베이스 접근을 위한 모듈을 설치한다.
사용자는 DBI모듈 불러오고 이 DBI모듈이 DBD::mysql 모듈을 불러와 DB에 접근할 수 있다.

모듈정보를 확인한다.

# perl -MDBI -e 'print "$DBI::VERSION\n"'
Can't locate DBI.pm in @INC (@INC contains: /usr/local/lib/perl5/site_perl/5.8.6/mach /usr/local/lib/perl5/site_perl/5.8.6 /usr/local/lib/perl5/site_perl /usr/local/lib/perl5/5.8.6/BSDPAN /usr/local/lib/perl5/5.8.6/mach /usr/local/lib/perl5/5.8.6 .).
BEGIN failed--compilation aborted.

# perl -MDBD::mysql -e 'print "$DBD::mysql::VERSION\n"'
Can't locate DBD/mysql.pm in @INC (@INC contains: /usr/local/lib/perl5/site_perl/5.8.6/mach /usr/local/lib/perl5/site_perl/5.8.6 /usr/local/lib/perl5/site_perl /usr/local/lib/perl5/5.8.6/BSDPAN /usr/local/lib/perl5/5.8.6/mach /usr/local/lib/perl5/5.8.6 .).
BEGIN failed--compilation aborted.

# cpan
cpan> i /DBI/
cpan> install DBI
cpan> exit
# perl -MDBI -e 'print "$DBI::VERSION\n"'
1.607

DBI 모듈이 설치되었다.

DBD::mysql 모듈을 설치한다.

# cpan
cpan> install DBD::mysql
...
mysql_config 를 찾지못한다고 오류가나면서 종료된다.
$PATH를 추가하고 다시 한다.

이번에는 DB 테스트하는 과정에서 오류가 난다.
테스트를 건너뛰고 모듈을 설치할 수도 있겠지만 어떻게 하는지는 모르겠다.
기본 DB가 test인데 내가 가지고 있는 mysql 서버에는 test DB조차 없다.
root 계정도 비밀번호가 있어서 어쨌든 DB 테스트는 실패로 끝났다.

$HOME/.cpan/ 디렉토리의 설치문서를 본다.

$ vi /root/.cpan/build/DBD-mysql-4.008/INSTALL.html

이런 부분이 있다.

CPAN installation

.....
If you cannot get the CPAN module working, you might try manual installation. If installation with CPAN fails because the your local settings have been guessed wrong, you need to ensure MySQL's mysql_config is on your path (see SOURCE INSTALLATION) or alternatively create a script called mysql_config. This is described in more details later. Configuration.
....

또 이런 부분도 있다.

Configuration

The install script ``Makefile.PL'' can be configured via a lot of switches. All switches can be used on the command line. For example, the test database:

  perl Makefile.PL --testdb=<db>

If you do not like configuring these switches on the command line, you may alternatively create a script called mysql_config. This is described later on.

Available switches are:

testdb

   Name of the test database, defaults to test.

testuser

   Name of the test user, defaults to empty. If the name is empty, then the currently logged in users name will be used.

testpassword

   Password of the test user, defaults to empty.

testhost

   Host name or IP number of the test database; defaults to localhost.

testport

   Port number of the test database

ps-protcol=1 or 0

   Whether to run the test suite using server prepared statements or driver emulated prepared statemetns. ps-protocol=1 means use server prepare, ps-protocol=0 means driver emulated.

cflags

   This is a list of flags that you want to give to the C compiler. The most important flag is the location of the MySQL header files. For example, on Red Hat Linux the header files are in /usr/include/mysql and you might try

     -I/usr/include/mysql

   On Windows the header files may be in C:\mysql\include and you might try

     -IC:\mysql\include

   The default flags are determined by running

     mysql_config --cflags

   More details on the C compiler flags can be found in the following section. Compiler flags.

libs

   This is a list of flags that you want to give to the linker or loader. The most important flags are the locations and names of additional libraries. For example, on Red Hat Linux your MySQL client libraries are in /usr/lib/mysql and you might try

     -L/usr/lib/mysql -lmysqlclient -lz

   On Windows the libraries may be in C:\mysql\lib and

     -LC:\mysql\lib -lmysqlclient

   might be a good choice. The default flags are determined by running

     mysql_config --libs

   More details on the linker flags can be found in a separate section. Linker flags.

If a switch is not present on the command line, then the script mysql_config will be executed. This script comes as part of the MySQL distribution. For example, to determine the C compiler flags, we are executing

  mysql_config --cflags
  mysql_config --libs

If you want to configure your own settings for database name, database user and so on, then you have to create a script with the same name, that replies

 
=head2 Compiler flags

Note: the folling info about compiler and linker flags, you shouldn't have to use these options because Makefile.PL is pretty good at utilising mysql_config to get the flags that you need for a successful compile.

It is typically not so difficult to determine the appropriate flags for the C compiler. The linker flags, which you find in the next section, are another story.

The determination of the C compiler flags is usually left to a configuration script called mysql_config, which can be invoked with

  mysql_config --cflags

When doing so, it will emit a line with suggested C compiler flags, for example like this:

  -L/usr/include/mysql

The C compiler must find some header files. Header files have the extension .h. MySQL header files are, for example, mysql.h and mysql_version.h. In most cases the header files are not installed by default. For example, on Windows it is an installation option of the MySQL setup program (Custom installation), whether the header files are installed or not. On Red Hat Linux, you need to install an RPM archive mysql-devel or MySQL-devel.

If you know the location of the header files, then you will need to add an option

  -L<header directory>

to the C compiler flags, for example -L/usr/include/mysql.


# cd ~/.cpan/build/DBD-mysql-4.008
# perl Makefile.PL --testdb=xxxx --testuser=xxxx --testpassword=xxxx --testhost=localost
# make
# make test
테스트할때 중간쯤 오래걸릴때가 있다. 그럴땐 가볍게 Ctrl-C..

# make install
# perl -MDBD::mysql -e 'print "$DBD::mysql::VERSION\n"'
4.008

운영체제는 FreeBSD 5.4 이고 perl 버전은 5.8.6, mysql 버전은 4.1.18 이다.

KLDP 컨퍼런스가 다가왔다.

지난 스터디때 pung96님께 빼앗은(?) Perl OneLiner에 대한 준비와 가물가물한 awk, sed ...

공부 해야겠다.

GeoIP

컴퓨터/Programming 2008/06/05 13:38

ip나 host로 해당 지역이 어딘지 알 수 있다.

maxmind 에서 C,perl,php,java,python,ruby,vb 등 여러 언어로(심지어 자바스크립트로도 제공) GeoIP 기능을 사용할 수 있는 Geo API 를 제공한다.

perl의 Geo::IP::PurePerl 모듈을 제외하고는 모든 언어의 API에 GeoIP C Library가 설치되어 있어야 한다.

perl 같은 경우,
Geo::IP 는 C Library가 설치되어 있어야 하지만 속도가 빠른반면 Geo::IP::PurePerl 모듈은 속도는 느리지만 C Library가 설치되지 않아도 사용할 수 있다는 장점이 있다.

LGPL 라이센스를 따르는 GeoLite Country는 해당 데이터베이스 파일(GeoIP.dat)을 매달 1일 마다 업데이트해 무상으로 제공한다.

GeoIP.dat 파일 다운로드


젠투에서 GeoIP C Library 설치
# emerge dev-libs/geoip

CPAN에서 Geo::IP 모듈 설치
# cpan
cpan> install Geo::IP
cpan> quit



Geo::IP에 대한 내용은 perldoc 이나 CPAN 에서 참조한다.

일단 perl을 설치한다.
http://www.perl.com

D:\Perl 에 설치되어 있다고 가정하고,


awstats를 다운받는다.
http://awstats.sourceforge.net

압축을 해제하든 exe 파일을 실행시키든 어쨌든 설치한다.
D:\awstats 에 설치되었다고 가정한다.


D:\awstats\wwwroot\cgi-bin\ 폴더를 해당 webroot/awstats/ 에 카피한다.
D:\awstats\wwwroot\icon\ 폴더를 해당 webroot/awstats/ 에 카피한다.

웹사이트명을 mylog.com 이라고 가정하면,

webroot/awstats/cgi-bin/awstats.model.conf 파일을 같은 폴더에 복사한다.
파일명은 반드시 awstats.mylog.conf 로 한다.

awstats.mylog.conf 파일을 편집한다.

LogFile="D:\LogFiles\W3SVC12345678\ex%YY-24%MM-24%DD-24.log
LogType=W
LogFormat=2
SiteDomain="mylog.com"
DirIcons="/awstats/icon"
AllowAccessFromWebToFollowingIPAddresses="192.168.0.1-192.168.0.254"
UseFramesWhenCGI=0
Lang="ko"


도스창에서 실행한다.
D:> perl awstats.pl -config=mylog -update

기본적으로 awstats는 현재날짜의 로그를 적용하지 않는다.
그래서 보통 매일새벽에 스케줄링으로 업데이트를 한다.

브라우저에서 실행시킨다.

http://mylog.com/awstats/cgi-bin/awstats.pl?config=mylog

간혹, 텍스트만 출력되기도 하는데 그럴땐 브라우저에 다시 입력해보면 제대로 출력된다.
왜 그런지 이유는 모르겠음.



IIS설정을 확인해 보자.

먼저, IIS에서 perl을 해석할 수 있어야 한다.
IIS관리에서 mylog.com 의 속성->홈디렉토리->구성->매핑 탭에 들어가서 "pl" 확장자를 추가한다.
이때 실행파일을 D:\perl\bin\perl.exe 로 하면 안되고 D:\perl\bin\perlis.dll 로 해야한다.

당연하겠지만 "W3C 확장 로그 파일 형식"으로 IIS 로그사용에 체크되어 있어야 한다.
로깅 속성은 다음과 같다.

date
time
c-ip
cs-username
cs-method
cs-uri-stem
cs-uri-query
sc-status
sc-bytes
cs-version
cs(User-Agent)
cs(Referer)

위 내용빼고는 전부 체크해제해야 한다.
간혹, 윈도우즈 서버의 버전 또는 IIS 버전에 따라 기본속성이 틀릴수 있으니 반드시 확인해 봐야한다.

자세한 내용은 awstats 웹사이트의 doc을 확인해라.

http://awstats.sourceforge.net/docs/index.html

부럽다..ㅠㅠ

http://jeen.tistory.com/tag/yapcasia2008


http://aero.dnip.net/blog/

http://www.perlmania.kr/bbs/bbs.html?mode=read&table=free&article=6368&page=1

#!/usr/bin/perl -w

#############################################################
# 파일명 : E:\perl\test\daum\daum_ftp.pl
# 작성자 : 고기스님 (gogisnim@gmail.com)
# 작성일 : 2008.05.09
# 사용법 : perl E:\perl\test\daum_ftp.pl [all|new|del]
# 설명    : daum 검색 데이터를 ftp로 제공한다.
#             스케줄에 등록하고 매일 새벽 자동실행된다.
# 주의    : new 일때 실행후 관련 파일은 자동 삭제된다.
#             따라서 del 옵션은 실제로는 필요가 없다.
#############################################################

use strict;
use warnings;
use Net::FTP;

my $ftp;
my $host = "myhost.test.com";
my $port = "2121";
my $user = "someuser";
my $pwd = "somepassword";
my $local_dir = "E:\\inetpub\\test\\daum\\";
my $target_dir;
my $fh;

my @real_files;


##### 파라미터 갯수를 체크하고 옵션(all, new, del) 값을 저장 #####
die "ARGV failed !!!" unless $#ARGV == 0;
my ( $opt ) = @ARGV;

##### all 일 경우 #####
if ( $opt eq "all" ) {
# 업로드할 파일 목록을 배열에 저장한다.
push @real_files, $local_dir.$opt."\\static.source.0";

##### new 또는 del 일 경우 #####
} else {
$target_dir = $local_dir.$opt;
opendir $fh, $target_dir
or die "file handle failed: $! \n";
while ( my $tmp_f = readdir $fh ) {
if ( ! -d $tmp_f ) { # 디렉토리는 포함하지 않는다.
  # 업로드할 파일 목록을 배열에 저장한다.
  push @real_files, $local_dir.$opt."\\".$tmp_f;
}
}
closedir $fh;
}

##### ftp 커넥션 #####
$ftp = Net::FTP->new($host, Port=>$port, Debug=>0)
or die "Cannot connect host $host : $@";


##### ftp 사용자 로그인 #####
$ftp->login($user, $pwd)
or die "cannot login ", $ftp->message;


##### 윈도우즈에서는 텍스트파일의 라인 마지막 1 byte가 짤렸다. #####
##### 이를 해결하기위해 binary 메소드를 호출한다.    #####
##### 리눅스/유닉스에서는 없어도 정상 작동한다.     #####
$ftp->binary;


##### 파일 전송 #####
foreach my $f ( @real_files ) {
$ftp->put($f)
or die "put failed ", $ftp->message;
}


##### ftp 커넥션 종료 #####
$ftp->quit;


##### new 또는 del 일 경우 로컬파일을 삭제한다 #####
if ( $opt ne "all" ) {
foreach my $del_f ( @real_files ) {
unlink($del_f);
}
}


binary

Transfer file in binary mode. No transformation will be done.

Hint: If both server and client machines use the same line ending for text files, then it will be faster to transfer all files in binary mode.


http://search.cpan.org/~gbarr/libnet-1.22/Net/FTP.pm