2012년 4월 10일 화요일

System Administrator

사용자 계정

rsyoung 사용자 생성


[root@cent ~]#useradd rsyoung
[root@cent ~]# id rsyoung

uid=500(rsyoung) gid=500(rsyoung) groups=500(rsyoung)
[root@cent ~]# 

계정 삭제는 반드시 userdel -r로 해서 /home/ user directory를 제거해야한다. 왜냐하면, 삭제된 UID는 재사용되기 때문에 useradd로 생성한 사용자가 이전 사용자의 파일을 소유할 수 있어 보안의 문제가 발생할 수 있다.

그룹 dreamers 생성

[root@cent ~]# groupadd -g 601 dreamers

그룹 멤버로 추가 (-a 옵션사용)

[root@cent ~]# usermod -aG dreamers rsyoung
[root@cent ~]# 
[root@cent ~]# id rsyoung
uid=500(rsyoung) gid=500(rsyoung) groups=500(rsyoung),601(dreamers)
[root@cent ~]# 

shadow password 라이 확인

[root@cent ~]# cat /etc/shadow | grep rsyoung
rsyoung:$6$NKtePQa3i3uL4igb$Lgk7coKuzalMusvcEzaKkVzriz4mT6kkLR9ESYMVtjjmGMSwLRvV6d2peYlIxy2zIgSuHxRnnzYW5VBEvWojF1:15440:0:99999:7:::
[root@cent ~]# 

사용자 비활성화 (-L) - ! 확인

[root@cent ~]# usermod -L rsyoung
[root@cent ~]# 
[root@cent ~]# cat /etc/shadow | grep rsyoung
rsyoung:!$6$NKtePQa3i3uL4igb$Lgk7coKuzalMusvcEzaKkVzriz4mT6kkLR9ESYMVtjjmGMSwLRvV6d2peYlIxy2zIgSuHxRnnzYW5VBEvWojF1:15440:0:99999:7:::
[root@cent ~]# 

사용자 활성화 (-U)

[root@cent ~]# usermod -U rsyoung
[root@cent ~]# 
[root@cent ~]# cat /etc/shadow | grep rsyoung
rsyoung:$6$NKtePQa3i3uL4igb$Lgk7coKuzalMusvcEzaKkVzriz4mT6kkLR9ESYMVtjjmGMSwLRvV6d2peYlIxy2zIgSuHxRnnzYW5VBEvWojF1:15440:0:99999:7:::
[root@cent ~]# 

다음로그인시 암호 업데이트 강제 수행

[root@cent ~]# chage -d 0 rsyoung


현재 설정정보



[root@cent ~]# chage -l alice
Last password change : Apr 10, 2012
Password expires : never
Password inactive : never
Account expires : Apr 20, 2012
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
[root@cent ~]# 


계정정보 확인



[root@cent ~]# getent passwd rsyoung
rsyoung:x:500:500:Seo-Young Noh:/home/rsyoung:/bin/bash
[root@cent ~]# 


debug log file 생성하기

rsyslog (reliable syslog)를 이용하여 debug 정보를 로그로 만들 수 있다.

/etc/rsyslog.conf 파일에 다음 라인 추가

*.debug               var/log/debug.log

logger를 이용하여 debug 메시지 생성

[root@cent etc]# logger -p debug Hello This is Debug

/var/log/debug.log에 메시지가 생성되는지 검사

[root@cent etc]# tail -f /var/log/debug.log 
Apr 10 21:16:13 cent root: Hello This is Debug


logwatch 실행결과 전자우편으로 받아보기

/etc/logwatch/conf/logwatch.conf 파일에 다음 라인 추가

MailTo = <your email address>

logwatch의 default conf 파일은 /usr/share/logwatch/default.conf/logwatch.conf에 존재하지만, /etc/logwatch/conf/logwatch.conf에 설정된 값이 오버라이딩하게된다.

매일 새벽 1시에 logwatch를 수행하려면 crontab을 작성한다.


[root@cent etc]# crontab -e


1 0 * * *       logwatch

만약 매일 자정 1분에 logwatch를 시작하기로 되어있으나 문제가 발생하여 실핼을 못시킬 수 도 있다 이를 예방하려면, /etc/cron.daily에 cron job 생성한다.


logrotate

설정파일은 /etc/logrotate.conf

yum

yum list installed <package name>
yum list installed
yum info <package name>
yum install <package name>
yum remove <package name>
yum update <package name>
yum repolist
yum check-update
yum history
yum history list
yum history info <num>
yum history undo <num>


yum search 'web server'
yum grouplist -v
yum groupinstall @kde-desktop
yum install @kde-desktop

rpm

rpm -q samba-client
rpm -qa 
rpm -q zlib -l                # location
rpm -q httpd --scripts    # scripts 
rpm -q httpd -c              # conf files
rpm -q httpd -d              # document
rpm -q -p <local rpm packages> -l
rpm -q -p <local rpm packages> -c
rpm -q -p <local rpm packages> -d


yum localinstall <local rpm package>
yum localinstall --nogpgcheck <local rpm package>


/etc/yum.repos.d/*.repo 설정예

[root@cent yum.repos.d]# cat errata.repo 
[Updates]
name=Update Repository
baseurl=ftp://update.url.com/pub
gpgcheck=1
enabled=1
[root@cent yum.repos.d]# 


[root@cent yum.repos.d]# yum repolist
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
 * base: ftp.daum.net
 * extras: ftp.daum.net
 * updates: ftp.daum.net
ftp://update.url.com/pub/repodata/repomd.xml: [Errno 14] PYCURL ERROR 7 - "couldn't connect to host"
Trying other mirror.
repo id                                    repo name                                              status
Updates                                    Update Repository                                      0
base                                       CentOS-6 - Base                                        0
extras                                     CentOS-6 - Extras                                      0
updates                                    CentOS-6 - Updates                                     0
repolist: 0
[root@cent yum.repos.d]# 

man
  • 명령어의 위치: /usr/bin/man
  • 파일의 실제위치
    • /usr/local/share/man
      • man1, man2, ..., man2x
      • man1: user command
      • man2: system call
      • man3: 라이브러리 함수 & 서브루틴
      • man4: /dev의 특수파일 보관 디렉토리
      • man5: 파일포맷관련
      • man6: 게임관련
      • man7: 기타
      • man8: 시스템 관리 명령
      • man9: 커널관련 명령어
      • mann: Tcl/tk 내장
        • man 1 ps
        • man 5 sssd
        • man 8 sssd.conf
        • man path ls
    • /usr/share/man/ko
    • /usr/share/man
    • /usr/x11r6/man
top
  • M: Memory를 가장 많이 소비하고있는 프로세스
  • P: Processor를 가장 많이 소비하고있는 프로세스
  • renice -n 15 <pid>
ssh
    키생성하기

    [root@cent ~]# ssh-keygen 
    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa): 
    Created directory '/root/.ssh'.
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /root/.ssh/id_rsa.
    Your public key has been saved in /root/.ssh/id_rsa.pub.
    The key fingerprint is:
    49:73:4f:8a:29:86:fb:f2:b4:bb:65:2c:02:f3:30:e2 root@cent.rsyoung.org
    The key's randomart image is:
    +--[ RSA 2048]----+
    |                 |
    |                 |
    |        o . .    |
    |     . . * +     |
    |. = . o S . .    |
    |.. * o o         |
    | E  + o +        |
    |    .+ =         |
    |     o*o         |
    +-----------------+
    [root@cent ~]# 
    [root@cent ~]# ls -al .ssh/
    total 16
    drwx------.  2 root root 4096 Apr 10 22:20 .
    dr-xr-x---. 25 root root 4096 Apr 10 22:20 ..
    -rw-------.  1 root root 1675 Apr 10 22:20 id_rsa
    -rw-r--r--.  1 root root  403 Apr 10 22:20 id_rsa.pub
    [root@cent ~]# 

    다른서버로 public key 보내기

    [root@cent ~]# ssh-copy-id root@targetserver

    설정파일

    [root@cent ~]# rpm -q openssh-server -c
    /etc/pam.d/ssh-keycat
    /etc/pam.d/sshd
    /etc/ssh/sshd_config
    /etc/sysconfig/sshd
    [root@cent ~]# 

    루트로그인 막기 (/etc/ssh/sshd_config)

    PermitRootLogin       no

    암호인증 막기

    PasswordAuthentication    no

    ssh 접속이 매우 늦을때

    GSSAPIAuthentication no


    타임관리

    현재시간: data
    하드웨어시간: hwclock
    네트워크시간: rdate -s time.bora.net
    시간프린트: rdate -p time.bora.net

    FTP 서버설정

    /etc/vsftpd/vsftpd.conf

    anonymous =YES
    local_enable=NO    # local user 접근불가
    write_enable=NO   # 쓰기금지

    SELINUX

    /etc/selinux/config
    • Mode
      • enabled
        • enforcing
        • permissive: log는 남김
      • disabled

    [root@cent ~]# getenforce
    Enforcing
    [root@cent ~]# setenforce 
    usage:  setenforce [ Enforcing | Permissive | 1 | 0 ]
    [root@cent ~]# 
    [root@cent ~]# setenforce Permissive
    [root@cent ~]# getenforce
    Permissive
    [root@cent ~]# setenforce 1
    [root@cent ~]# getenforce
    Enforcing
    [root@cent ~]# 

    selinux가 enforcing되어있을때 ls -Z

    [root@cent ~]# ls -Z
    -rw-------. root root system_u:object_r:admin_home_t:s0 anaconda-ks.cfg
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Desktop
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Documents
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Downloads
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Music
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Pictures
    -rw-r--r--. root root system_u:object_r:admin_home_t:s0 post-install
    -rw-r--r--. root root system_u:object_r:admin_home_t:s0 post-install.log
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Public
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Templates
    drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 Videos
    [root@cent ~]# 

    admin_home_t: 컨텍스트를 의미함. 이 컨텍스트가 아닌 다른 컨텍스트에서 파일을 조작할경우 selinux 에러메시지가 /var/log/message에 기록됨.

    [root@cent /]# touch /tmp/file1
    [root@cent /]# touch /tmp/file2
    [root@cent /]# ls -Z /tmp/file*
    -rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/file1
    -rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/file2
    [root@cent /]# 
    [root@cent /]# mv /tmp/file1 /var/www/html/
    [root@cent /]# cp /tmp/file2 /var/www/html/
    [root@cent /]# 
    [root@cent /]# cd /var/www/html/
    [root@cent html]# ls -Z
    -rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 file1
    -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2
    -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
    [root@cent html]# 
    [root@cent html]# cd ..
    [root@cent www]# restorecon -R /var/www/
    [root@cent www]# 
    [root@cent www]# cd html/
    [root@cent html]# ls -Z
    -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1
    -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2
    -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
    [root@cent html]# 


    Access Control List

    현재 파일시스템이 ACL을 지원하는지여부 파악

    [root@cent ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/vg_centos-lv_root
                          5.5G  2.2G  3.3G  40% /
    tmpfs                1004M  272K 1004M   1% /dev/shm
    /dev/sda1             485M   33M  427M   8% /boot
    /dev/sr0               43M   43M     0 100% /media/VBOXADDITIONS_4.1.2_73507
    [root@cent ~]# 
    [root@cent ~]# dumpe2fs /dev/mapper/vg_centos-lv_root | grep Default
    dumpe2fs 1.41.12 (17-May-2010)
    Default mount options:    user_xattr acl
    Default directory hash:   half_md4
    [root@cent ~]# 

    ACL을 지원하고있다. 만약 지원하지 않는다면, tune2fs로 ACL지원하도록 설정.

    [root@cent ~]# tune2fs -o user_xattr,acl /dev/mapper/vg_centos-lv_root 
    tune2fs 1.41.12 (17-May-2010)
    [root@cent ~]# 

    주의: 컴마(,) 사이는 공백이 있으면 안됨.

    ACL의 특징중의 하나가 다중 group을 지원한다는 점이다. ugo 모드에서는 단일 그룹만지원한다.

    /opt/research 디렉토리


    [root@cent opt]# ls -al /opt/research/
    total 16
    drwxr-s---. 2 root grads 4096 Apr 12 22:36 .
    drwxr-xr-x. 4 root root  4096 Apr 12 22:29 ..
    -rw-rw----+ 1 root grads   29 Apr 12 22:36 file.txt
    [root@cent opt]# 

    ./research 디렉토리의 ACL

    [root@cent opt]# getfacl ./research/
    # file: research/
    # owner: root
    # group: grads
    # flags: -s-
    user::rwx
    group::r-x
    other::---

    grads, profs 그룹이 /opt/research 디렉토리를 접근하고 읽고쓸수 있도록 설정.

    [root@cent opt]# setfacl -m g:profs:rwx ./research/
    [root@cent opt]# setfacl -m g:grads:rwx ./research/
    [root@cent opt]# 
    [root@cent opt]# getfacl ./research/
    # file: research/
    # owner: root
    # group: grads
    # flags: -s-
    user::rwx
    group::r-x
    group:profs:rwx
    group:grads:rwx
    mask::rwx
    other::---

    [root@cent opt]# 

    grads 그룹이 ./research 디렉토리하에 생기는 모든 파일들을 읽고쓸수 있게함.
    other들은 ./research 디렉토리 접근을 원천 차단
    other들은 ./research 디렉토리내에 생성된 파일들을 접근할 수 없음.

    [root@cent opt]# setfacl -m d:g:grads:rwx ./research/
    [root@cent opt]# setfacl -m o::- ./research/
    [root@cent opt]# setfacl -m d:o::- ./research/
    [root@cent opt]# 
    [root@cent opt]# getfacl ./research/
    # file: research/
    # owner: root
    # group: grads
    # flags: -s-
    user::rwx
    group::r-x
    group:profs:rwx
    group:grads:rwx
    mask::rwx
    other::---
    default:user::rwx
    default:group::r-x
    default:group:grads:rwx
    default:mask::rwx
    default:other::---

    [root@cent opt]# 

    grads 그룹이 ./research 디렉토리를 소유하게하고, 이 디렉토리 하에 생기는 모든 파일들들에 대해 grads 그룹이 소유하도록 설정.


    [root@cent opt]# chgrp grads ./research/
    [root@cent opt]# chmod g+s ./research/
    [root@cent opt]# ls -al
    total 20
    drwxr-xr-x.  4 root root  4096 Apr 12 22:29 .
    dr-xr-xr-x. 26 root root  4096 Apr 12 22:57 ..
    drwxrws---+  2 root grads 4096 Apr 12 22:36 research
    [root@cent opt]# 

    디렉토리를 오픈하기위해서는 rwx에서 x가 반드시 설정되어 있어야 함. man chmod를 해보면 다음과 같은 설명이 있음.

    The  letters  rwxXst select file mode bits for the affected users: read (r), write (w), execute (or search for directories) (x), execute/search only  if  the file is a directory or already has execute permission for some user (X), set user or group ID on execution (s), restricted  deletion  flag or sticky bit (t).  Instead of one or more of these letters, you can specify exactly one of the letters ugo: the permissions granted to  the  user  who  owns the file (u), the permissions granted to other  users who are members of the file’s  group  (g),  and  the  permissions  granted  to  users  that are in neither of the two preceding categories (o).

    Fedora, RedHat, CentOS에서 Boot Time시 문제 해결


    fstab 문제로 Maintenance 모드로 빠지고 fstab을 수정할 수 없을때

    mount -o remount rw, /

    root password를 잃어버렸을 때

    GRUB에서 Kernel Parameter로 "s"를 넘겨 single user로 접속
    passwd 변경시도.
    passwd 변경시도시 바로 빠져나오면 SELinux가 enable 되었는지 확인
    SELinux가 enable되었다면 setenforce 0으로 SELinux를 passive 모드로 전환
    passwd로 root 패스워드 변경








      2011년 12월 9일 금요일

      메모리매핑

      (원소스: 리눅스 디바이스드라이버, 유영창 저)

      • MMU에는 MMU 테이블을 유지하기위한 별도의 관리 메모리가 없다. MMU는 보통 프로세서에 내장되고, 시스템 메모리를 같이 사용한다. 그래서 프로세서가 처음 부팅되면 리눅스는 시스템 메모리의 일부를 MMU 테이블에 할당하고, 관리할 정보를 MMU 테이블에 기록한다. 이 과정에서는 MMU가 동작하지 않는다. 리눅스 커널은 MMU 테이블에 관련된 정보를 메모리에 모두 기록한 후에 MMU 테이블에 해당하는 메모리 위치를 MMU에 알려주고 MMU를 동작시킨다.
      • 메모리맵I/O 방식: 
          char *videoptr;
          videoptr = (char *) 0x000B0000;
          *videoptr = 'A';

      • 메모리 접근 명령으로 처리하는 것을 Memory Mapped I/O라 한다. 하지만, MMU가 활성화되어 동작하는 커널 모드에서는 위의 예처럼 비디오의 물리주소 0x000B0000에 접근하면 페이지폴트가 발생하여 처리되지 않는다. 따라서, 디바이스드라이버는 하드웨어를 제어하기위해 물리주소를 가상주소로 매핑해야 한다. 메모리맵 I/O 방식의 물리적 주소공간을 커널에서 사용 가능한 주소로 매핑하거나 매핑된 영역을 해제할 때는 ioremap(), ioremap_nocache(), iounmap() 함수를 사용해야 한다.
      • 응용 프로그램에서는 디바이스 파일로 하드웨어를 제어하기 위해 보통 read(), write(), ioctl() 함수를 사용한다. 이 함수들은 응용 프로그램에 하드웨어의 내부구조를 숨겨주는 효과가 있다. 그러나 이런 함수들은 프로세스 메모리공간과 커널메모리 공간사이의 메모리 전달 과정이 수반되기 때문에 매우 비효율적이다. 특히나 많은 용량의 데이터가 빠르게 전달되어야 하는 사운드나 비디오 장치에 메모리 복사가 수반되는 read(), write(), ioctl() 함수를 사용한다면 시스템 성능이 저하된다. (put_user(), copy_to_user(), get_user(), copy_from_user())
      • 이렇게 비효율적인 방법을 극복하기위해 리눅스에서는 mmap() 함수를 제공하여 응용 프로그램에서 직접 하드웨어의 I/O 주소공간을 메모리 복사없이 직접적으로 사용할 수 있도록 한다. mmap() 함수는 원래 메모리 주소를 이용해 파일에 접근할 수 있도록 하는 함수다. 그러나 디바이스 파일에 적용할 경우에는 디바이스에서 제공하는 물리주소 (I/O 메모리 주소 또는 할당된 메모리 공간주소)를 응용 프로그램에서 사용할 수 있게한다. 응용 프로그램이 동작하는 프로세스의 메모리 영역에 디바이스 드라이버가 제공하는 물리주소를 매핑하면 된다.
      • 동일한 물리주소를 가상주소로 매핑하는 방법에는 두가지가 있다. 하나는 mmap() 함수를 사용하여 응용프로그램의 프로세스 가상주소에 매핑하는 방법이고, 하나는 ioremap() 함수를 하용하여 커널의 가상주소에 매핑하는 방법이다.
      • nopage 매핑방식: 디바이스 드라이버에서 mmap을 처리하는 방식은 mmap() 함수에서 remap_pfn_range() 함수를 이용하여 필요한 매핑을 직접처리하는 방법과 nopage 방식을 사용해 페이지 단위로 매핑하는 방법이 있다. 앞에서 설명한 방법이 remap_pfn_range() 함수를 이용해 매핑 대상이 되는 영역을 한꺼번에 매핑하는 방법이었다면, nopage 방법은 PAGE_SIZE 단위로 매핑을 처리한다. nopage 방식은 응용 프로그램에서 mmap() 함수를 호출하여 프로세스에서 사용할 수 있는 주소를 먼저 요구한다. nopage 방식은 remap_pfn_range() 함수를 이용하는 방법처럼 응용 프로그램 mmap() 함수를 호출하면 디바이스 드라이버의 파일 오퍼레이션 구조체에 정의된 mmap() 함수가 호출된다. 그러나 핲서 설명한 mmap() 함수가 요청된 영역의 매핑을 remap_pfn_range() 함수를 이용해 처리하는 것과 달리 nopage 방식에서는 mmap() 함수가 remap_page_range() 함수를 수행하지 않는다. 그래서 커널이 해당 영역을 매핑하지 않기 때문에 응용 프로그램이 mmap()을 통해 주소에 접근하면 해당 메모리 주소를 유효하지 않은 영역으로 인식하여 페이지폴트가 발생한다. 커널은 페이지 폴트가 발생하면 디바이스 드라이버로 매핑하기 위해 해당 주소공간이 예약된 주소 영역인지를 확인하고, 예약된 영역이면 vma->vm_ops->nopage에 선언된 함수를 호출한다.  nopage 방식은 물리적인 I/O 메모리공간을 응용 프로그램의 프로세스 공간에 사용하기 보다는 주로 디바이스 드라이버에 의해 할당된 메모리 공간을 공유하기 위해 사용한다. nopage 방식으로 mmap을 구현하려면 디바이스 드라이버는 가장 먼저 페이지 폴트가 발생할 때 호출된 nopage() 함수를 만들어야 한다.


      rsyoung@descartes:~$ cat /proc/iomem 
      00000000-0000ffff : reserved
      00010000-0009fbff : System RAM
      0009fc00-0009ffff : reserved
      000a0000-000bffff : PCI Bus 0000:00
      000e0000-000fffff : reserved
      00100000-ba108fff : System RAM
        01000000-015952c2 : Kernel code
        015952c3-01ad4f6f : Kernel data
        01bc1000-01d18113 : Kernel bss
      ba109000-ba10bfff : ACPI Non-volatile Storage
      ba10c000-bba6afff : System RAM
      bba6b000-bbabefff : reserved
      bbabf000-bbb72fff : System RAM
      bbb73000-bbbbefff : ACPI Non-volatile Storage
      bbbbf000-bbbe8fff : System RAM
      bbbe9000-bbbfefff : ACPI Tables
      bbbff000-bbbfffff : System RAM
      bbc00000-bfffffff : reserved
      c0000000-febfffff : PCI Bus 0000:00
        c0000000-cfffffff : PCI Bus 0000:01
          c0000000-cfffffff : 0000:01:00.0
        d0000000-dfffffff : 0000:00:02.0
        e0000000-e1ffffff : PCI Bus 0000:0b
        e2000000-e4ffffff : PCI Bus 0000:01
          e2000000-e3ffffff : 0000:01:00.0
          e4000000-e4ffffff : 0000:01:00.0
        e5000000-e5000fff : Intel Flush Page
        e6000000-e80fffff : PCI Bus 0000:0b
          e8000000-e8000fff : 0000:0b:04.0
            e8000000-e8000fff : yenta_socket
          e8001000-e80017ff : 0000:0b:04.1
            e8001000-e80017ff : firewire_ohci
          e8001800-e80018ff : 0000:0b:04.4
          e8001900-e80019ff : 0000:0b:04.2
            e8001900-e80019ff : mmc0
        e8400000-e87fffff : 0000:00:02.0
        e8800000-e97fffff : PCI Bus 0000:02
        e9800000-ea7fffff : PCI Bus 0000:06
        ea800000-eb7fffff : PCI Bus 0000:08
        eb800000-ec7fffff : PCI Bus 0000:08
        ec800000-ed8fffff : PCI Bus 0000:06
          ec800000-ec801fff : 0000:06:00.0
            ec800000-ec801fff : iwlagn
        ed900000-ee8fffff : PCI Bus 0000:02
        ee900000-ee91ffff : 0000:00:19.0
          ee900000-ee91ffff : e1000e
        ee920000-ee923fff : 0000:00:1b.0
          ee920000-ee923fff : ICH HD audio
        ee924000-ee924fff : 0000:00:19.0
          ee924000-ee924fff : e1000e
        ee925000-ee9257ff : 0000:00:1f.2
          ee925000-ee9257ff : ahci
        ee925800-ee925bff : 0000:00:1d.7
          ee925800-ee925bff : ehci_hcd
        ee925c00-ee925fff : 0000:00:1a.7
          ee925c00-ee925fff : ehci_hcd
        ee926000-ee9260ff : 0000:00:1f.3
        f0000000-f3ffffff : PCI CardBus 0000:0c
        f4000000-f7ffffff : PCI CardBus 0000:0c
        f8000000-fbffffff : PCI MMCONFIG 0000 [bus 00-3f]
          f8000000-fbffffff : reserved
            f8000000-fbffffff : pnp 00:01
      fec00000-fec00fff : reserved
        fec00000-fec003ff : IOAPIC 0
      fed00000-fed003ff : HPET 0
      fed10000-fed13fff : reserved
        fed10000-fed13fff : pnp 00:01
      fed18000-fed19fff : reserved
        fed18000-fed18fff : pnp 00:01
        fed19000-fed19fff : pnp 00:01
      fed1c000-fed1ffff : reserved
        fed1c000-fed1ffff : pnp 00:01
      fed20000-fed3ffff : pnp 00:01
      fed40000-fed44fff : PCI Bus 0000:00
      fed45000-fed8ffff : pnp 00:01
      fee00000-fee00fff : Local APIC
        fee00000-fee00fff : reserved
          fee00000-fee00fff : pnp 00:01
      ffe80000-ffffffff : reserved
      100000000-1bfffffff : System RAM
      rsyoung@descartes:~$ 




      2011년 6월 19일 일요일

      리눅스 실무기술 300 정리

      여기에 기술된 모든 내용은 "리눅스 실무기술 300 - 박성수 저"를 기반으로 본인(?)에게 필요한 내용으로 요약되었습니다.

      책: http://image.yes24.com/goods/3369046/L


      * useradd rsyoung
          /etc/login.defs, /etc/default/useradd 파일을 참조하여
              /etc/passwd 파일에 등록. ID/ UID/ GID, home 디렉토리, 쉘 정의
              /etc/shadow 파일에 password 정보등록

          /home/rsyoung 생성
          /etc/skel/ 모든 파일 (히든파일포함)을 /home/rsyoung 에 복사함
          /var/spool/mail/rsyoung 메일박스를 생성함

      * passwd에 대한 간략한 정보
          passwd -s <userid>

      * userdel
          userdel <userid>
              /etc/passwd
              /etc/shadow
              /etc/group
              파일에서 해당 id 제거

          userdel -r <userid>
              /home/<userid>
              /var/spool/mail/<userid>
              파일까지 제거

          userdel -f <userid>
              심지어 로그인중이라도 삭제 ㅠ.ㅠ (잔인한놈 ㅋㅋㅋ)

      * w
          현재 시스템에 접속한 정보 확인

      * last, last reboot
          시스템의 부팅정보

      * who -d
          죽어있는 프로세스 정보 확인

      * chsh -l
          /etc/shells의 내용을 보여줌
              : chsh은 기본쉘을 변경하는 것임. 기본쉘은 로그인쉘을 의미하며
                /etc/passwd의 값이 변경됨
          현재쉘을 변경하는 명령은
              /bin/sh
              /bin/csh
              /bin/bash

      * logname
          서버에 접속할 당시의 이름. rsyoung --> root --> mybrain으로 사용자를 변경해도
          logname은 rsyoung임

      * users
          서버에 접속해있는 사용자들의 계정만을 확인하는 명령.
          참조하는 파일
              /var/run/utmp  
              /var/log/wtmp

      * chage
          aging 정보 변경하기. aging 정보는 /etc/passwd 파일에 저장됨   

      * ls -a
          . 시작하는 파일 리스트 (not hidden file only)

      * ls -A
          ., .. 제외

      * ls -F
          파일종류 표시
              regular file: none
              execution file: *
              directory: /
              symbolic link: @
              FIFO file: |
              socket file: =

      * ls -n
          UID/ GID 표시

      * ls -1
          file명만 리스트

      * ls -alRSh | more
          recursively 디렉토리까지 파일 크기별로 (K,M,G) 단위 표시

      * 홈 디렉토리의 위치는  /etc/passwd 파일에 지정되어있고 로그인하면 쉘환경변수 HOME에 저장함

      * cat -b <text file>
          행번호를 붙혀서 출력, 빈행은 번호를 붙히지 않음

      * cat -n <text file>
          빈행도 번호를 부여함

      * cp -rp <dir1> <dir2>
          원본파일의 소유자, 그룹소유자, 권한, 시간정보등을 보존하면서 복사하기

      * mv -u
          이동하려는 파일이 더 최근것일경우만 이동시킴

      * rename test test0 test?
          test? 파일에 대해서 test로 시작하는 prefix를 test0로 변경
          test1 --> test01

      * rename .htm .html *.htm
          *.htm 파일에 대해서 .htm --> .html로 변경

      * more 명령
         - b : 한페이지씩 앞으로 이동
         - = : 현재 위치의 행번호 표시하기
         - /문자열 : 지정한 문자열을 검색하기
         - n : /문자열로 검색한 문자열을 차례대로 계속해서 찾기
         - !쉘명령어: more 명령어 상태에서 쉘명어를 실행하기
         - v : more 명령어로 열려있는 파일의 현재위치에서 vi를 실행하기

      * head 명령어로 바이트단위로지정하여 확인
         head -c 200 website

      *less 명령
        - space bar or f : 현재페이지에서 한페이지 뒤로 이동
        - b : 현재페이지에서 한페이지 앞으로 이동
        - Enter : 한행씩 차례대로 뒤로 이동
        - 숫자 + n: 원하는페이지 만큼 뒤로 이동 (이후부턴 n만 클릭)
        - q : 종료

      *로그파일 실시간 모니터링
        - $ tail -f /var/log/messages
        - $ tail -f /var/log/secure
        - $ tail -f /va/log/maillog

      * 파일 내용을 행단위로 거꾸로 출력하기
        - $ rev <file name>

      * 탭을 공백문자로 변경
        - $ cat <file name> | expand -t <# of space>
        - Tab이 # of space만큼 공백으로 변경됨

      * 지정한 파일의 시간정보를 특정파일의 날찌시간과 동일하게 변경
        - tourch -r <original file> <target file>
        - <target file>이 <original file>과 동일한 시간으로 변경됨

      * 특정 파일내에서 가장 긴 행의 길이 확인
        - $ wc -L <file name>

      * 특정 디렉토리내에 존재하는 전체 디렉토리개수 확인하기
        - $ ls -Rl /etc | grep "^d" | wc -l

      * 특정 파일내용을 지정한 열을 기준으로 정렬
        - $ sort -k 2 textfile

      * 현재 디렉토리내의 파일들을 용량기준으로 오름차순 정렬
        - $ ls - l /var/log | sort -k 5

      * 현재 디렉토리내의 파일들을 용량기준으로 내림차순 정렬
        - $ ls -l /var/log | sort -rk 5

      * 지정한 파일의 모든 영문자를 대문자로 바꾸기
        - $ cat trtest | tr '[a-z]' '[A-Z]'

      * 지정한 파일내의 특정문자 삭제
        - $ cat trtest | tre -d <삭제할 문자>

      * /etc/passwd의 구조
        ----------------------------------------------------------------------------------------------------------------------
        ID : password: UID : GID : Description : Home Directory : Shell
        ----------------------------------------------------------------------------------------------------------------------

        rsyoung: x : 500 : 500 : my username : /home/rsyoung : /bin/bash

        (1)         (2)  (3)     (4)            (5)                  (6)                   (7)

      */etc/passwd 파일에서 ID, 패스워드자리, UI만 출력
        - $ cut -d : -f 1, 2, 3 /etc/passwd

      * 바이트만 잘라내기
        - $ cut -b1 /etc/passwd  (첫바이트)
        - $ cut -b1,2,3 /etc/passwd (1, 2, 3 바이트)
        - $ cut -b-10 /etc/passwd (처음부터 10 바이트)
        - $ cut -b10- /etc/passwd (10부터 마지막바이트)

      * 파일 종류를 확인하는 file 명령어가 참조하는 파일
        - /usr/share/file/magic
        - /usr/share/file/magic.mgc
        - 위 두 파일을 참조하여 파일 종류를 표시해 줌.

      * type 명령으로 리눅스 명령어의 종류 확인
        - $ type test

      * 표준입력되는 문자열을 가로 -> 세로순으로 정렬
        - $ cat group | column -x

      * 표준입력되는 무자열을 특정문자를 기준으로 가로정렬
        - $ cat group | column -t -s :

      * dd로 파일복사하기
        - $ dd if=<input file> of=<output file>

      * 두파일이 동일한지 검사
        - $ diff --brief <file 1> <file 2>

      * 파일 세개 비교
        - $ diff3 <file1> <file 2> <file 3>

      * grep
        - Globally find Regular-Expression and Print의 약자
        - egrep = grep -E
        - fgrep = grep -F
        - 대소문자 구분없이 검색 : -i

      * 특정 디렉토리내에서 디렉토리리스트만 확인
        - $ ls -l /etc | grep "^d"

      * 특정 디렉토리내에서 일반파일리스트만 확인
        - $ ls -l /etc | grep "^-"

      * 특정 디렉토리내에 존재하는 파일들 한번에 편집하는 명령어 만들기
        - $ ls -l | grep "^-" | awk '{print "vi "$8}'

      *awk
        - 1977년 Bell 연구소의 Alfred v. Aho' Peter j. Wenberger, Brian W. Kernighan이 만듬

      * /home 디렉토리의 각 계정별로 압축하는 명령어 만들기
        - $ ls -l /home | grep "^d" | awk '{print "tar cvfpz " "/backup/"$8".tar.gz" "/home/"$8}'
        - Shell 파일 생성후 실행함

      * 공백을 TAB 문자로 대체하는 unexpand
        - $ cat spacefile | unexpand

      * Symbolic Link vs. Hard Link
        - Symbolic Link: 원본파일을 가르키도록 링크만 시켜둔 것 (다른 파일시스템에서 적용됨)
        - Hard Link: 다른 이름으로 존재하는 동일한 파일 (다른 파일시스템에서 적용안됨)

      * 기본 명령어에 대한 심볼릭 링크 관리기 alternatives
        - /etc/alternatives 디렉토리와 /var/lib/alternatives 디렉토리에는 많은 링크파일들의 설정이 정의되어 있으며 시스템 설치시에 기본적으로 정의되어 있는 링크파일들의 설정값

      * 비어있는 파일 찾기
        - $ find / -empty -exec ls -l {} \;
        - {}는 검색된 파일이 하나씩 치환됨을 의미

      * 최근 몇시간 이전(후)에 사용된 적이 있는 파일 검색
        - $ find /home/rsyoung -atime -100 -exec ls -l {} \;

      * 특정명령어의 간략한 도움말 확인하기
        - $ whatis find

      * 실행파일, 소스, man페이지파일의 위치를 찾기
        - $ whereis -b ifconfig

      * 파일시스템의 용량이 0인 모든 파일 시스템을 대상으로 디스크용량 확인
        - $ df -a

      * 디스크용량을 파일 시스템의 종류와 함께 표시
        - $ df -T

      * 특정 디렉토리의 전체 사용량 점검
        - $ du -s /etc

      * hdparm로 디스크의 기본 설정정보 확인
        - $ hdparm /dev/hdc1

      * hdparm 명령어로 버퍼링되어있지 않은 데이터의 디스크 ACCESS 속도 체크하기
        - $ hdparm -t /dev/sda

      *hdparm 명령어로버퍼링되어 있는 데이터와 되어있지 않은 데이터의 ACCESS 속도 비교하기
        - $ hdparm -tT /dev/sda

      * IDE 하드디스크 휴지 또는 준비상태로 전환하기
        - $ hdparm -Y /dev/hdc
        - $ hdparm -y /dev/hdc

      * 하드디스크에 배드블럭 존재 유무 검사
        - $ badblocks -v /dev/sda1

      * 어떤 디스크가 장착되어있는지 확인하기
        - $ df
        - $ fdisk -l /sda7    (root 명령으로 확인)

        - $ fdisk -l   (root 명령으로 확인)

      * 대용량 디스크 파티션 (2TB 이상) - parted
        - 리눅스의 모든 파티션들은 msdos 레이블만을 사용함
        - 리눅스의 부트로더인 LILO와 GRUB은 msdos 디스크 레이블만을 인식
        - 2TB 이상되는 디스크는 gpt라는 레이블을 사용해야함
        - gpt 레이블은 LILO와 GRUB에서 인식되지 못하므로 시스템디스크 같은 부팅디스크는 gpt 레이블을 사용해서는 안됨.

      * /etc/fstab 파일 구조
        - [파일시스템장치명] [마운트포인트] [파일시스템종류] [옵션] [dump관련설정] [파일점검옵션]
        - [옵션의 종류]
          + defaults: rw, nouser, auto, exec, suid 속성을 모두가지는 속성
          + auto: 부팅시 자동마운트
          + exec: 실행파일이 실행되는 것을 허용하는 파일 시스템
          + suid: SetUID와 SetGID의 사용을 허용하는 파일 시스템
          + ro: 읽기전용
          + rw: 읽고 쓰기 파일시스템
          + user: 일반 계정사용자들도 마운트 할수 있는 파일 시스템
          + nouser: 일반 사용자들은 마운트 할 수 없는 파일 시스템 (root만 마운트)
          + noauto: 부팅시 자동마운트되지 않게 함
          + noexec: 실행파일을 실행되지 못하게 하는 파일시스템
          + nosuid: SetUID와 SetGID의 사용을 허용하지 않는 파일 시스템
          + usrquota: 개별 사용자의 쿼타 설정이 가능한 파일 시스템
          + grpquota: 그룹별 쿼타설정이 가능한 파일 시스템

        - [dump관련 설정]
          + 1: 데이터백업등을 위해 dump가 가능한 파일시스템
          + 0: dump 명령으로 덤프되지 않은 파일시스템

        - [파일점검 옵션]
          + 0: 부팅시 실행되는 fsck가 실행되지않게 설정
          + 1: 루트파일 시스템
          + 2: 루트파일 시스템 이외의 파일 시스템

      * mke2fs로 파일시스템 생성하기전에 배드블럭 검사하기
        - $ mke2fs -t ext4 -c /dev/sdb1

      * 파일시스템 생성시에 예비블럭 크기 지정
        - $ mke2fs -t ext4 -m 20 /dev/sdb1
        - 전체 파일시스템의 20%를 예비블럭으로 생성

      *e2fsck명령어로 특정 파일시스템의 점검및 복구
        - $ e2fsck /dev/hdc2
        - /dev/hdc2가 unmount된 상태에서 수행해야 함

      * 백업수퍼블럭을 이용한 파일 시스템 보구
        - $ dumpe2fs /dev/sda3 | grep superblock   (Superblock 위치확인)
        - $ e2fsck -b 98304 -f -y /dev/hdc2
        - $ e2fsck -b 98304 -j ext3 -y /dev/hdc2   (ext3 filesystem의 경우)

      * e2fsck로 배드블럭 마킹
        - $ e2fsck -j ext3 -cv /dev/sda3
        - e2fsck 옵션에서 badblocks를 실행하여 배드블럭을 찾은 후에 디스크의 배드블럭 아이노드에 추가하여 마크함으로써 배드블럭을 사용하지 못하도록 하는 방법

      * e2fsck로 손상된 파일시스템 자동복구
        - $ e2fsck -b 98304 -p /dev/hdc2
        - 옵션 -p가 없으며 질문에 답을 해야함..해넘어갈 수 있음 ^^;

      * 특정 파일시스템의 상세정보와 그 사용내역확인
        - $ dumpe2fs /dev/sda3

      * 특정 파일시스템의 수퍼블럭만 확인
        - $ dumpe2fs -h /dev/sda3

      * tune2fs로 특정 파일시스템의 수퍼블럭 정보 확인
        - $ tune2fs -l /dev/sdb1

      * 파일시스템 디버거 debugfs
        - $ debugfs
        - q: 종료
        - help: 도움말
        - params: 실행옵션에 대한 파라미터 보기

      * 리눅스에서 삭제된 파일들의 inode목록 확인
        - $ debugfs -w /dev/sd3
        - lsdel

      * 현재 상태에서 사용가능한 debugfs 명령어 확인
        - lr

      * nice값 조정하기
        - $ renice -15 -p 2010
        - $ renice +10 -p 3999


      * 각 프로세스 명령해 옵션들까지 pstree로 확인하기
        - $ pstree -a

      * 현재 프로세스와 그 조상 프로세스를 강조하여 pstree 결과 출력
        - $ pstree -h

      * 각 프로세스들의 PID를 함께 표시하여 pstree 출력
        - $ pstree -p

      * pstree의 결과를 긴출력이 있더라도 그대로 출력
        - $ pstree -l

      * 프로세스 이름으로 정렬하여 pstree 출력
        - $ pstree -n

      * bg를 이용하여 백그라운드로 프로세스 실행
        - $ jobs
        - $bg %1
        - Ctrl + Z로 foregroud process 를 Stop 시킬 수 있으며, jobs로 확인가능

      * 백그라운드 프로세스를 포그라운드로 전환
        - $ fg %1

      *kill 명령어에서 사용 가능한 시그널들 모두 확인하기
        - $ kill -l

      * chkconfig로 관리되는전체 리스트 확인
        - $chkconfig --list

      * 특정파일이나 특정 디렉토리를 사용하고 있는 프로세스 모두 죽이기
        - $ fuser -k /usr/sbin/httpd

      * 특정 데몬 (프로세스) 파일이 사용하고 있는 상세정보 확인
        - $ fuser -v /usr/sbin/httpd

      * jobs로 실행중인 프로세스들의 PID 확인
        - $ jobs -l
        - $ jobs -p

      * 특정 프로세스의 PID를 출력하는 pidof
        - $ pidof httpd

      * 현재 마운트된 정보 자세히 살펴보기
        - $ mount -v
        - $ cat /etc/mtab

      *free 명령어로 시스템 메모리 사용현황 확인
        - $ free

      * free 명령어로 메모리사용현황 정보를 초단위 갱신하여 확인
        - $ free -s 3

      * 시스템 부하율 점검
        - $ uptime

      * top
      top - 15:09:38 up  4:56,  3 users,  load average: 0.07, 0.08, 0.06
              [현재시간] [up time] [사용자]  [1분, 5분, 15분 각각의 평균부하율]    

      Tasks: 188 total,   1 running, 187 sleeping,   0 stopped,   0 zombie
        [전체 프로세스수]  [running]  [sleeping]         [stopped]     [zombie]


      Cpu(s): 11.7%us,  6.3%sy,  0.0%ni, 82.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
                [사용자]     [시스템]   [nice 정책]   [idel]   [I/O waiting]  [IRQ]   [soft IRQ]   [Steal값]

      Mem:   6057416k total,  1978864k used,  4078552k free,   358080k buffers
                 [Total]                 [Used]               [Free]                 [버퍼링된 메모리양]   

      Swap: 12000516k total,        0k used, 12000516k free,   770520k cached
                [Total]                       [Swap된양]   [Free]              [캐싱메모리양]

      * top의 결과를 메모리 사용율이 높은 프로세스 순서로 정렬
        - $ top
        - SHIFT + M

      * top의 결과를 실행시간이 오래된 프로세스 순서대로 정렬
        - $ top
        - SHFIT + T

      * top의 결과를 idle 프로세스들을 모두 감추고 확인
        - $ top
        - i

      * top 상태에서 특정 프로세스 죽이기
        - $ top
        - k

      * top 상태에서 프로세스들의 우선순위 조정
        - $ top
        - r

      * top 상태에서 특정 사용자가 실행한 프로세스 확인
        - $ top
        - u

      * 시스템 각 계정의 최근 접속 정보 확인
        - $ lastlog

      * 자주 사용하는 ssh 명령어 alias 설정으로 간편하게 사용하기
        - $ alias ssh123='ssh -l rsyoung abc.def.ghi.jkl'

      * 휴대용 시스템의 전원관리 정보를 확인하는 apm
        - $ cat /proc/apm
        - APM (Advanced Power Management)

      * 히스토리파일 (.bash_history)에 저장된 최근 명령어리스트 확인
        - $ fc -l
        - $ fc -l 250 260  (범위지정)
        - $ fc -ln 250 260 (번호 생략)

      * 최근에 사용했던 명령어를 지정된 편집기로 편집한 다음 실행
        - $ fc -e vi


      * 터미널에 작업중인 내용을 텍스트 형태로 모두 저장하기
        - $ script
        - exit
        - $ script <filename>
        - exit


      * 일정기간 이상 사용되지 않은 파일은 자동삭제
        - $ tmpwatch --mtime 10 /home/rsyoung


      * shutdown 명령어가 실행된 후 시스템 종료 절차
        - sych 작업
        - 종료메시지 전달 to 사용자
        - 새로운 사용자 로그인 금지
        - 지정된 시간내에 종료안된 프로세스 강제 종료
        - 지정된 시간내 로그아웃 안된 사용자 강제 로그아웃
        - 메모리에 남아있는 데이터를 디스크에 저장
        - 시스템 종료에 관련된 정보를 시스템 로그파일에 기록 (wtmp, utmp)
        - 마운트되어 있는 디바이스들을 마운트 해제
        - 시스템 종료

      * init 프로세스의 의미
        - PID 1번
        - swapper (PID 0번, 커널의 일부)가 init 프로세스를 생성함

      * 하드웨어시간과 운영체제 시간 확인
        - $ hwclock -r
        - $ date

      * 운영체제 시간을 참조하여 하드웨어 시간 재설정
        - $ hwclock -w

      * 파일 허가권 종류
        - permission
        - attribution
        - SetUID, SetGID, StickyBit

      * 특정파일에 SetUID Bit 설정하기
        - $ chmod 4<xxx> testfile
        - SetUID가 설정된 파일을 실행하였을 경우 실행되는 동안 실생시킨 사용자의 권한이 아닌 파일 소유자권한으로 실행한다.

      * 특정 디렉토리에 Sticky Bit 설정하기
        - $ chmod 1<xxx> testdir
        - testdir 디렉토리내에서 특정 파일을 생성하면 생성한 사용자의 소유로 파일이 생성됨

      * SetUID의 대문자 S의 의미
        - SetUID는 설정하였지만 일반퍼미션에 소유자퍼미션자리에 실행권한이 설정되지않았기 대문에 S로 마킹됨.  Sticky Bit의 T도 동일한 의미임.

      * Attribution - chattr & lsattr
        - chattr 명령어는 파일과 디렉토리의 속성을 지정하는 명령어
        - $ lsattr rc.local

      *특정파일에 삭제, 변경, 추가등을 불가능하게 속성부여
        - $ chattr +i rc.local
        - $ lsattr rc.local
        - i : immutable
        - a: secure deletion - 파일삭제시 해당 블럭이 모두 0으로 셋팅
        - S: synchronous updates

      * 특정 파일이 어떤 패키지에 의해 설치된 파일인가 확인
        - $ rpm -qf /bin/ps

      * 특정 패키지에 의해 설치된 모든 파일들 확인
        - $ rpm -ql httpd

      * 특정 패키지에 의해 설치된 파일들의 정상여부 점검
        - $ rpm -qs htdtp-2.2.10-2.i386

      * 특정 RPM 패키지의 설정파일들만 확인하기
        - $ rpm -qc httpd

      * 설치된 특정 RPM 패키지의 문서파일위치 확인
        - $ rpm -qd quota

      * RPM 패키지 의존성 관계 확인하기
        - $ rpm -qRp quota-3.16-5.fc10.i386.rpm

      * 설치된 RPM 패키지 변경 가능성 여부 검증하기
        - $ rpm -V httpd-2.2.10-2.i386

      * yum을 이용한 업데이트 가능한 패키지 리스트 확인하기
        - $ yum list all   (이미 설치되어있는 목록)
        - $ yum list available (설치 가능한 모든 패키지)
        - $ yum list updates (업데이트 가능한 패키지 리스트)
        - $ yum list installed <패키지 명>   (패키지의 인스톨여부 확인)

      * 라우팅설정과 라우팅 테이블 확인하는 route
        - $ route
        - $ netstat -rn

      * 특정 ethernet으로 송수신되는 패킷을 파일에 저장
        - $ tcpdump -i eth0 -w TCPDUMP
        - $ tcpdump -r TCPDUMP

      *ping
        - ICMP (Internet Control Message Protocol) 프로토콜 사용

      * 특정 도메인명의 호스트 통신경로 확인하기
        - $ traceroute www.daum.net

      * nmap
        - nmap은 사용자가 지정한 네트워크와 호스트 (서버)들을 대상으로 보안측면에서 취약한 점이 있는가를 스캐닝할 수 있고 포트기반을 스캐닝할 수 있다.
        - 옵션
          + -sS: TCP SYN 스캔
          + -sT: TCP 연결 스캔
          + -sF -sX -sN: Stealth FIN, Xmas Tree, 또는 Null 스캔모드
          + -sP: Ping 스캐닝
          + -sU: UDP 스캐닝
          + -sO: IP 프로토콜 스캔
          + -sI <zombie host[:probeport]: Idlescan
          + -sA: ACK 스캔
          + -sW: Window 스캔
          + -sR: RPC 스캔
          + -sL: List 스캔

      * nmap으로 로컬 서버 스캔해보기
        - $ nmap -sT -O -v localhost

      * 현재 시스템에 열려있는 서비스와 포트 점검
        - $ lsof | grep LISTEN

      * 특정파일이 사용하는 서비스데몬 (프로세스) 확인
        - $ lsof /lib/libdb-4.0.so

      * 현재 열려진 포트를 사용하고 있는 프로세스 확인
        - $ lsof | grep <port num>

      *현재 시스템에 열려져있는 TCP 포트 점검
        - $ lsof -i TCP | grep LISTEN

      * 환경변수 적용하여 root로 변경
        - $ su - root

      * sudo
        - sudo 명령어는 /etc/sudoers 파일에 설정되어 있는 허가된 사용자들에 한하여 허용
        - 일반사용자에게 root 사용자만 사용할 수 있는 명령어들의 사용을 허용하고자 할때 사용

      * 쿼타파일의 위치
        - 파일시스템의 루트에 위치해야함
        - aquota.user, aquota.group

      * 시스템로그파일 관리를 위한 logrotate
        - /usr/sbin/logrotate
        - /etc/cron.daily/logrotate
        - /etc/logrotate.conf
        - /etc/logrotate.d

      *logwatch의 시스템 로그분석 결과 보고
        - $ /usr/sbin/logwatch

      * /etc/fstab에 설정된 모든 스왑파일시스템을 스왑영역으로 설정
        - $ cat /etc/fstab
        - $ swapon -a     (swapoff -a , 스왑해제)

      * 시스템크론 데몬
        - 시작:
          + $ /etc/rc.d/init.d/crond start
          + $ service crond start
        - /etc/crontab
          + 01 * * * * root run-parts /etc/cron.hourly  : 매시 1분마다 실행
          + 02 04 * * * root run-parts /etc/cron.daily  : 매일 4시 02분마다 실행
          + 22 4 * * 0   root run-parts /etc/cron.weekly: 매주 일요일 4시 22분마다 실행
          + 42 4 1 * *   root run-parts /etc/cron.monthly: 매월 1일 4시 42분 마다 실행

      * 일반 사용자의 crontab 명령어 사용허가 또는 제한
        - $ cat /etc/cron.allow

      * crontab으로 설정한 개별사용자의 cron 설정, 파일로 확인
        - $ cat /var/spool/cron/<userid>

      * root 권한으로 일반 사용자의 cron 설정
        - $ crontab -u <userid> -e

      * root 권한으로 root의 cron 설정내용 확인하는 방법
        - $ crontab -l

      * root 권한으로 일반 사용자의 cron 설정내용 확인
        - $ contab -u <userid> -l

      * at으로 예약작업 설정하기
        - $ at -f /root/backup.sh 22:05  (22시 05분에 예약)
        - $ atq   (큐확인)
        - $ atrm <id>   (큐에서 id 삭제)
        - $ at -f /root/backup.sh 1pm+1days   (1일 후 오후 1시)
        - $ at -f /root/backup.sh 10182015  (2015년 10월 18일로 설정)
        - $ ls -l /var/spool/at     (예약된 작업이 파일로 저장됨)
        - $ atrun    (큐에 있는 예약된 작업 바로 실행)
        - $ batch -f /root/backup.sh 20:00   (at과 동일)

      * 커널 파라미터값 확인 및 설정하는 sysctl 사용법
        - $ cat /etc/sysctl.conf

      * 현재 커널의 모든 파라미터값 확인
        - $ sysctl -a

      * 커널의 특정 파라미터값 변경하기
        - $ sysctl -a | grep kernel.sysrq
        - $ sysctl -w kernel.syssrq=1
        - $ cat /proc/sys/kernel/sysrq

      * modprobe 명령어로 로드되어있는 모듈 제거하기
        - $ modprobe -r birdge

      * modprobe 명령어로 현재 사용되고 있는 커널모듈 설정확인
        - $ modprobe -c
        - $ modprobe -d | grep <모듈명>

      *modprobe 명령어로 전체(특정) 커널모듈 파일 확인하기
        - $ modprobe -l
        - $ modprobe -l | grep <모듈명>

      * 커널모듈 정보를 확인
        - $ lsmod
        - $ cat /proc/modules

      * 리눅스 커널모듈의 의존성관계 재설정
        - $ depmod -a
        - 리눅스 부팅과정에서 "Finding modules dependance..." 에러가 발생할 경우 싱글모드로 들어가서 depmod -a 실행

      2011년 6월 15일 수요일

      Serial Port Terminal vs. Pseudo Terminals

      *Serial Port Terminal

      The computer considers each serial port to be a "device". It's sometimes called a terminal device since at one time terminals were the most common use for a serial port. For each such serial port there is a special file in the /dev (device) directory. /dev/ttyS0) is the special file for the serial port known as COM1 in the DOS/Windows world.
      To send text to a terminal you may redirect standard output of some command-line command to the appropriate special file. For example typing "echo test > /dev/ttyS1" at the command prompt should send the word "test" to the terminal on ttyS1 (COM2) provided you have write permission on /dev/ttyS1. Similarly, typing "cat my_file > /dev/ttyS0" will send the contents of the file my_file to COM1 (ttyS0).

      *Pseudo Terminals


      Pseudo terminals are pairs of devices such as /dev/ptyp3 and /dev/ttyp3. There is no physical device directly associated with either of them, not even a serial port connector. But if a program treats ttyp3 like it was a serial port, what is read and written to that port appears on the other member of the pair ptyp3 which another program uses to read and write to. Thus two programs talk to each other via this method and one program on ttyp3 thinks it's talking to a serial port. It's something like a "pipe" between these two tty's.
      For talking to ttyp3, any program designed to talk to a serial port will do. But for the other program that talks to ptyp3, it must have been specially written to talk to it. It's mainly programmers that must concern themselves with pseudo terminals and most users don't need to worry about them.
      Here's an example: If someone connects via telnet to your computer over a network (you are a telnet server), the part of the telnet program handling this connection on your computer may wind up connected to the pseudo terminal ptyp2. A getty program should be running on the corresponding ttyp2. Getty thinks it's talking to a terminal. When telnet gets a character from the remote client, it goes thru ptyp2 to ttyp2 to getty which then sends back "login:" routed via ttyp2, ptyp2, your server telnet program, and then out to the network back to the client. Here the login program and the telnet server program talk to each other via a "pseudo terminal". Note that there is no pseudo terminal used on the client computer, just telnet. Of course the server allocates a pseudo terminal (on the server) for each client.
      In X Window, the terminal emulator programs (such as xterm) use pseudo terminals. Ham radio programs under Linux also use them. By using certain application software, it is possible to have 2 or more pseudo terminals attached to the same physical serial port.
      For a pseudo terminal pair such as ptyp3 and ttyp3, the pty... is the master or controlling terminal and the tty... is the slave.
      There are only 16 ttyp's: ttyp0-ttypf (f is a hexadecimal digit). To get more pairs, more letters such as q, r, s are used instead of p. For example the pair ttys8, ptys8 is a pseudo terminal pair. Later on, even more letters were added so as to allow even more pseudo terminals. And when z was reached, they wrapped around to a. This is confusing but old habits are difficult to change. Today Linux allow say ttyp189 but it's not used. The device file system, which was abandoned in 2004, would have used tty/s189. Be sure not to type say ttys2 if you mean ttyS2 (a real serial port).
      The master and slave are really the same "port" but the slave is used by the application program and the master is used by a network program (or the like) which supplies (and gets) data to/from the slave port. The program using the slave port can run "as is" since it thinks it is talking to a serial port.
      Unix98 pseudo terminals (available on Linux) is more advanced than the above but the basic concepts are the same (only the device names and methods of creating them change). It creates pseudo terminal devices on request so there is no need to check if the pseudo terminal you might want to use in in use. By opening /dev/ptmx a new pseudo terminal pair is created. The master doesn't show up as a device but is just a file descriptor number passed to the computer program that opened /dev/ptmx. But the slave is put into the /dev/pts directory: for example" /dev/pts/3.
      The /dev/pts directory is considered to be a file system of type devpts and appears in the lists of mounted filesystems. While the "file" /dev/pts/3 looks like an entry in the now obsolete device filesystem, /dev/pts Is really a wholly different kind of filesystem.
      See the Linux manual pages "pty" and "pts" (Unix 98 style) for more details. For programmers there's the man-page openpty/forkpty (either name displays the same man-page) which assumes that you already understand pseudo terminals. There is a usr/include/pty.h file for use by programmers. In earlier versions of Linux there was a pty.o module, but it now seems that it's been built into the kernel. Here's an example of some options available when you are compiling a Linux 2.6 kernel:


      CONFIG_UNIX98_PTYS=y CONFIG_LEGACY_PTYS=y
      CONFIG_LEGACY_PTY_COUNT=256 

      source: http://www.tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.1

      2011년 6월 14일 화요일

      OpenNebula - vm으로부터 image 생성

      Steps

      1. onevm list 로부터 image로 생성할 vm id, disk id를 구한다.
          $ onevm list | grep <username>


      2. vm을 image로 save한다.
          $ onevm saveas <vm_id> <disk_id> <image_name>
       
          vm이 Shutdown되기전까지 Image가 디스크에 저장되지 않음.


      3. oneimage list 로 생성된 image id 값을 확인한다.
          $ oneimage list <image_id>


      4. image에 persistent 셋팅
          $ oneimage persistent <image_id>


      5. image를 enable 시킴
          $ oneimage enable <image_id>


      6.  vm을 shutdown시킴. Shutdown 시키지않으면 image가 생성되지 않음.
          $ onevm shutdown <vm_id>

      7. oneimage show <image_id>를 통해 image가 위치곳 확인

      - Done

      2011년 6월 10일 금요일

      libvirt

      • Linux 가상화를 위한 Linux API
      • Host에서 수행중인 VM을 관리하기위한 Hypervisor-Agnostic API 제공
      • XEN용 VM을 관리하기위해 개발되었으나 다른 Hypervisor 지원

      qemu-kvm vs. kvm-xx vs. kvm-kmod

      kvm : Kernel-based Virtual Machine

      qemu-kvm : kvm을 위해 optimized된 qemu이며 stable한 버전. Kernel module을 포함하지않고 user space part만 포함하고 있음. Hardware virtualization feature를 가지고 있음.

      kvm-xxx : kvm-xxx로 이름지어지는 것은 모두 development 단계이며 unstable. kernel space + user space part 포함.

      kvm-kmod : kvm-xxx와 다르며, kernel space part임. qemu-kvm이 user space part.