회사동료로부터 알게된 귀중한 팁^^




출처 : http://blog.linuxfriend.org/?tag=stdbufhttp://www.pixelbeat.org/programming/stdio_buffering/


pipe 사용시 커널에서 버퍼를 두어 버퍼가 찰 때까지 대기해야 하는데. 이 이슈는 fflush로 쉽게 해결할 수 있다. pipe 사용시 강제 fflush를 해주게 하는 stdbuf 명령어를 사용하면 된다. 



$ tail -f abc.log | grep --line-buffered new_word | tee filtered.log

->

$ stdbuf -oL tail -f abc.log | stdbuf -oL grep  new_word | tee filtered.log









Posted by '김용환'
,


mac과 linux(ubuntu)에서 환경변수 JAVA_HOME 지정 하기


<MAC OS> 

http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/


 $ /usr/libexec/java_home

/Library/Java/JavaVirtualMachines/jdk1.7.0_65.jdk/Contents/Home


$ export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_65.jdk/Contents/Home"




<Linux-ubuntu>

https://www.digitalocean.com/community/tutorials/how-to-install-java-on-ubuntu-with-apt-get


$ sudo update-alternatives --config java


$ sudo nano /etc/environment


$ JAVA_HOME="YOUR_PATH"


$ source /etc/environment


Posted by '김용환'
,

linux screen

unix and linux 2014. 8. 27. 10:57

linux screen : nohup처럼 계속 리눅스 명령이 동작되게 한다.



$ screen

[detached]


(배치 작업)

$ mysql 덤프 작업

..

(ctrl + a+ d) 하면 shell로 이동


$ screen -list

There is a screen on:

23455.pts-0.alpha-google (Detached)

1 Socket in /var/run/screen/S-deploy.


$  screen -r 23455.pts-0.alpha-google

(배치 작업 확인)



https://kldp.org/node/18744

http://kevinx64.tistory.com/337

http://www.rootman.co.kr/board/bbs/board.php?bo_table=linux&wr_id=557&page=5



* 사용상 유의할 점

- ctrl + c으로 프로세스 종료시에는 사용할 수 없다.  ctrl + a + d로 화면을 종료(detached)시킨다. 

- 터미널 비정상 종료시를 염두해서 매우 좋은 효과를 가질 수 있다. (bg, fg 안녕~)

- screen -list로 나오는 결과에 숫자.blahblah 의 숫자를 이용해서 attach 할 수 있다. (screen -r 숫자)

- attach는 오직 하나의 터미널에서만 가능하다. 누군가 독점하면 쓸 수 없다. (only one user attach)

 


스크린 모든 프로세스를 shutdown한다.

$ screen -wipe

Posted by '김용환'
,


vi 에서 탐색기를 쓰려면 nerdtree / janus를 활용하면 된다.

1. janus 설치

$ brew install macvim

$ curl -Lo- https://bit.ly/janus-bootstrap | bash


2. nerdtree

$ mkdir -p ~/.vim/bundle
$ cd ~/.vim/bundle
$ git clone https://github.com/scrooloose/nerdtree.git



3. nerdTree
vi 또는 vim 실행 후 :NERDTree 명령실행



* Short cut 설명

:NERDTreeToggle - NERDTree 명령 실행 이후 원래 화면으로 돌아갈 때 사용 

 ctrl ww   -  창 이동


== 탭 관련

T - NERDTree에서 파일을 선택하고 T를 입력하면 탭 생성 (그냥 t를 선택하면 NERDTree 화면이 없는 탭 생성)

gT, gt - Tab 이동


== 창 관련

ctrl + q 하고 w - 열려있는 창 닫기

ctrl ww 또는 ctrl wh - 창 간의 이동




Posted by '김용환'
,


회사 지인이 알려준 좋은 팁 - expect 이용시 창 크기가 바뀌어도 터미널에서 반영못한 현상을 해결

http://ubuntuforums.org/showthread.php?t=865420



아래 코드를 #!/usr/bin/env expect 밑에 추가하면 됨.

Code:
trap {
 set rows [stty rows]
 set cols [stty columns]
 stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH

실제 예

Code:
#!/usr/bin/env expect

#trap sigwinch and pass it to the child we spawned
trap {
 set rows [stty rows]
 set cols [stty columns]
 stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH

set username yourUserNameHere
set pass yourPasswordHere
set host theIpAddressToConnectTo

spawn ssh ${username}@${host}

expect -re "password:"
send "${pass}\r"

expect -re "$"

# now interact with the session
interact


Posted by '김용환'
,


개발서버에 공인 인증서를 설치하는 것은 부담스럽다. 따라서 10년에서 30년짜리 사설 인증서를 일반적으로 따로 설치해서 사용한다. 

curl로 https 요청하면  SSL certificate problem: Invalid certificate chain 에러가 발생한다.


$> curl 'https:/1.1.1.1/aaaaa'


curl: (60) SSL certificate problem: Invalid certificate chain

More details here: http://curl.haxx.se/docs/sslcerts.html


curl performs SSL certificate verification by default, using a "bundle"

 of Certificate Authority (CA) public keys (CA certs). If the default

 bundle file isn't adequate, you can specify an alternate file

 using the --cacert option.

If this HTTPS server uses a certificate signed by a CA represented in

 the bundle, the certificate verification probably failed due to a

 problem with the certificate (it might be expired, or the name might

 not match the domain name in the URL).

If you'd like to turn off curl's verification of the certificate, use

 the -k (or --insecure) option.




쉽게 해결하려면 -k 추가 하면 된다. insecure 하게 통신하게 하도록 하도록 옵션을 주다. 


-k, --insecure

(SSL) This option explicitly allows curl to perform "insecure" SSL connections and transfers. All SSL connections are attempted to be made secure by using the CA certificate bundle installed by default. This makes all connections considered "insecure" fail unless -k, --insecure is used.

See this online resource for further details: http://curl.haxx.se/docs/sslcerts.html



$> curl  -k 'https:/1.1.1.1/aaaaa'



Posted by '김용환'
,


윈도우에서는 서버 터미널 접속시 한글깨짐이 발생하지 않는데,

Mac에서는 서버 터미널 접속시 한글꺠짐이 발생한다고 해서 다음과 같이 가이드를 했다. 




1. 터미널 한글깨짐 해결하기 

export LANG=ko_KR.UTF-8


(locale -a | grep ko_KR로 미리 확인 필요)




2. vi 한글깨짐 해결하기


~/.vimrc 파일에아래 encoding, fileencodings 를 아래와 같이 추가(수정)하기


   set encoding=utf-8

   set fileencodings=utf-8,euckr


euckr되신 cp949를 넣어야 함.. 

Posted by '김용환'
,


1. sh대신 source

bash에서 재사용성을 높이기 위해서 환경설정 파일을 읽어서  (include file 개념) 처리해야 하는 상황이다.

export 만 정의하는 스크립트가 있고, 실행스크립트들이 export 스크립트를 재사용하여 편하게 스크립트 개발을 할 수 있게 하려고 한다. 

이때 sh 이 아닌 source를 쓰는 것이 좋다. 



export.sh


#!/bin/sh

export A=/development/work



exe.sh


#!/bin/sh

sh export.sh

export A


위와 같이 sh 명령어를 사용하면 출력되는 결과는 없다. export.sh 를 실행만 시키고 context는 공유하지 못한다는 뜻이 된다. 즉 하나의 export.sh 프로세스를 실행하고 exe.sh에는 아무 영향을 주지 말라는 뜻이다. 그냥 실행의 의미이다. 


=> 따라서 export.sh의 내용을 영향을 받게 하기 위해서는 sh 대신 source를 사용하면 된다.


#!/bin/sh

source export.sh

export A




2. -bash: export: `path..': not a valid identifier


원인은 export 하는 변수의 이름에 허용하지 않은  charactor를 넣었을 때 발생한다.

'-'는 허용하지 않는다. 


만약 쓰고 싶으면, export yyy='\x41\x42\x43'  이렇게 쓰면 된다.

Posted by '김용환'
,


nagios 실행 명령어는 bin/nagios  이다.

그런데, 이 bin/nagios 실행후 이게 데몬으로 실행되어야 잘 동작한다. 이 부분을 잘 쓸 수 있도록 script를 생성했다. 


bin/nagios 명령어의 파라미터 옵션은 다음과 같다. 


Options:


  -v, --verify-config          Verify all configuration data

  -s, --test-scheduling        Shows projected/recommended check scheduling and other

                               diagnostic info based on the current configuration files.

  -x, --dont-verify-paths      Don't check for circular object paths - USE WITH CAUTION!

  -p, --precache-objects       Precache object configuration - use with -v or -s options

  -u, --use-precached-objects  Use precached object config file

  -d, --daemon                 Starts Nagios in daemon mode, instead of as a foreground process







check-nagios-config.sh


#!/bin/bash


CUR_PWD=`pwd`

NAGIOS_HOME=/app/tomcat/nagios/nagios

cd $NAGIOS_HOME

bin/nagios -v etc/nagios.cfg

cd $CUR_PWD






restart-nagios.sh


#!/bin/bash



# start bin/nagios

CUR_PWD=`pwd`

NAGIOS_HOME=/app/nagios

cd $NAGIOS_HOME


# syntax check(verification), precache object creation

bin/nagios -v -p -s etc/nagios.cfg


if [[ $? > 0 ]]; then 

    echo 'there are some error. check configs'

    exit $?;

else 

    PID=`ps -ef | grep bin/nagios | grep -v grep | awk '{print $2}'`

    if [ -n "$PID" ]; then 

        kill -9 $PID;

        echo "bin/nagios killed."

    fi

    # precache object use

     bin/nagios -u -d etc/nagios.cfg

     echo 'start nagios...'

fi




Posted by '김용환'
,

nagios ncsa 연동

unix and linux 2013. 10. 2. 12:09

* nagios에서 nsca 연동 간단 설명 


이 자료가 가장 좋은 자료인 듯 하다. 

http://nagios.sourceforge.net/download/contrib/documentation/misc/NSCA_Setup.pdf


만약 이해가 잘 안가거나 debug 설명을 더 보고 싶으면 소스 보는 것을 추천한다. 그다지 어렵지 않다. 

nsca 디렉토리의 홈을 /app/nsca라고 가정했다.



1. nsca 데몬을 찾아 저장한 후, inet또는 xinet 데몬으로 설치한다.

http://sourceforge.net/projects/nagios/files/nsca-2.x/
이 안에 readme 파일이 있는데. 그대로 따라하면 된다. 


2. 서버 설정

nsca.cfg 파일

만약 debug=1로 수정후 nsca 데몬 재시작하면 보다 많은 정보를 확인할 수 있다.

syslog로 debug 출력이 되어 있는데. 기본 디폴트로 /var/log/message에 로그를 저장하도록 되어 있다. 

그리고 command_file 설정을 한후, 테스트를 진행한다. 

command_file=/app/nsca/var/rw/nagios.cmd 


nagios.cmd 파일은 일종의 pipe file이고, 추후 nagios 연동시 이 파일을 통해서 전달하도록 되어 있으므로, 신경을 잘써야 한다. 테스트하다가 이런 로그를 볼 수 있다.(Could not create external command file '/app/nsca/var/rw/nagios.cmd' as named pipe: (17) -> File exists.  If this file already exists and you are sure that another copy of Nagios is not running, you should delete this file.)




3. 클라이언트 테스트

클라테스트 정보는  

nagios홈/libexec/eventhandlers/distributed-monitoring>$ cat submit_check_result_via_nsca 

printfcmd="/usr/bin/printf"


NscaBin="/usr/local/nagios/libexec/send_nsca"

NscaCfg="/usr/local/nagios/etc/send_nsca.cfg"

NagiosHost="nagioshost"


# Fire the data off to the NSCA daemon using the send_nsca script

$printfcmd "%s\t%s\t%s\t%s\n" "$1" "$2" "$3" "$4" | $NscaBin -H $NagiosHost -c $NscaCfg



테스트 예제


>$ printf "%s\t%s\s\t%s\t%s\n" NSCA-Client-Host-Name TestMessage 0 "test" | /app/nsca/bin/send_nsca -H NSCA-Host-Name -c /app/nsca/etc/send_nsca.cfg


4. 서버 로그 확인

syslog에 로그가 제대로 남는지 확인. nsca client와 nsca server간의 통신 확인. command 파일에 nsca client가 전달한 데이터가 남음.


---- 여기까지가 nsca client와 nsca server간의 통신 체크 확인정도까지 완료.


5. nagios 연동


commands.cfg 파일 수정


define command{

    command_name check_dummy

    command_line $USER1$/check_dummy $ARG1$

}




services.cfg

# nsca 

define service{

name passive-service

use generic-service

register 0

active_checks_enabled 0

passive_checks_enabled 1

flap_detection_enabled 1

is_volatile 0

check_period 24x7

max_check_attempts 1

normal_check_interval 5

retry_check_interval 1

check_freshness   0

contact_groups admins

check_command check_dummy!0

notification_interval 120

notification_period 24x7

notification_options w,u,c,r 

stalking_options w,c,u

}


# nsca - client

define service{

use passive-service

service_description 서버이름:case1

hostgroup_name work-servers

}




* 트러블 슈팅 정보

1. Could not open alternate dump file '/app/nsca/var/rw/nsca.dump' for appending


1) /app/nsca/var/rw/ read write하게 할 수있도록 권한 부여 

2) touch  /touch /app/nsca/var/rw/nagios.cmd


성공시 아래와 같은 로그 출력(syslog)

SERVICE CHECK -> Host Name: 'NSCA-Client-Host-Name', Service Description: 'TestMessage', Return Code: '0', Output: 'test'





Posted by '김용환'
,