AWS ec2 에서 최근에는 ntp보다 chrony를 많이 사용한다.
1. sudo vi /etc/chrony.conf 에서
server 169.254.169.123 prefer iburst
를 넣는다. 1줄만 있어도 된다.
2. sudo systemctl restart chronyd
3. chronyc sources -v
-> 소스서버가 제대로 반영되었는지 확인 (check)
4. date 로 시간확인.
AWS ec2 에서 최근에는 ntp보다 chrony를 많이 사용한다.
1. sudo vi /etc/chrony.conf 에서
server 169.254.169.123 prefer iburst
를 넣는다. 1줄만 있어도 된다.
2. sudo systemctl restart chronyd
3. chronyc sources -v
-> 소스서버가 제대로 반영되었는지 확인 (check)
4. date 로 시간확인.
1. 폰트 위치는 /usr/share/fonts/arial
이며, msttcore 폴더 밑에 ms 기본 폰트들이 있는지 확인가능.
2. 없을시 설치 방법.
a. $wget https://www.itzgeek.com/msttcore-fonts-2.0-3.noarch.rpm
b. sudo rpm -Uvh msttcore-fonts-2.0-3.noarch.rpm
c.
sudo fc-cache -f -v
#!/bin/bash
while sleep 5; do
PROCESS_NUM=`ps -ef | grep -v grep | grep -v attach | grep geth | wc -l`
if [ $PROCESS_NUM -ge 1 ]; then
echo $PROCESS_NUM"process"
else
echo "not running ! RESTARTING" $(date)
./start.sh
fi
done
단, 실제로 $ps -ef | grep -v grep | grep -v attach | grep geth | wc -l 한 결과보다
스크립트에서 찍는 결과가 1이 더 큰 값이 나오는데.. 왜 그런지 조사 중.
$ lsof -i :8080 (8080포트를 사용하고 있는 process id를 알려줌)
sed 로 치환's/4.5.0-SNAPSHOT/4.7.0-SNAPSHOT/g'
명령을 써서 다른 파일에 저장하는 건 간단하지만
같은 파일에 저장하고 싶을때는 -i 옵션을 써야 한다.
하지만 맥에서는 -i 옵션 뒤에 항상 파라미터가 필요해서 '' 를 넣어주면 잘 동작한다.
예) sed -i '' 's/4.5.0-SNAPSHOT/4.7.0-SNAPSHOT/g' pom.xml
UDP traceroute:
traceroute 125.152.0.117 -s 220.75.130.5 -p 5160 -U
linux에서 c로 개발한 후, 코드를 검사하는 방법 몇가지..
Valgrind: REF-SITE
- 메모리 오류 체크, 메모리 leak 체크.
특히 메모리 오류가 가장 짜증나는 부분인데 이런 부분을 제법 잡아주므로 꼭 돌릴 필요가 있다.
- 사용법:
$gcc test.c -o app_test
$valgrind --leak-check=yes ./app_test
CppCheck http://cppcheck.sourceforge.net/
- Linux버전도 있고, pc버전도 있으며, 파일 단위나 폴더단위로 소스를 검사.
메모리 누수/배열 범위/멀티 Thread 등이 check됨.
gcov REF-SITE
- 사용(혹은 TEST) 이 안되고 있는 코드 체크, 코드별 실행 횟수 및 %가 나온다.
- 사용법:
$gcc -fprofile-arcs -ftest-coverage tmp.c
$./a.out
$gcov tmp.c
gprof
- 코드 성능 분석
간혹 네트웍이 몇초간 접속 안하면
세션이 끊어지도록 구축된 경우가 있다.
이런 경우 네트웍이 끊어지지 않도록 계속 연결을 물고 있으면 편하므로
아래와 같은 sell script를 만들어 연결을 유지하곤 한다.
#!/bin/sh
while sleep 2; do
telnet server_ip server_port << EOF
quit (서버에서 결종료 명령어.. 없으면 안써도 될듯)
EOF
done
vrrp가 A/B 서버간에 메시지를 broadcating하는데
근래 OS들이 이 broadcast들을 default로는 막는 경우가 존재한다.
조치:
echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
CentOS 6.3을
커널 2.6.32-279에서 2.6.32-358.14.1 로 update해보았다.
일단 binary를 받을 수 있는 URL은
-기본 버전: http://vault.centos.org/6.4/os/x86_64/Packages/ kernel-xx-.14.1.el6.x86_64.rpm
-update 버전: http://vault.centos.org/6.4/updates/x86_64/Packages/ kernel-xx.el6.x86_64.rpm
최초에 기본버전이 나오고 마이너 update버전이 나오게 되므로
보통 update버전을 많이 설치하는 것으로 보인다.
kernel은 간단하게 rpm -ivh xx.rpm으로 설치가 된다.
하지만 dependecy문제가 발생하게 되므로
1. kernel-firmware-xx.xx 먼저설치
2. kernel-devel-xx.xx 설치
3. kernel rpm 설치.. 옵션을 --nodeps를 주면 dependency없이 설치 가능.
서버가 접속이 안될 경우를 대비해
HP에서는 ILO (Integrated Light Out) 기능을 제공 한다.
독립적인 Ethernet포트를 이용해
OS에서 사용하는 것과 다른 IP어드레스와 user/비번을 제공한다.
1. ssh 터미널로 초기접속하게되면 아래와 같은 커서가 뜨게 된다.
=====================================
</>hpiLO->
2. 웹브라우저로 https://서버IP 로 접속하면
웹기반 GUI가 제공된다.
==> 접속후 보통 Remote Console (IRC)로 파워 on/off, OS설치, keyboard 입력 등의 작업을 한다.
IRC를 뛰우면 OS 로그인 prompt가 기본적으로 뜨고.. 상단메뉴에 PowerSwitch / Virtual Drives / Keyboard 가 존재한다.
list of Open File. 특정파일을 access하고 있는 프로세서들을 나열한다.
예)
$lsof mylogfile
$lsof /proc
가변 파라미터를 받아서 사용하는 방법: (vprintf로 출력가능 한데)
=> 약간 변조하고 싶을 때에는 vsprintf를 사용하면 된다...
#include <stdarg.h>
void logPRINTD(const char* format, ...){
char str[512];
va_list args;
va_start(args, format);
vsprintf(str, format, args); //str로 옮기기
strcat(str,"\n"); ///////////////////// str에 \n 더하기
va_end(args);
//str로 하고싶은일 하기. bla bla
}
리눅스에서 실제 라우팅이 되는지 체크하는 명령어는
$traceroute 123.45.123.45 이다.
라우팅이 안되어 있다면
$route add -net 125.159.63.14 netmask 255.255.255.255 gw 14.63.134.254 dev eth4 명령으로 추가가능.
삭제시에는
$ route del -net 118.49.2.0 netmask 255.255.255.0 명령어로 사용.
라우팅 테이블 확인은
$route 명렁어이다. 추가와 삭제 후에 이 명령어로 확인하면 된다.
(맥북에서는 $netstat -nr 이 비슷하네요)
=====껐다켜도 되게 하려면 아래 정보 추가=================
/etc/sysconfig/network-scripts/route-eth4
ADDRESS0=14.63.237.0
GATEWAY0=10.217.80.1
NETMASK0=255.255.255.0
참조: http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Beginning/PthreadApiReference
Thread의 상태:
PTHREAD_CREATE_JOINABLE : 다른 thread끝나고 동작하는 thread. (exit나 join을 호출을 통해서 자원을 반납해야 하는 thread.)
PTHREAD_CREATE_DETACHED : 독립적으로 동작하므로 종료시점 체크필요없고, 종료시 자동자원반납.
<구조체>
typedef long pthread_t;
struct pthread_attr { void *stackaddr; size_t stacksize; int detachstate; struct sched_param param; int inheritsched; int contentionscope; }; typedef struct pthread_attr pthread_attr_t;
#define PTHREAD_CREATE_JOINABLE 0 #define PTHREAD_CREATE_DETACHED 1
<예제 - 심플 detatched thread 생성. >
pthread_t id;
pthread_attr_t attributes;
// initialize thread attributes
pthread_attr_init(&attributes)
pthread_attr_setdetachstate( &attributes, PTHREAD_CREATE_DETACHED);
//create a new thread
pthread_create( &myId, &attributes, startFunc, args); //args는 startFunc로 전달.
pthread_attr_destroy(&attributes); //자원해제
<함수 prototype>
struct hostent *gethostbyname(const char *name);
int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop);
두 함수 모두 return type은 hostent struct 이다.
<struct hostent 구조 >
struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */
==> 아래쪽에 in_addr구조체의 s_addr 변수 참조. 같은 형태임. 0xff01ffff의 네트웍바이트(순서대로) 형태(255.1.255.255)
} #define h_addr h_addr_list[0] /* for backward compatibility */ The members of the hostent structure are:
h_addrtype The type of address; always AF_INET or AF_INET6 at present. h_length The length of the address in bytes. h_addr_list An array of pointers to network addresses for the host (in net- HOST_NOT_FOUND The specified host is unknown. NO_ADDRESS or NO_DATA The requested name is valid but does not have an IP address. NO_RECOVERY A non-recoverable name server error occurred. TRY_AGAIN A temporary error occurred on an authoritative name server. Try again later.
<그 외 network관련 struct들 >
struct sockaddr_in { sa_family_t sin_family; /* address family: AF_INET */ in_port_t sin_port; /* port in network byte order */ struct in_addr sin_addr; /* internet address */ }; /* Internet address. */ struct in_addr { uint32_t s_addr; /* address in network byte order */ };0xffffffff의 네트웍바이트 형태.=255.255.255.255
<in_addr_t inet_addr(hostname) 함수> 이름을 0xffffffff (255.255.255.255 효과) 형태로 변환리턴.
리턴type: typedef uint32_t in_addr_t;
INADDR_NONE= -1 (255.255.255.255)을 리턴하는 경우. 약간문제가 될때도 있으나 거의 괜찮음.
c++하나를 불러쓰는 경우
wrapping layer를 만들어서,
c언어에서 불러쓰면 된다.
예) c++파일 안에서
extern "C" {
MyClass* myclass_new()
{
return new MyClass();
}
..몇개 함수 더 매핑.
}
이렇게만 하면,
main. c파일안에서 아래와 같이 호출이 가능하다.
struct MyClass *m = myclass_new();
그리고 build시에는 특히 c빌드시(혹은 최종 link시에)
gcc main.c -lstdc++ 추가 필요....
참고 blog: http://ospace.tistory.com/215
아주 유용하게 쓰고 있는 자동접속 script.
전문가가 ssh_stdin 을 개발해 주셔서, 이를 이용해 쓰고 있다.
===================================자동접속 + 작업 SCIRPT ==============
#!/bin/sh
PASSWD="myPasswd!"
curDir=$(pwd)
SSH_STDIN=$curDir/ssh_stdin
sshOption="-T -o StrictHostKeyChecking=no -o ConnectTimeout=1 -o NumberOfPasswordPrompts=1"
SVR_LIST="172.25.49.135 172.25.49.136"
mpList=$(eval echo $SVR_LIST)
for i in $mpList
do
echo "---------"$i
echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "ps -ef|grep redis"
echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "nstatus"
#scp를 하고 싶을때는 .. -T옵션 빼고.. $1에 파일이름 줘서.. 아래처럼. 하면 된다.
echo $PASSWD | $SSH_STDIN scp $sshOption $1 "root@"$i":"$1
done
=============================ssh_stdin내용=================================
#!/bin/bash
if [ -n "$SSH_ASKPASS_PASSWORD" ]; then
cat <<< "$SSH_ASKPASS_PASSWORD"
elif [ $# -lt 1 ]; then
echo "Usage: echo password | $0 <ssh command line options>" >&2
exit 1
else
read SSH_ASKPASS_PASSWORD
export SSH_ASKPASS=$0
export SSH_ASKPASS_PASSWORD
[ "$DISPLAY" ] || export DISPLAY=dummydisplay:0
# use setsid to detach from tty
# exec setsid "$@" </dev/null
exec setsid "$@"
fi
SIGINT 라고 가끔 본 적이 있을 것이다.
이 것은 Interrupt 시그널을 의미한다.
Interrupt (^c) 시그널은 2
Quit (^\) 시그널은 3
EOF(or Exit ^D) 시그널은 1
이 중에서 2,3번 시그널이 shell script가 도는 동안에 동작안하게 하고 싶으면..
trap "" 2 3 <- 이렇게 무시를 걸어 놓으면 된다.
trap 2 3 reset <-shell script종료 후에는
Linux c개발시 shm 사용방법.
shmget : malloc 처럼 공유메모리 생성
shmat : 생성된 공유메모리를 해당 프로세서로 가져옴(첨부-attach)
shmdt : 가져온 메모리를 다시 반납. (분리-detach )
Linux를 하다보면, 터미널로 접속해서 프로세스를 실행시키고,
나중에 다시 접속해보면.. 죽어있는 경우가 있다.
- 백그라운드로 실행해도 그러하다..
( 백그라운드 실행은 명령어 뒤에 & 추가=> $shell.sh & )
이럴경우
1. nohup으로 실행 : $nohup shell.sh &
2. screen명령어로 실행.(화면까지 보존)
-------screen 사용법--------------
screen -S 스크린네임.
ctrl+a=>c생성
ctrl+a=>shift+a타이틀변경
ctrl+a=>shift+" 리스트
선택
ctrl+a=>c화면 클리어
ctrl+a=>d 나가기(리스트는 있고, 모드만 종료)
screen -r 모드진입(리스트 출력)
ctrl+a=>shift+" 리스트
ctrl+a=>shift+k 리스트선택 종료.
ctrl+a=>Shift+s 화면 분활 화면
ctrl+a=>tab 으로 화면 이동
ctrl+a=>shift+q 종료
ctr
멀티코어 linux에서 코어를 할당하는 방법:
taskset -pc
{해당 process를 기동할 core 번호} process-pid
예) taskset -pc 0
{process-pid}
만약 cloud상의 VM상에서
이와 같이 특정 core에 할당한 후에는 해당 VM을 reboot하여야 하며,
isolcpus 옵션이 grub.conf 파일에 추가되어서 VM이 생성되어야 한다.
<grub.conf>
# grub.conf generated by anaconda
#
# Note that you do not have to rerun
grub after making changes to this file
# NOTICE: You have a /boot
partition. This means that
# all kernel and initrd paths are
relative to /boot/, eg.
# root (hd0,0)
# kernel
/vmlinuz-version ro root=/dev/mapper/VolGroup-lv_root
# initrd
/initrd-[generic-]version.img
#boot=/dev/xvda
default=1
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title
CentOS (2.6.32-431.3.1.el6.x86_64)
root (hd0,0)
kernel
/vmlinuz-2.6.32-431.3.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root
rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us
rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto
rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd
/initramfs-2.6.32-431.3.1.el6.x86_64.img
title CentOS
(2.6.32-358.14.1.el6.x86_64)
root (hd0,0)
kernel
/vmlinuz-2.6.32-358.14.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root
rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us
rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto
rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd
/initramfs-2.6.32-358.14.1.el6.x86_64.img
title CentOS
(2.6.32-279.2.1.el6.x86_64)
root (hd0,0)
kernel
/vmlinuz-2.6.32-279.2.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root
rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us
rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto
rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd
/initramfs-2.6.32-279.2.1.el6.x86_64.img
title CentOS
(2.6.32-279.el6.x86_64)
root (hd0,0)
kernel
/vmlinuz-2.6.32-279.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root rd_NO_LUKS
LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us rd_LVM_LV=VolGroup/lv_swap
SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=VolGroup/lv_root rd_NO_DM
rhgb quiet isolcpus=0
initrd
/initramfs-2.6.32-279.el6.x86_64.img
-F_ 없어도 됨(2210)
echo ${JOB_NAME} | awk -F_ '{print $3}' |xargs -I {} rm -rf /tmp/doxygen/{};
수많은 프로세스들 한방에 죽이기
ps -ef | grep 키워드 | awk '{print $2}' | xargs -I {} sudo kill {}
find . -name "*.js" -print | xargs grep -n keywordToFind
(filename) (linenumber)
openssh-server를 설치하려고 하니..
openssh-server : Depends: openssh-client (= 1:6.6p1-2ubuntu1) 이런 에러가 뜬다.
이런 경우 다음방식으로 client를 먼저 설치하면 된다.
sudo apt-get install openssh-client=1:6.6p1-2ubuntu1
그외 sudo apt-get 명령어는
sudo apt-get --reinstall install xx
sudo apt-get remove xx
설치된 놈 조회
/var/cache/apt/archives 여기서 ls로 검색. ?
안될때는.. 그냥 sudo apt-cache search blabla 로...하면 됨.
java여러개 깔아서 하나 선택시에는
sudo update-alternatives --config java
sudo update-alternatives --config javac 이렇게 2번.
<서버에서 조회>
sudo apt-cache search xx
sudo apt-cache show xx
(apt-get 이 잘 안될때는)
sudjo apt-get dist-upgrade : 서버목록 업그레이드
sudo apt-get update : 목록 index update.
.deb 파일을 받아서 직접 설치하는 경우는
sudo dpkg -i *.deb 로 하면된다. 참고: http://egloos.zum.com/mcchae/v/10795420
<CentOS>에서는
일반적으로는 $yum install blabla로 하면된다.
rpm패키지 파일을 구했을때는 아래와 같이 한다.
rpm -qa | grep xx 정보조회
rpm -ivh xx.rpm 설치
rpm -e xx 제거
/etc/init.d/tomcat7 start
/etc/init.d/tomcat7 stop
/etc/init.d/tomcat7 restart
booting시에 자동으로 시작하는 기능은
$ sudo update-rc.d tomcat(7) defaults
제외는
$ sudo update-rc.d -f tomcat(7) remove
라고 입력합니다.
CentOS는 여기 참조: Ref-Site
[Redhat계열] Linux hostname변경
$ hostname : 이건 그냥 조회
$ hostname abc_server : 이렇게 세팅가능하며, 리부팅이 되면 원복이 되는 문제점 존재.
리부팅 시에도 적용되게 하려면
/etc/sysconfig/network 여기서
HOSTNAME=abc_server 이렇게 수정하도록 한다.
ftp에 접속해서 파일을 다 가져오는 shell script는 다음과 같다.
여기서 EOF 대신에 ENDFILE등 다른 임의의 단어를 사용해도 된다.
< autoFTP.sh 내용>
ftp -n 127.0.0.1 << EOF
user root pass1234
cd ftpserver
prompt off
binary
mget *.out
bye
EOF
흔히 보는 linux의 파일권한 type은 다음과 같다.
-rwsrwsrwt
1. 여기서 현재 '-'로 표시되어 있는
첫 글자가 c/b인 경우라면 device file을 뜻한다.
(모두 나열하면)
c: 캐릭터 입출력하는 device
b: 블록 단위로 입출력하는 device
p: named pipe
s: socket
D: door
2. 그리고
네번째, 일곱번째 글자가 s일경우 set-uid 또는 set-gid 비트임.
돌리는 동안 잠깐 super (root)가 된다. ps로 확인 가능
(/usr/bin/passwd 참고. ) 보안체크시 필수체크항목
3. 마지막 글자가
t:sticky 폴더는 타인이 못지우게 함 /tmp/ 용
0. 추가적으로 옵션설정방법:
chmod 에 6777 옵션을 줄 수 있는데
처음 6표시된 자리는
4: set-uid
2: set-gid
1: sticky
과 같은 용도로 사용한다.
Linux 및 unix에서는 파일이
[File명: inode번지] 로 관리가 된다. (ls –i 하면 inode 조회 가능하다)
여기서 inode번지는
è <inode table 구조> 를 참조하게 된다: (ls –l하면 나오는 정보들이라고 보면 된다)
1File Type
2Permission
3Hard Link Count (inode 번지 복사) 하드링크시 사용. ( 용법: ln f1 f2 이며 그 후에 : rm f1 해도 됨. )
단, 파티션이 다르면 번지중복으로 사용 불가
4Owner
5Group
6Size
7Time
8Point à data block저장소를 가르킴
symbolic link의 경우 point에 원본위치 있음 (ln -s f1 f2 로 지정)
Symbolic link장점: 1. 디렉토리도 된다,
2. 파티션 달라도 된다.
solaris에서는 하드링크를 주로 사용하고
linux에서는 심볼릭 링크(소프트 링크)를 주로 사용하게 된다.