UNIX/Redhat

Linux 관리자 단기집중과정 -중급 1일차

99iberty 2018. 7. 12. 10:53


1장 access the command line



0. vim 옵션

:se nu    - 행번호 표시


1. 리눅스 옵션 의미

-옵션 아규먼트  : 유닉스때부터 계열 명령 (문자 형태)

--옵션 아규먼트 : 단어 형태


2. su

1) su - 로그인명 (- , -l, --login 같은 옵션)

2) - 쓰는 이유 : - 안 쓰면 현재 유저의 설정값을 가지고 로그인 전환.

3) sudo : 권한 위임. su - root 하면 root 암호를 알려줘야 함.

이런 작업은 일반유저도 할 수 있도록 설정해줌.

root 암호 안 알려줘도 됨.

/etc/sudoers 설정

4) vim /etc/sudoers  ---> visudo

## Allows people in group wheel to run all commands
     %wheel  ALL=(ALL)       ALL, !SHUTDOWN

.1열 : %wheel   : wheel 그룹에 설정 (% 없으면 걍 계정명)

.2열 : 호스트명 = (실행계정)

.3열 : 명령어 (저기서 SHUTDOWN은 Cmnd_Alias SHUTDOWN으로 alias 준 명령어임.)


## 아래와 같이 visudo 안에 command alias를 설정할 수 있다. 위에 명령어 계속 나열하는건 지저분하니....

## Networking
     # Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/        dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial        , /sbin/iwconfig, /sbin/mii-tool

.#  ll /usr/sbin/shutdown /sbin/shutdown

[root@station7 ~]# ll /usr/sbin/shutdown /sbin/shutdown
lrwxrwxrwx. 1 root root 16 Jul 11 11:51 /sbin/shutdown -> ../bin/systemctl
lrwxrwxrwx. 1 root root 16 Jul 11 11:51 /usr/sbin/shutdown -> ../bin/systemctl


[root@station7 ~]# ll /bin/systemctl
-rwxr-xr-x. 1 root root 637664 May 25  2017 /bin/systemctl
[root@station7 ~]# ll /usr/bin/systemctl
-rwxr-xr-x. 1 root root 637664 May 25  2017 /usr/bin/systemctl

---> /bin/systemctl 이 777이니까 750으로 변경해야 shutdown이 안 먹힘...?

. # chmod 750  /bin/systemctl    /usr/bin/systemctl


. sudoers 파일이 일반유저인 guru가 열수 없게 되어 있다.

[guru@station7 ~]$ ll /etc/sudoers
-r--r-----. 1 root root 4008 Jul 11 20:00 /etc/sudoers
[guru@station7 ~]$ cat /etc/sudoers
cat: /etc/sudoers: Permission denied


. sudo 명령어를 쓰면 guru 암호를 묻는다.

[guru@station7 ~]$ sudo cat/etc/sudoers

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for guru:


. shutdown 못 함

[guru@station7 ~]$ shutdown
-bash: /usr/sbin/shutdown: Permission denied




2장 Manage files from the command line


1. 설정된 alias 확인

[root@station7 /]# alias
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

. -i : interactive 옵션


2. touch

. 0바이트짜리 파일 생성

. 기존에 있던 파일에 touch 명령어 쓰면 timestamp 가 현재시각으로 업데이트됨.


3. 파일시스템 링크

. 물리적/논리적 분할된 디스크영역에 하드링크를 걸 수 없다.

. 심볼릭 링크(소프트 링크) : 다른 영역에도 심볼링 링크 걸 수 있다.

[root@station7 ~]# ln /etc e.link (하드링크 생성 불가능)
ln: ‘/etc’: hard link not allowed for directory
[root@station7 ~]#
[root@station7 ~]# ln -s /etc e.link (심볼릭 링크로는 생성 가능)
[root@station7 ~]# ls
anaconda-ks.cfg  Documents  e.link  original-ks.cfg  Public     toppost.log
Desktop          Downloads  Music   Pictures         Templates  Videos




3장 Get help in a textual environment


1. 시스템 인포 확인

- 배포판 버전 확인 :# cat /etc/os-release

[root@station7 yum.repos.d]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

- 커널 버전 확인 :# uname -a

[root@station7 yum.repos.d]# uname -a
Linux station7.example.com 3.10.0-514.26.1.el7.x86_64 #1 SMP Thu Jun 29 16:05:25 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux



2. man

1) man [section] name

- section 옵션을 줘야 할 때가 있다.

- 보통은 명령어가 먼저 나옴.

- man -k passwd : 이 단어가 나와있는 모든 매뉴얼 뒤짐. 무슨 섹션번호일지 모를때 keyword로 검색

[root@station7 yum.repos.d]# man -k passwd
chpasswd (8)         - update passwords in batch mode
fgetpwent_r (3)      - get passwd file entry reentrantly
getpwent_r (3)       - get passwd file entry reentrantly
gpasswd (1)          - administer /etc/group and /etc/gshadow
grub2-mkpasswd-pbkdf2 (1) - Generate a PBKDF2 password hash.
kpasswd (1)          - change a user's Kerberos password
lpasswd (1)          - Change group or user password
lppasswd (1)         - add, change, or delete digest passwords.
mkpasswd (1)         - generate new password, optionally apply it to a user
pam_localuser (8)    - require users to be listed in /etc/passwd
passwd (1)           - update user's authentication tokens
sslpasswd (1ssl)     - compute password hashes
passwd (5)           - password file
passwd2des (3)       - RFS password encryption
pwhistory_helper (8) - Helper binary that transfers password hashes from pass...
smbpasswd (5)        - The Samba encrypted password file

- man Sections :

1 : User Commands

2 : System Calls

3 : Subroutines

4 : Devices

5 : File Formats

6 : Games

7 : Miscellaneous

8 : System Administration

n : new



4장 Create, view, and edit text files


1. Communication Channels

1) STDIN : 0 (파일디스크립터 번호)

2) STDOUT : 1

3) STDERR  : 2

4) 입력 리다이렉션 : $ sort < /etc/passwd  ("0<" 0이 생략되어 있음.)

5) 출력 리다이렉션 : $ echo 1000 > /proc/sys/fs/file-max ("1>" 1이 생략되어 있음.)

6) 에러 리다이렉션 : $ ls -alR /proc/ 2> /dev/null (화면이나 파일 말고 걍 출력 안 하고 싶음)

   $ ls -R /proc > output  2>&1  (에러든 정상이든 하나의 파일에 다 저장. 에러도 1(표준출력)로 보내겠다.)

   $ ls -R /proc &> output (에러든 정상이든 하나의 파일에 다 저장. 다만 이 방식은 유닉스에서 안 먹힘.)


7) tr : translates

. 파이프 또는 리다이렉션으로만 데이터 전달 가능.

. 단어 단위가 아니고 캐릭터 하나씩 대응

# tr A-Z a-z <  hello.txt

: 파일 내 대문자를 소문자로 치환해서 화면에 보여주겠다.

[root@station7 ~]# cat hello.txt
Hello
How are you??

[root@station7 ~]# cat hello.txt | tr a-z A-Z (소문자를 대문자로)
HELLO
HOW ARE YOU??


[root@station7 ~]# tr A-Z a-z < hello.txt (대문자를 소문자로)
hello
how are you??


[root@station7 ~]# uname -r
3.10.0-514.26.1.el7.x86_64

[root@station7 ~]# uname -r | tr 16 I8

(1은 I로, 6은 8로 치환하겠다.)

(16을 I8로 바꾸겠다가 아님.)

3.I0.0-5I4.28.I.el7.x88_84



8) 파이프

Piping allows the STDOUT from one program (on the left of the pipe) to become the STDIN of another (on the right of the pipe)

. 파이프 앞 :

. 파이프 중간 :

. 파이프 맨끝 : 출력리다이렉션과 에러리다이렉션이 가능

. Usually used for feeding STDERR into the pipeline along with STDOUT :

   # ls /proc/ 2>&1 | grep kernel


9) The Streaming Editor : sed

. 스트리밍 에디터

. s : 치환

. d : delete (행 자체를 삭제)

. g : global (첫번째 만나는 단어 말고 모두 대상) (근데 // 이걸로 검색하면 g 안해도 다 적용되는듯.)

[root@station7 test]# cat sed.txt
coffee coffee coffee

coffee

2003 coffee coffee

2003 decaf coffee

2000 coffee coffee

decaf 2003 coffee

2003 decaf
[root@station7 test]# sed 's/coffee/milk/' sed.txt

(sed.txt의 파일내용의 coffee를 milk로 바꾸겠다.)

(실제 파일 내용이 바뀌는건 아니고 출력화면에만 바뀌어서 보여진다.)


milk coffee coffee (첫번째 커피만 바뀌어버렸다.)

milk

2003 milk coffee

2003 decaf milk

2000 milk coffee

decaf 2003 milk

2003 decaf


[root@station7 test]# sed 's/coffee/milk/g' sed.txt

(global하게 전체 coffee를 milk로 바꾸겠다.)

milk milk milk

milk

2003 milk milk

2003 decaf milk

2000 milk milk

decaf 2003 milk

2003 decaf


[root@station7 test]# sed '/2003/s/coffee/tea/g' sed.txt

(2003이 들어간 행을 먼저 검색한 후 해당 행에서 coffee 를 tea로 g, 모두 치환)


coffee coffee coffee

coffee

2003 tea tea

2003 decaf tea

2000 coffee coffee

decaf 2003 tea

2003 decaf

[root@station7 test]# sed '/2003/d' sed.txt

(2003 들어가는 행 다 지우겠다.)

coffee coffee coffee

coffee



2000 coffee coffee


10) awk

. 패턴 스캐닝 및 processing language.

[root@station7 test]# cat awk.txt
milk dairy coffee 2.00

hamburger meat tea 2.75

cheese dairy cola 1.50
[root@station7 test]# grep tea awk.txt
hamburger meat tea 2.75

[root@station7 test]# awk '/tea/ {print}' awk.txt

awk '작업할 내용' 파일명

(tea 들어간 행을 {print} 출력해달라.)

hamburger meat tea 2.75


[root@station7 test]# awk '{print $2,$4}' awk.txt

(두번째, 네번째 컬럼 출력)

dairy 2.00
 
meat 2.75
 
dairy 1.50


[root@station7 test]# awk '/dairy/ {print $2,$3,$4}' awk.txt

(dairy 들어간 행의 2,3,4번 컬럼 출력)

dairy coffee 2.00
dairy cola 1.50


11) wc

[root@station7 test]# cat awk.txt
milk dairy coffee 2.00

hamburger meat tea 2.75

cheese dairy cola 1.50
[root@station7 test]#
[root@station7 test]# wc awk.txt
 5 12 73 awk.txt
5개의 행, 12개의 단어, 73개의 문자(띄어쓰기 엔터도 모두 포함)로 이루어져 있다.




5장 Manage Local Linux Users and groups


1. User Administration

1) 시스템 계정 : uid 1~999 (리눅스 7부터, 이전버전은 499까지)

2) useradd -o : uid 똑같은 계정 생성하고 싶을때. 보통 루트와 똑같은 권한의 계정 생성하고 싶을때 사용한다.

3) newgrp

# newgrp wheel 하면 내 프라이머리 그룹이 바뀜.

# newgrp 하면 다시 원래 그룹으로 프라미어리 그룹이 바뀜.

4) userdel

-r : 홈디렉토리랑 mail spool까지 삭제

5) '    : 예외없이 특수문자 모두 해제

6) "    : \ , $, $(), {} 제외하고 특수문자 해제

7) \  : 바로 뒤 특수문자 하나만 해제

[ccc@station7 aaa]$ ls -al
total 12
drwxrwxrwx. 3 aaa  aaa   94 Jul 12 01:26 .
drwxr-xr-x. 7 root root  66 Jul 12 01:05 ..
-rw-r--r--. 1 aaa  aaa   18 Dec  6  2016 .bash_logout
-rw-r--r--. 1 aaa  aaa  193 Dec  6  2016 .bash_profile
-rw-r--r--. 1 aaa  aaa  231 Dec  6  2016 .bashrc
-rw-r--r--. 1 ccc  bbb    0 Jul 12 01:26 ccc2.txt
drwxr-xr-x. 4 aaa  aaa   39 Jul 11 11:48 .mozilla

[root@station7 aaa]# ls -al
total 12
drwxrwxrwx. 3 aaa  aaa   94 Jul 12 01:26 .
drwxr-xr-x. 6 root root  55 Jul 12 01:26 ..
-rw-r--r--. 1 aaa  aaa   18 Dec  6  2016 .bash_logout
-rw-r--r--. 1 aaa  aaa  193 Dec  6  2016 .bash_profile
-rw-r--r--. 1 aaa  aaa  231 Dec  6  2016 .bashrc
-rw-r--r--. 1 2000 bbb    0 Jul 12 01:26 ccc2.txt
drwxr-xr-x. 4 aaa  aaa   39 Jul 11 11:48 .mozilla


----> userdel -r ccc 해도 ccc의 홈디렉토리랑 메일 스풀만 삭제 되고 ccc가 만든 파일은 삭제되지 않는다.

        따라서 ccc가 만들어둔 저 파일은 uid 값이 /etc/passwd에 없으니 uid 컬럼 부분에 C의 uid인 2000 가 덜렁 남겨져 있다.


[root@station7 home]# find /home -nouser -exec rm -rf {} \;

----> /home 밑에 user가 없는 것들에 대해 모두 삭제해라.


▼ 짜잔! ccc2.txt 파일 사라짐.

[root@station7 aaa]# ls -al
total 12
drwxrwxrwx. 3 aaa  aaa   78 Jul 12 01:32 .
drwxr-xr-x. 6 root root  55 Jul 12 01:26 ..
-rw-r--r--. 1 aaa  aaa   18 Dec  6  2016 .bash_logout
-rw-r--r--. 1 aaa  aaa  193 Dec  6  2016 .bash_profile
-rw-r--r--. 1 aaa  aaa  231 Dec  6  2016 .bashrc
drwxr-xr-x. 4 aaa  aaa   39 Jul 11 11:48 .mozilla




                  



8) 퀴즈1. /etc/passwd 파일에서 nfs 단어가 들어간 라인을 검색해 /tmp/hpedu.txt 로 저장하라. (awk 사용)

# awk '/nfs/ {print}' /etc/passwd > /tmp/hpedu.txt

9) 퀴즈2. 3개의 계정 (harry ,natasha, tom)을 생성하고 암호는 linux1234로 초기화.

 (harry, natasha 계정의 보조그룹을 adm, tom 계정의 로그인 쉘은 non-interactive가 되도록 설정하라.)

# useradd -G adm harry; useradd -G adm natasha

# useradd -s /sbin/nologin tom

# passwd harry 하고 인터렉티브하게 linux1234입력 혹은 # echo linux1234 | passwd --stdin harry



2. Password Aging

1) 계정/그룹을 만드는 3요소 :

. /etc/skel (디렉토리)                 : 뼈대가 되는. 이 디렉토리에 있는 내용이 그대로 복사되어 홈디렉토리의 컨텐츠를 만듦.

. /etc/default/useradd (파일)  : useradd했을때 디폴트로 만드는 내용들

[root@station7 skel]# cat -n /etc/default/useradd
     1    # useradd defaults file
     2    GROUP=100                                  // 지금 쓰지 않는 unix 잔재. users그룹의 아이디.
     3    HOME=/home
     4    INACTIVE=-1                                 // 암호 무한대
     5    EXPIRE=                                          // 계정 자체도 만료 안 되게
     6    SHELL=/bin/bash
     7    SKEL=/etc/skel
     8    CREATE_MAIL_SPOOL=yes       // 계정 로그인할때동안 메일 대기상태로 있고 로그인하면 그때 계정한테 주겠다.
     9   

. /etc/login.defs                    : 암호 만료날짜 복합도 같은 설정 같은거 설정.

[root@station7 skel]# cat -n /etc/login.defs
     1    #
     2    # Please note that the parameters in this configuration file control the
     3    # behavior of the tools from the shadow-utils component. None of these
     4    # tools uses the PAM mechanism, and the utilities that use PAM (such as the
     5    # passwd command) should therefore be configured elsewhere. Refer to
     6    # /etc/pam.d/system-auth for more information.
     7    #
     8   
     9    # *REQUIRED*
    10    #   Directory where mailboxes reside, _or_ name of file, relative to the
    11    #   home directory.  If you _do_ define both, MAIL_DIR takes precedence.
    12    #   QMAIL_DIR is for Qmail
    13    #
    14    #QMAIL_DIR    Maildir
    15    MAIL_DIR    /var/spool/mail
    16    #MAIL_FILE    .mail
    17   
    18    # Password aging controls:
    19    #
    20    #    PASS_MAX_DAYS    Maximum number of days a password may be used.
    21    #    PASS_MIN_DAYS    Minimum number of days allowed between password changes.
    22    #    PASS_MIN_LEN    Minimum acceptable password length.
    23    #    PASS_WARN_AGE    Number of days warning given before a password expires.
    24    #
    25    PASS_MAX_DAYS    99999
    26    PASS_MIN_DAYS    0
    27    PASS_MIN_LEN    5
    28    PASS_WARN_AGE    7
    29   
    30    #
    31    # Min/max values for automatic uid selection in useradd
    32    #
    33    UID_MIN                  1000
    34    UID_MAX                 60000
    35    # System accounts
    36    SYS_UID_MIN               201
    37    SYS_UID_MAX               999
    38   
    39    #
    40    # Min/max values for automatic gid selection in groupadd
    41    #
    42    GID_MIN                  1000
    43    GID_MAX                 60000
    44    # System accounts
    45    SYS_GID_MIN               201
    46    SYS_GID_MAX               999
    47   
    48    #
    49    # If defined, this command is run when removing a user.
    50    # It should remove any at/cron/print jobs etc. owned by
    51    # the user to be removed (passed as the first argument).
    52    #
    53    #USERDEL_CMD    /usr/sbin/userdel_local
    54   
    55    #
    56    # If useradd should create home directories for users by default
    57    # on RH systems, we do. This option is overridden with the -m flag on
    58    # useradd command line.
    59    #
    60    CREATE_HOME    yes
    61   
    62    # The permission mask is initialized to this value. If not specified,
    63    # the permission mask will be initialized to 022.
    64    UMASK           077
    65   
    66    # This enables userdel to remove user groups if no members exist.
    67    #
    68    USERGROUPS_ENAB yes
    69   
    70    # Use SHA512 to encrypt password.
    71    ENCRYPT_METHOD SHA512



위 파일들을 수정하면 계정 생성할때마다 위 파일들을 참조하여 반영.