스크립트로 파일 내 문자열 수정 할 경우. 유용한 예제.

 

 

정규식

. -> 모든 문자

* -> 0개 이상

? -> 1개 또는 0개

 

예제 1

sed -i "s/\(# \)\?registry_host:.*/registry_host: \"${PRIVATE_REGISTRY}\"/" offline.yml

sed -i 's/\(# \)\?docker_insecure_registries:/docker_insecure_registries:/' offline.yml

-> 변수를 받을 경우 쌍따옴표(") 사용.

-> 변수가 있는데 따옴표(')를 사용한다면 문자 그대로 출력 ex) ${PRIVATE_REGISTRY}

->  \(# \)\? 원래 형태는 (# )? 이며, 특수문자이기 때문에 역슬래시(\)로 체크

->  (# )?registry_host 의미는 registry_host 또는 # registry_host를 의미 함

 

 

예제 2

sed -i "/docker_insecure_registries:/a\  - ${PRIVATE_REGISTRY}" docker.yml

sed -i '/docker_insecure_registries:/a\  - brightforest.com' docker.yml

-> a 옵션은 docker_insecure_registries: 다음라인에   - ${PRIVATE_REGISTRY} 를 추가

-> i 옵션은 이전 라인에 추가

 

 

예제 3

sed -i "s/container_manager: .*/container_manager: ${CLUSTER_RUNTIME/" k8s-cluster.yml

sed -i "s|kube_service_addresses: .*|kube_service_addresses: ${SERVICE_NETWORK}|" k8s-cluster.yml

-> 구분자로 /와 | 모두 사용 가능

-> path가 들어갈 경우 역슬래시를 써야해서 구분자 /를 쓰면 귀찮아짐

-> path가 있을 경우 구분자 |를 사용하면 역슬래시를 안써도 되서 편함.

 

 

예제 4

sed -i "s/\(# \)\?http_proxy: .*/http_proxy: /"http:/\/\${PROXY_SERVER}\"/" all.yml

sed -i "s/127\.0\.0\.1:6443/${MASTER0_IP}:6443/g" kube-admin.conf

-> 점(.) 앞에도 역슬래시(\)를 써야 함

 

 

 

옵션 참고

https://jhnyang.tistory.com/m/287

1. tee 명령어

 - standard input에서 문자열을 읽어서 standard output과 파일에 문자열을 씀

 

 

2. 사용법

(1) echo 명령어와 사용

 - test.txt에 기존 내용이 있다면 모두 삭제되고 "hello"만 저장

$ echo "hello" | tee test.txt

 

(2) cat 명령어와 사용

  - 파일을 읽어서 새로운 파일로 내용 저장

$ cat test.txt | tee test2.txt

 

(3) echo 명령어로 기존 파일 뒤에 내용 추가

$ echo "world" | tee -a test.txt

 

(4)  /dev/null을 이용하여 터미널에는 표기되지 않게 사용

$ echo "hello" | tee -a test.txt /dev/null

 

 

3. 심화

$ echo "hello" >> test.txt

$ echo "hello" | tee -a test.txt

 - 위 두 명령어는 같은 결과를 보임

 - 일반사용자 계정일 경우 sudo echo와 같이 사용할 경우 root 권한 파일에는 Permission denied로 정상동작하지 않음

 - 위와 같은 경우 echo를 sudo tee로 받아서 실행하면 정상적으로 작동

 - 쉘 스크립트에서 root 권한으로 특정파일을 쓰거나 append 할 때 주로 사용한다고 함.

 

 

 

참고) https://www.lesstif.com/lpt/linux-tee-89556049.html

 

구성내용

 - kubernetes master Node에 설정

 - deploy 서버가 별도로 존재하며 설정파일은 ansible을 사용하여 배포

 

서버 환경

Node IP VIP
deploy xx.xx.0.10  
master001 xx.xx.0.31 xx.xx.0.30
master002 xx.xx.0.32  
master003 xx.xx.0.33  

 

 

1. install haproxy, keepalived

# ansible -m shell -a 'yum -y install haproxy keepalived' -i inventory/k8s/inventory.ini kube_control_plane

 

2. backup config

# ansible -m shell -a 'mv -f /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.original' -i inventory/k8s/inventory.ini kube_control_plane

# ansible -m shell -a 'mv -f /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.original' -i inventory/k8s/inventory.ini kube_control_plane

 

3. Create haproxy & keepalived config on Deploy Node

keepalied.j2
cat << EOF > keepalived.j2
global_defs {
    notification_email {
    root@localnet
}
  
notification_email_from {{ inventory_hostname }}@localnet
    smtp_server localhost
    smtp_connect_timeout 30
}
  
vrrp_script chk_haproxy { 
    script "killall -0 haproxy"
    interval 2
    weight 2
}
  
vrrp_instance VI_{{ inventory_hostname }} {
    state MASTER
    interface eth0
    virtual_router_id 150
    priority {{ 102 - (inventory_hostname | regex_replace('test-master(\\\\d{2})', '\\\\1')) | int }}
    advert_int 1
    authentication {   
        auth_type PASS
        auth_pass p@ssw0rd
    }
    virtual_ipaddress {
        xx.xx.0.30
    }
 
    track_script {
        chk_haproxy
    }
}
EOF

 

haproxy.j2
cat << EOF > haproxy.j2
global
    log         127.0.0.1 local2 
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
 
    stats socket /var/lib/haproxy/stats
 
 defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 1
    timeout http-request    10s
    timeout queue           20s
    timeout connect         5s
    timeout client          20s
    timeout server          20s
    timeout http-keep-alive 10s
    timeout check           10s
 
frontend apiserver
    bind *:8443
    mode tcp
    option tcplog
    default_backend apiserver
 
backend apiserver
    option httpchk GET /healthz
    http-check expect status 200
    mode tcp
    option ssl-hello-chk
    balance     roundrobin
 
    server test-master001 xx.xx.0.31:6443 check
    server test-master002 xx.xx.0.32:6443 check
    server test-master003 xx.xx.0.33:6443 check
EOF

*샘플 파일 위치 참고.

/usr/local/etc/keepalived/samples

/usr/share/doc/keepalived-1.3.5/samples

 

 

4. Copy config to Master Node

# ansible -m template -a "src=keepalived.j2 dest=/etc/keepalived/keepalived.conf" -i inventory/k8s/inventory.ini kube_control_plane

# ansible -m template -a "src=haproxy.j2 dest=/etc/haproxy/haproxy.cfg" -i inventory/k8s/inventory.ini kube_control_plane

 

 

5. start haproxy, keepalived

# ansible -m shell -a "systemctl start haproxy" -i inventory/k8s/inventory.ini kube_control_plane

# ansible -m shell -a "systemctl start keepalived" -i inventory/k8s/inventory.ini kube_control_plane

 

# ansible -m shell -a "systemctl enable haproxy" -i inventory/k8s/inventory.ini kube_control_plane

# ansible -m shell -a "systemctl enable keepalived" -i inventory/k8s/inventory.ini kube_control_plane

 

 

6. Check

6-1 Check keepalived

(1) check vip on test-master1
(k8s-env) [root@test-deploy kubespray]# ansible -m shell -a "ip a | grep 20.21.0.30" -i inventory/k8s/inventory.ini kube_control_plane
test-master002 | FAILED | rc=1 >>
    non-zero return code
test-master001 | CHANGED | rc=0 >>
    inet xx.xx.0.30/32 scope global eth0
test-master003 | FAILED | rc=1 >>
    non-zero return code

 

(2) stop keepalived on test-master001
(k8s-env) [root@test-deploy kubespray]# ansible -m shell -a "systemctl stop keepalived" -i inventory/k8s/inventory.ini test-master001
test-master001 | CHANGED | rc=0 >>

 

(3) move vip to test-master002
(k8s-env) [root@test-deploy kubespray]# ansible -m shell -a "ip a | grep xx.xx.0.30" -i inventory/k8s/inventory.ini kube_control_plane
test-master002 | CHANGED | rc=0 >>
    inet xx.xx.0.30/32 scope global eth0
test-master003 | FAILED | rc=1 >>
    non-zero return code
test-master001 | FAILED | rc=1 >>
    non-zero return code

 

 

 

 

 

 

1. sshpass 설치

# yum install sshpass

 

2. ssh key 생성

# ssh-keygen -b 2048 -t rsa -f ~/.ssh/id_rsa -q -N ""

 

3. hosts 파일 등록

 

4. ssh 설정변경

cat << EOF > /root/.ssh/config

Host *

  StrictHostKeyChecking no

  UserKnownHostsFile /dev/null

EOF

 

5. 20.21 대역 서버에 키 복사

# cat /etc/hosts | grep 20.21 | grep -v deploy | awk '{print "sshpass -p root ssh-copy-id "$1 }' | sh

 

CentOS Linux release 7.9.2009 (Core)

내부망 Hostname  
20.21.0.10 test-deploy 인터넷 가능
20.21.0.31 test-master001 인터넷 불가
20.21.0.32 test-master001
20.21.0.33 test-worker001
20.21.0.34 test-worker001
20.21.0.35 test-worker001

 

 

1. 웹서버 설치

[root@test-deploy ~]# yum install httpd

[root@test-deploy ~]# yum install epel-release

 *epel-release : extra packages for enterprise linux, 커뮤니티 기반 저장소

 

*DocumentRoot 변경[root@test-deploy conf]# vi /etc/httpd/conf/httpd.conf==> DocumentRoot "/var/www/repos"

 

2.  패키지 설치

[root@test-deploy ~]# yum install createrepo yum-utils

 

3. repository 디렉터리 생성

[root@test-deploy html]# mkdir -p /var/www/repos/{base,centosplus,extras,updates}

 

4. Synchronize repositories

4-1 CentOS

# reposync -nlm --repoid=base --download-metadata --download_path=/var/www/repos/
# reposync -nlm --repoid=extras --download-metadata --download_path=/var/www/repos/
# reposync -nlm --repoid=updates --download-metadata --download_path=/var/www/repos/

 

4-2 epel

# reposync -nlm --repoid=epel --download-metadata --download_path=/var/www/repos/

 

4-3 docker-ce

# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

# reposync -lm --repoid=docker-ce-stable --download-metadata --download_path=/var/www/repos/

*docker 이전버전이 필요해서 n 옵션을 안씀

 

reposync 옵션
  -n, --newest-only     Download only newest packages per-repo
  -l, --plugins         enable yum plugin support
  -m, --downloadcomps   also download comps.xml

 

5. createrepo
createrepo -v /var/www/repos/base -o /var/www/repos/base
createrepo -v /var/www/repos/extras -o /var/www/repos/extras
createrepo -v /var/www//repos/updates -o /var/www/repos/updates
createrepo -v /var/www/repos/epel -o /var/www/repos/epel
createrepo -v /var/www/repos/docker-ce-stable -o /var/www/repos/docker-ce-stable

 

6. client 서버에서 repo 파일 변경

# mkdir /etc/yum.repos.d_back

# mv /etc/yum.repos.d/* /etc/yum.repos.d_back

 

# cat /etc/yum.repos.d/test-local.repo

[base]
name=CentOS Base
baseurl=http://20.21.0.10/base
gpgcheck=0
enabled=1

[updates]
name=CentOS Updates
baseurl=http://20.21.0.10/updates
gpgcheck=0
enabled=1

[extras]
name=CentOS Extras
baseurl=http://20.21.0.10/extras
gpgcheck=0
enabled=1

[epel]
name=CentOS Epel
baseurl=http://20.21.0.10/epel
gpgcheck=0
enabled=1

[docker-ce-stable]
name=docker-ce-stable
baseurl=http://20.21.0.10/docker-ce-stable
gpgcheck=0
enabled=1

 

7. client 서버에서 repo 확인

[root@test-master001 ~]# yum clean all
Loaded plugins: fastestmirror
Cleaning repos: base docker-ce-stable epel extras updates
Cleaning up list of fastest mirrors
[root@test-master001 ~]# yum repolist
Loaded plugins: fastestmirror
Determining fastest mirrors
base                                                                  | 2.9 kB  00:00:00
docker-ce-stable                                                  | 2.9 kB  00:00:00
epel                                                                  | 2.9 kB  00:00:00
extras                                                                | 2.9 kB  00:00:00
updates                                                             | 2.9 kB  00:00:00
(1/5): docker-ce-stable/primary_db                            | 5.8 kB  00:00:00
(2/5): extras/primary_db                                          | 135 kB  00:00:00
(3/5): base/primary_db                                            | 6.1 MB  00:00:00
(4/5): epel/primary_db                                            | 6.8 MB  00:00:00
(5/5): updates/primary_db                                       | 1.8 MB  00:00:00
repo id                            repo name                                    status
base                               CentOS Base                                  10,072
docker-ce-stable               docker-ce-stable                                    6
epel                                CentOS Epel                                  13,595
extras                              CentOS Extras                                    274
updates                           CentOS Updates                               1,341
repolist: 25,288

 

 

1. 특정 경로의 txt 파일 내 문자열 치환

red -> green

$ find ./ -name "*.txt" -exec sed -i 's/red/green/g' {} \;

 

 

 

 

2. 스크립트 내 변수 사용

bright.sh 스크립트 내에서 변수를 사용하여 green으로 변경

*변수를 사용할 경우 작은따옴표(')가 아닌 큰따옴표(")를 사용해야 함

*작은따옴표를 사용 할 경우 green이 아닌, $COLOR로 변경

#!/bin/bash

COLOR=green
find ./ -name "*.txt" -exec sed -i "s/red/$COLOR/g" {} \;

 

쌍따옴표인줄 알았는데 큰따옴표라니..

ssh 접속기록을 확인해야 하는 경우.

 

 

1. 설정파일

[root@brightforest /]# vi /etc/ssh/sshd_config

# Logging
SyslogFacility AUTH
#syslog 데몬에 의한 로그 facility를 지정. 기본값은 AUTH 그외 설정(DAEMON,USER,LOCAL0~7
LogLevel INFO
# 기타 로그레벨 [QUIET(기록하지않음) , FATAL(치명적오류) , ERROR,VERBOSE,DEBUGS]

 

 

 

 

 

2. 관련 로그 경로

[root@brightforest /]# vi /var/log/secure

#password 틀렸을 경우
May  3 11:25:24 sllee sshd[2793]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=10.77.xx.xx

May  3 11:25:24 sllee sshd[2793]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root"

#로그인 성공
May  3 11:25:50 sllee sshd[2793]: Accepted password for root from 10.77.xx.xx  port 50086 ssh2

May  3 11:25:50 sllee sshd[2793]: pam_unix(sshd:session): session opened for user root by (uid=0)
#세션 끊긴 경우
May  3 11:26:09 sllee sshd[2793]: pam_systemd(sshd:session): Failed to release session: Interrupted system call
May  3 11:26:09 sllee sshd[2793]: pam_unix(sshd:session): session closed for user root


 

 

 

config 옵션 설명은 잘 설명된 블로그가 많음..

webdir.tistory.com/119

 

 

1. /etc/fstab에 마운트 설정

 - CentOS(RHEL)를 기동하고 nfs를 자동으로 마운트 시킬 때 /etc/fstab을 사용

/etc/fstab
...
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=1b5530cf-f4e1-42de-929c-7d46b0331042 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

#nfs 마운트 설정
192.168.56.100:/pool/vol_1/FILE_TEMP /FILE_TEMP                   nfs                   defauls                   0 0
192.168.56.100:/pool/vol_2/DATA /DATA                  nfs                  defauls                  0 0
192.168.56.100:/pool/vol_3/LOG /LOG                   nfs                   defauls                   0 0

 

 

2. /etc/fstab에 마운트 설정

 - 기동 시 물리&네트워크 이슈로 인해 마운트가 안된다면 정상적으로 OS가 기동되지 않을 수 있다.

 - 기동 후에 자동으로 명령어가 실행되는 /etc/rc.local에 마운트 명령어를 적용하는 것이 보다 안전할 수 있다.

*[systemctl status rc-local.service]로 해당 데몬이 활성화되어있는지 확인해보고 아래 링크를 참고하여 rc-local 데몬을 활성화시키자

/etc/rc.local
..

mount -o ro,loop /ISO/RHEL_7.2_x86_64.iso /media
mount -t nfs 192.168.56.100:/pool/vol1/FILE_TEMP /FILE_TEMP
mount -t nfs 192.168.56.100:/pool/vol2/DATA /DATA
mount -t nfs 192.168.56.100:/pool/vol3/LOG /LOG

 

3. 수동 마운트

 - 아래와 같이 mount, unmount 명령으로 사용할 수 있는데

 

 

 

https://storyerp.tistory.com/41

 

리눅스 /etc/fstab 설정

/etc/fstab 파일은 파일 초밥 템 정보를 저장하고 있는 파일입니다. 이 파일의 정보가 조금이라도 잘못 저장되면 부팅이 정상적으로 되지 않으니 주의해야 합니다. /etc/fstab 파일에서 ��

storyerp.tistory.com

http://blog.naver.com/PostView.nhn?blogId=webpioneer&logNo=221434351474&categoryNo=0&parentCategoryNo=1&viewDate=¤tPage=1&postListTopCurrentPage=1&from=postView

 

CentOS 7버전 에서 /etc/rc.local 기능 활성화하기

CentOS 7버전의 /etc/rc.local 에 스크립트를 기입했지만 리부팅후 실행이 안되어 확인해보니 7버전이후...

blog.naver.com

+ Recent posts