리눅스 쉘스크립트 배열 비교



두개의 배열을 비교 및 추가, 삭제 출력하는 방법에 대해서 알아보겠습니다.


배열의 길이는 ${#변수명[*]} 입니다. * 대신에 @ 를 사용해도 됩니다.


배열의 값 가져오는 방법은 ${변수명[0]} 이렇게 하면 첫번째 값을 가져옵니다.


#!/bin/sh


ARR_A=(1 2 3 4 5)

ARR_B=(1 2 3 5 5)


CNT=${#ARR_A[*]}

for ((i=0; i<$CNT; i++))

do

        if [ ${ARR_A[$i]} -ne ${ARR_B[$i]} ] ; then

                echo ${ARR_A[$i]}" != "${ARR_B[$i]}

        else

                echo ${ARR_A[$i]}" == "${ARR_B[$i]}

        fi

done


대충 보시면 분석이 가능할 겁니다.



▶ 배열 출력


echo ${ARR_A[@]}



▶ 배열 추가


ARR_A[${#ARR_A[*]}]=6



▶ 배열 삭제


unset ARR_A[0]


첫번째 요소를 지우는 의미입니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

MySQL checksum tables 비교 쉘스크립트



DB Replication 이 잘 되고 있는지 Master 와 Slave의 테이블 체크섬으로 비교하는 shell script 입니다.


리플리케이션을 하더라도 sysdate 처럼 서버 종속적인 데이터는 값이 다르게 들어가니깐 이점 유의해서 감안하셔야 합니다.


동일하게 행단위로 들어가면 참 좋을텐데 아쉽군요.


그리고 마스터가 mysql 이고 슬래이브가 mariadb 라면 null 값인 경우 check sum 값이 다르게 나옵니다.


#!/bin/sh


M_DB_HOST="example.com"

M_DB_USER="root"

M_DB_PASS="비밀번호"

S_DB_HOST="localhost"

S_DB_USER="root"

S_DB_PASS="비밀번호"


M_DATABASES=(`mysql -h$M_DB_HOST -u$M_DB_USER -p$M_DB_PASS -e "show databases" | grep -v "Database\|information_schema\|mysql\|performance_schema"`)


DB_CNT=${#M_DATABASES[*]}

for ((i=0; i<$DB_CNT; i++)) ; do

DATABASE=${M_DATABASES[$i]}

TABLES=(`mysql -h$M_DB_HOST -u$M_DB_USER -p$M_DB_PASS -D$DATABASE -e "show tables" | grep -v "Tables_in_"`)

TB_CNT=${#TABLES[*]}

for ((j=0; j<$TB_CNT; j++)) ; do

TABLE=${TABLES[$j]}

M_CHECKSUMS=(`mysql -h$M_DB_HOST -u$M_DB_USER -p$M_DB_PASS -D$DATABASE -e "checksum tables $TABLE" | grep "$DATABASE." | awk -F " " '{print $1"-"$2}'`)

S_CHECKSUMS=(`mysql -h$S_DB_HOST -u$S_DB_USER -p$S_DB_PASS -D$DATABASE -e "checksum tables $TABLE" | grep "$DATABASE." | awk -F " " '{print $1"-"$2}'`)

CS_CNT=${#M_CHECKSUMS[*]}

for ((k=0; k<$CS_CNT; k++)) ; do

if [ "${M_CHECKSUMS[$k]}" != "${S_CHECKSUMS[$k]}" ] ; then

echo "${M_CHECKSUMS[$k]} != ${S_CHECKSUMS[$k]}"

#mysqldump -h$M_DB_HOST -u$M_DB_USER -p$M_DB_PASS $DATABASE $TABLE --opt | gzip > $DATABASE.$TABLE.$TODAY.sql.gz

#gunzip < $DATABASE.$TABLE.$TODAY.sql.gz | mysql -h$S_DB_HOST -u$S_DB_USER -p$S_DB_PASS $DATABASE 

fi

done

done

done


위에서 마스터와 슬래이브의 호스트, 아이디, 비밀번호를 자신에 맞게 값을 넣으시면 됩니다.


echo 라인 아래 두줄은 테이블을 복사해주는 부분인데 필요하면 주석을 풀어주면 됩니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

CentOS 6.x yum 에러 No module named yum



python 을 2.7 버전대로 yum update 가 아닌 컴파일 설치를 하게 되면 아래와 같은 에러가 발생하면서 yum 이 실행이 안됩니다.


이런 경우에는 해당 버전의 yum, python rpm 을 다운로드 받아서 재설치 해주면 됩니다.


버전 확인은 cat /etc/centos-release 으로 확인하면 됩니다.


# yum update

There was a problem importing one of the Python modules

required to run yum. The error leading to this problem was:


   No module named yum


Please install a package which provides this module, or

verify that the module is installed correctly.


It's possible that the above module doesn't match the

current version of Python, which is:

2.7.11 (default, May 13 2016, 18:00:58)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)]


If you cannot solve this problem yourself, please go to

the yum faq at:

  http://yum.baseurl.org/wiki/Faq



▶ 관련 rpm 다운로드


wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/yum-3.2.29-73.el6.centos.noarch.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/yum-metadata-parser-1.1.2-16.el6.x86_64.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/yum-plugin-fastestmirror-1.1.30-37.el6.noarch.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/yum-plugin-security-1.1.30-37.el6.noarch.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/yum-utils-1.1.30-37.el6.noarch.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/python-2.6.6-64.el6.x86_64.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/python-devel-2.6.6-64.el6.x86_64.rpm

wget http://mirror.centos.org/centos-6/6/os/x86_64/Packages/python-libs-2.6.6-64.el6.x86_64.rpm


위 파일은 64bit 용입니다.


▶ rpm 재설치


# rpm -e --nodeps yum

# rpm -e --nodeps python

# rpm -Uvh --nodeps *.rpm


이제 yum 을 실행해 보세요.


# yum

bash: /usr/bin/yum: No such file or directory


이렇게 에러가 나면 위에서 다운로드 받은 rpm 을 하나씩 다시 설치해주면 됩니다.


# rpm -Uvh --nodeps yum-3.2.29-73.el6.centos.noarch.rpm

# rpm -Uvh --nodeps python-2.6.6-64.el6.x86_64.rpm


우선 이 두가지만 먼저 재설치 해보세요.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

리눅스 ssh 에서 백그라운드 실행방법



ssh 로 접속해서 시간이 오래걸리는 작업을 실행한 다음에 접속이 끊어지면 해당 프로세스는 종료가 됩니다.


접속이 끊어지더라도 백그라운드로 실행하는 방법입니다.


먼저 5분 정도 실행되는 쉘스크립트를 만들어 보겠습니다.


#!/bin/sh


for i in {1..100}

do

        echo $i

        sleep 3

done


1부터 100까지 출력하는 반복문인데 중간에 3초 동안 sleep 하는 스크립트입니다.


이 스크립트를 백그라운드로 실행을 하게 되면 ssh 접속이 끊어지더라도 계속해서 실행이 됩니다.


# ./bgtest.sh > bgtest.txt &


이렇게 명령어 뒤에 & 를 붙이면 됩니다.



그리고 아래 처럼 원격으로 실행하는 방법도 있습니다.


# ssh root@localhost "sh /root/bgtest.sh > bgtest.txt &"


몇 시간 이상 오래 걸리는 작업시에 사용하면 클라이언트 컴퓨터를 계속 켜놓을 필요가 없겠지요~


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

쉘스크립트 for 반복문 사용방법



for loop 사용 예제입니다.


숫자를 이용하는 방법과 배열을 이용하는 방법이 있습니다.



▶ 나열된 숫자를 이용하는 방법


#!/bin/sh


for i in 1 2 3 4 5

do

        echo $i

done



▶ 숫자 from ~ to 를 이용하는 방법


#!/bin/sh


for i in {1..5}

do

        echo $i

done



▶ 배열을 이용하는 방법


#!/bin/sh


alphabet="a b c d e"

for c in $alphabet

do

        echo $c

done


필요에 따라 편한 방법을 사용하면 됩니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

CentOS 7.x phpMyAdmin 특정 IP 만 허용하는 방법



phpMyAdmin 을 설치하면 기본적으로 localhost (127.0.0.1) 에서만 접근이 가능합니다.


Require ip 에 허용IP 를 추가해도 되겠지만 VirtualHost 와 방화벽을 이용해서 접근 자체를 허용IP 와 특정 포트만 접근이 가능하도록 하는 방법에 대해서 알아보겠습니다.



▶ 아파치 설정 ( vi /etc/httpd/conf.d/phpMyAdmin.conf 수정 )


#Alias /phpMyAdmin /usr/share/phpMyAdmin

#Alias /phpmyadmin /usr/share/phpMyAdmin

Listen 8081

NameVirtualHost *:8081

<VirtualHost *:8081>

    ServerName www.example.com

    DocumentRoot /var/www/html

    ErrorLog logs/www.example.com.8081-error_log

    LogFormat "%V %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" vcommon

    CustomLog logs/www.example.com.8081-access_log vcommon

    Alias /phpMyAdmin /usr/share/phpMyAdmin

    Alias /phpmyadmin /usr/share/phpMyAdmin

</VirtualHost>


Alias 부분을 찾아서 주석처리를 하고 위의 내용을 자신에 맞게 수정하고 저장합니다.


아파치를 재시작 합니다. ( # systemctl restart httpd )



▶ 방화벽 설정


# firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="허용아이피/24" port protocol="tcp" port="8081" accept'

# firewall-cmd --reload


iptables 사용자라면


# iptables -I INPUT -p tcp --dport 8081 -j DROP

# iptables -I INPUT -p tcp -s 허용아이피 --dport 8081 -j ACCEPT



이제 접속이 가능할겁니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

MySQL DB 데이터 덤프 쉘스크립트



마스터 서버의 DB data 를 슬래이브 서버에 백업하는 스크립트을 작성하고 크론에 등록하는 방법입니다.


실행 위치는 Slave 서버 기준입니다.


Master 에서 실행한다면 호스트 부분을 수정하여야 합니다.


--databases 옵션으로 데이터베이스명을 나열해서 백업할 수도 있겠지만 시간이 너무 올래걸리므로 아래처럼 분리를 해보았습니다.


#!/bin/sh


M_HOST="example.com"

M_USER="root"

M_PASS="password"

S_HOST="localhost"

S_USER="root"

S_PASS="password"

DBNAMES="

database1

database2

database3

"


for DBNAME in $DBNAMES

do

echo "mysqldump -h$M_HOST -u$M_USER -p$M_PASS act --opt | gzip > $DBNAME.sql.gz"

echo "gunzip < $DBNAME.sql.gz | mysql -h$S_HOST -u$S_USER -p$S_PASS $DBNAME"

done


위 파일을 /root/bin/dbdump.sh 로 저장합니다.


# chmod 700 /root/bin/dbdump.sh



크론에 등록해 놓으면 편하겠지요~


# vi /etc/cron.d/dbdump


30 03 * * * root /root/bin/dbdump.sh


매일 새벽 3시 30분에 실행한다는 의미입니다.



그리고 로컬이 아닌 다른 IP 에서 접근이 가능하게 하려면 미리 권한을 주어야 합니다.


GRANT ALL PRIVILEGES ON *.* TO 'root'@'접속허용아이피' identified by '비밀번호';


접속허용아이피에 % 를 주면 모든 ip에 대해서 허용한다는 의미입니다.


그리고 root 계정 보다는 다른 이름으로 만드는게 좋을 것 같습니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

리눅스 하드디스크 점검 유틸리티



스마트모니터툴로 운영중인 하드디스크 상태를 확인 할 수 있습니다.


운영중인 서버의 두번째 디스크인데 상태가 안좋아서 사용하지 않고 있는 하드디스크입니다.


# smartctl -a /dev/sdb 로 상태를 체크했는데 문제로 보이는 항목입니다.


Raw_Read_Error_Rate <= 디스크에서 읽기 실패, 소프트웨어적인 오류

Reallocated_Sector_Ct <= 섹터에 문제가 있어 다른영역으로 치환된 횟수


위 처럼 오류가 있다면 배드섹터를 체크해 보세요~


# badblocks -wsv /dev/sdb

Checking for bad blocks in read-write mode

From block 0 to 976762583

Testing with pattern 0xaa:   0.10% done, 2:38 elapsed


-w 옵션은 쓰기모드이므로 기존 데이터가 지워집니다.

비파괴 검사를 하려면 -n 을 주세요.


아래는 smartctl 전체 내용입니다.


# smartctl -a /dev/sdb

smartctl 5.43 2012-06-30 r3573 [x86_64-linux-2.6.32-431.17.1.el6.x86_64] (local build)

Copyright (C) 2002-12 by Bruce Allen, http://smartmontools.sourceforge.net


=== START OF INFORMATION SECTION ===

Model Family:     Hitachi Deskstar 7K1000.D

Device Model:     Hitachi HDS721010DLE630

Serial Number:    MSK523Y202D35C

LU WWN Device Id: 5 000cca 37fc03e15

Firmware Version: MS2OA610

User Capacity:    1,000,204,886,016 bytes [1.00 TB]

Sector Sizes:     512 bytes logical, 4096 bytes physical

Device is:        In smartctl database [for details use: -P show]

ATA Version is:   8

ATA Standard is:  ATA-8-ACS revision 4

Local Time is:    Fri Mar 10 11:29:59 2017 KST

SMART support is: Available - device has SMART capability.

SMART support is: Enabled


=== START OF READ SMART DATA SECTION ===

SMART overall-health self-assessment test result: FAILED!

Drive failure expected in less than 24 hours. SAVE ALL DATA.

See vendor-specific Attribute list for failed Attributes.


General SMART Values:

Offline data collection status:  (0x84) Offline data collection activity

                                        was suspended by an interrupting command from host.

                                        Auto Offline Data Collection: Enabled.

Self-test execution status:      (   0) The previous self-test routine completed

                                        without error or no self-test has ever

                                        been run.

Total time to complete Offline

data collection:                ( 7361) seconds.

Offline data collection

capabilities:                    (0x5b) SMART execute Offline immediate.

                                        Auto Offline data collection on/off support.

                                        Suspend Offline collection upon new

                                        command.

                                        Offline surface scan supported.

                                        Self-test supported.

                                        No Conveyance Self-test supported.

                                        Selective Self-test supported.

SMART capabilities:            (0x0003) Saves SMART data before entering

                                        power-saving mode.

                                        Supports SMART auto save timer.

Error logging capability:        (0x01) Error logging supported.

                                        General Purpose Logging supported.

Short self-test routine

recommended polling time:        (   1) minutes.

Extended self-test routine

recommended polling time:        ( 123) minutes.

SCT capabilities:              (0x003d) SCT Status supported.

                                        SCT Error Recovery Control supported.

                                        SCT Feature Control supported.

                                        SCT Data Table supported.


SMART Attributes Data Structure revision number: 16

Vendor Specific SMART Attributes with Thresholds:

ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE

  1 Raw_Read_Error_Rate     0x000b   002   002   016    Pre-fail  Always   FAILING_NOW 3948150783

  2 Throughput_Performance  0x0005   068   068   054    Pre-fail  Offline      -       2076

  3 Spin_Up_Time            0x0007   100   100   024    Pre-fail  Always       -       205

  4 Start_Stop_Count        0x0012   100   100   000    Old_age   Always       -       7

  5 Reallocated_Sector_Ct   0x0033   001   001   005    Pre-fail  Always   FAILING_NOW 1976

  7 Seek_Error_Rate         0x000b   100   100   067    Pre-fail  Always       -       0

  8 Seek_Time_Performance   0x0005   115   115   020    Pre-fail  Offline      -       34

  9 Power_On_Hours          0x0012   095   095   000    Old_age   Always       -       38464

 10 Spin_Retry_Count        0x0013   100   100   060    Pre-fail  Always       -       0

 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       7

192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       381

193 Load_Cycle_Count        0x0012   100   100   000    Old_age   Always       -       381

194 Temperature_Celsius     0x0002   150   150   000    Old_age   Always       -       40 (Min/Max 20/45)

196 Reallocated_Event_Count 0x0032   001   001   000    Old_age   Always       -       2102

197 Current_Pending_Sector  0x0022   100   100   000    Old_age   Always       -       0

198 Offline_Uncorrectable   0x0008   100   100   000    Old_age   Offline      -       0

199 UDMA_CRC_Error_Count    0x000a   200   200   000    Old_age   Always       -       0


SMART Error Log Version: 1

ATA Error Count: 311 (device log contains only the most recent five errors)

        CR = Command Register [HEX]

        FR = Features Register [HEX]

        SC = Sector Count Register [HEX]

        SN = Sector Number Register [HEX]

        CL = Cylinder Low Register [HEX]

        CH = Cylinder High Register [HEX]

        DH = Device/Head Register [HEX]

        DC = Device Command Register [HEX]

        ER = Error register [HEX]

        ST = Status register [HEX]

Powered_Up_Time is measured from power on, and printed as

DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,

SS=sec, and sss=millisec. It "wraps" after 49.710 days.


Error 311 occurred at disk power-on lifetime: 37261 hours (1552 days + 13 hours)

  When the command that caused the error occurred, the device was active or idle.


  After command completion occurred, registers were:

  ER ST SC SN CL CH DH

  -- -- -- -- -- -- --

  10 51 08 3f 00 00 00  Error: IDNF at LBA = 0x0000003f = 63


  Commands leading to the command that caused the error were:

  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name

  -- -- -- -- -- -- -- --  ----------------  --------------------

  ca 00 08 3f 00 00 e0 08   5d+04:35:46.742  WRITE DMA

  35 00 08 3f 00 44 e0 08   5d+04:35:40.691  WRITE DMA EXT

  35 00 08 3f 00 44 e0 08   5d+04:35:34.756  WRITE DMA EXT

  35 00 08 3f 00 44 e0 08   5d+04:35:34.458  WRITE DMA EXT

  35 00 08 f8 48 80 e0 08   5d+04:35:30.949  WRITE DMA EXT


Error 310 occurred at disk power-on lifetime: 37260 hours (1552 days + 12 hours)

  When the command that caused the error occurred, the device was active or idle.


  After command completion occurred, registers were:

  ER ST SC SN CL CH DH

  -- -- -- -- -- -- --

  10 51 08 47 21 00 00  Error: IDNF at LBA = 0x00002147 = 8519


  Commands leading to the command that caused the error were:

  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name

  -- -- -- -- -- -- -- --  ----------------  --------------------

  ca 00 08 47 21 00 e0 08   5d+02:50:47.175  WRITE DMA

  27 00 00 00 00 00 e0 08   5d+02:50:47.175  READ NATIVE MAX ADDRESS EXT

  ec 00 00 00 00 00 a0 08   5d+02:50:47.172  IDENTIFY DEVICE

  ef 03 42 00 00 00 a0 08   5d+02:50:47.169  SET FEATURES [Set transfer mode]

  27 00 00 00 00 00 e0 08   5d+02:50:47.169  READ NATIVE MAX ADDRESS EXT


Error 309 occurred at disk power-on lifetime: 37260 hours (1552 days + 12 hours)

  When the command that caused the error occurred, the device was active or idle.


  After command completion occurred, registers were:

  ER ST SC SN CL CH DH

  -- -- -- -- -- -- --

  10 51 08 47 21 00 00  Error: IDNF at LBA = 0x00002147 = 8519


  Commands leading to the command that caused the error were:

  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name

  -- -- -- -- -- -- -- --  ----------------  --------------------

  ca 00 08 47 21 00 e0 08   5d+02:50:43.296  WRITE DMA

  35 00 08 a8 6b 45 e0 08   5d+02:50:24.581  WRITE DMA EXT

  35 00 10 98 6b 45 e0 08   5d+02:50:24.557  WRITE DMA EXT

  35 00 08 a7 3b 44 e0 08   5d+02:50:06.715  WRITE DMA EXT

  35 00 10 97 3b 44 e0 08   5d+02:50:03.638  WRITE DMA EXT


Error 308 occurred at disk power-on lifetime: 37236 hours (1551 days + 12 hours)

  When the command that caused the error occurred, the device was active or idle.


  After command completion occurred, registers were:

  ER ST SC SN CL CH DH

  -- -- -- -- -- -- --

  10 51 08 47 21 00 00  Error: IDNF at LBA = 0x00002147 = 8519


  Commands leading to the command that caused the error were:

  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name

  -- -- -- -- -- -- -- --  ----------------  --------------------

  ca 00 08 47 21 00 e0 08   4d+02:56:47.399  WRITE DMA

  27 00 00 00 00 00 e0 08   4d+02:56:47.399  READ NATIVE MAX ADDRESS EXT

  ec 00 00 00 00 00 a0 08   4d+02:56:47.396  IDENTIFY DEVICE

  ef 03 42 00 00 00 a0 08   4d+02:56:47.393  SET FEATURES [Set transfer mode]

  27 00 00 00 00 00 e0 08   4d+02:56:47.393  READ NATIVE MAX ADDRESS EXT


Error 307 occurred at disk power-on lifetime: 37236 hours (1551 days + 12 hours)

  When the command that caused the error occurred, the device was active or idle.


  After command completion occurred, registers were:

  ER ST SC SN CL CH DH

  -- -- -- -- -- -- --

  10 51 08 47 21 00 00  Error: IDNF at LBA = 0x00002147 = 8519


  Commands leading to the command that caused the error were:

  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name

  -- -- -- -- -- -- -- --  ----------------  --------------------

  ca 00 08 47 21 00 e0 08   4d+02:56:43.515  WRITE DMA

  27 00 00 00 00 00 e0 08   4d+02:56:43.515  READ NATIVE MAX ADDRESS EXT

  ec 00 00 00 00 00 a0 08   4d+02:56:43.512  IDENTIFY DEVICE

  ef 03 42 00 00 00 a0 08   4d+02:56:43.509  SET FEATURES [Set transfer mode]

  27 00 00 00 00 00 e0 08   4d+02:56:43.509  READ NATIVE MAX ADDRESS EXT


SMART Self-test log structure revision number 1

No self-tests have been logged.  [To run self-tests, use: smartctl -t]



SMART Selective self-test log data structure revision number 1

 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS

    1        0        0  Not_testing

    2        0        0  Not_testing

    3        0        0  Not_testing

    4        0        0  Not_testing

    5        0        0  Not_testing

Selective self-test flags (0x0):

  After scanning selected spans, do NOT read-scan remainder of disk.

If Selective self-test is pending on power-up, resume after 0 minute delay.



아무래도 하드웨어적인 오류가 있는 듯 합니다.



블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

리눅스 ftp smtp 포트 특정IP 만 허용하기



iptables 로 특정아이피에서만 접근이 가능하게 하는 방법입니다.


ftp smtp mysql 포트를 127.0.0.1(localhost)과 192.168.1.1 만 허용하는 예제입니다.


iptables -I INPUT -p tcp --dport 21 -j DROP

iptables -I INPUT -s 127.0.0.1 -p tcp --dport 21 -j ACCEPT

iptables -I INPUT -s 192.168.1.1 -p tcp --dport 21 -j ACCEPT

iptables -I INPUT -p tcp --dport 25 -j DROP

iptables -I INPUT -s 127.0.0.1 -p tcp --dport 25 -j ACCEPT

iptables -I INPUT -s 192.168.1.1 -p tcp --dport 25 -j ACCEPT

iptables -I INPUT -p tcp --dport 3306 -j DROP

iptables -I INPUT -s 127.0.0.1 -p tcp --dport 3306 -j ACCEPT

iptables -I INPUT -s 192.168.1.1 -p tcp --dport 3306 -j ACCEPT

service iptables save


위와 같이 명령어를 실행하면 됩니다.


확인은 iptables -L 로 확인할 수 있습니다.


# iptables -L

Chain INPUT (policy ACCEPT)

target     prot opt source               destination

ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED

ACCEPT     all  --  anywhere             anywhere

DROP       icmp --  anywhere             anywhere

ACCEPT     tcp  --  192.168.1.1          anywhere            tcp dpt:ftp

ACCEPT     tcp  --  localhost.localdomain  anywhere            tcp dpt:ftp

DROP       tcp  --  anywhere             anywhere            tcp dpt:ftp

ACCEPT     tcp  --  192.168.1.1          anywhere            tcp dpt:smtp

ACCEPT     tcp  --  localhost.localdomain  anywhere            tcp dpt:smtp

DROP       tcp  --  anywhere             anywhere            tcp dpt:smtp

ACCEPT     tcp  --  192.168.1.1          anywhere            tcp dpt:mysql

ACCEPT     tcp  --  localhost.localdomain  anywhere            tcp dpt:mysql

DROP       tcp  --  anywhere             anywhere            tcp dpt:mysql

ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ftp

ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:domain

ACCEPT     udp  --  anywhere             anywhere            state NEW udp dpt:domain

ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:http

ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpts:irdmi:webcache

ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:warehouse


iptables 정책은 위쪽이 우선순위가 높습니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,

MySQL DB TABLE 다른 DATABASE로 빨리 옮기는 방법



데이터가 많은 테이블의 경우 mysqldump 로 덤프를 받아서 다른 database 로 옮기는 작업은 시간이 너무 오래 걸립니다.


동일한 서버에 database 명이 다른 곳에 table 을 손쉽게 옮기고 싶을 때 사용할 수 있습니다.


물론 테이블 복사도 가능하지만 copy 하는 시간 만큼은 시간이 소요가 됩니다.



▶ 테이블 옮기기 ( database1 -> database2 )


# mv /var/lib/mysql/database1/*.frm /var/lib/mysql/database2/

# mv /var/lib/mysql/database1/*.MYD /var/lib/mysql/database2/

# mv /var/lib/mysql/database1/*.MYI /var/lib/mysql/database2/



▶ 테이블 복사하기 ( database1 -> database2 )


# cp /var/lib/mysql/database1/*.frm /var/lib/mysql/database2/

# cp /var/lib/mysql/database1/*.MYD /var/lib/mysql/database2/

# cp /var/lib/mysql/database1/*.MYI /var/lib/mysql/database2/


database2 는 미리 생성이 되어 있어야 합니다.


mysql 을 재시작 할 필요도 없습니다.


블로그 이미지

영은파더♥

가상서버호스팅 VPS 리눅스 서버관리 윈도우 IT

,