tcpdump 로 패킷 이동 확인하기

리눅스/Network|2022. 7. 25. 14:56
반응형

서버 운영중 통신 여부를 확인하기 위해 tcpdump 로 패킷 이동 상황을 보게되는 경우가 있습니다.

이경우 아래와 같은 명령으로 간단히 확인이 가능합니다.

 

* 네트워크 장치명 : eno2 일 경우

 

// 나가는 모든 패킷 확인하기

# tcpdump -i eno2

 

// 특정 포트로 확인하기

# tcpdump -i eno2 tcp port 3306

 

// 소스 IP 로 확인하기

# tcpdump -i eno2 src 192.158.10.2

 

// 목적지 IP 로 확인하기

# tcpdump -i eno2 dst 192.158.10.3

 

// ping 으로 수신, 송신 확인하기

# tcpdump -nni eno2 icmp

# tcpdump -nni eno2 src 192.168.10.2 and icmp

 

 

반응형

댓글()

[MySQL 에러] ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails 해결

리눅스/MySQL|2022. 6. 30. 10:10
반응형

레코드를 삭제할때 아래와 같은 에러 메세지가 출력되었다면

 

mysql> delete from log where idx='161';
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`baudit`.`checklist`, CONSTRAINT `fk_checklist_log1` FOREIGN KEY (`log_idx`) REFERENCES `log` (`idx`))

 

다른 곳 (checklist 테이블의 log_idx 컬럼) 에서 현재 삭제하려는 데이터 (log 테이블의 idx 컬럼) 를 참조하고 있다는 메세지 입니다.

해결 방법으로는 아래 두가지가 있습니다.

 

1. 관련 데이터 삭제

 

순차적으로 checklist 테이블에서 관련 레코드 삭제 후 log 테이블에서 해당 레코드 삭제

 

2. 참조 무시하고 삭제

 

mysql> SET foreign_key_checks = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from log where idx='161';
Query OK, 1 row affected (0.02 sec)

mysql> SET foreign_key_checks = 1;
Query OK, 0 rows affected (0.00 sec)

 

 

반응형

댓글()

CentOS 7 에서 MySQL 8.0.29 설치 (gcc 관련 에러시에만 참고)

리눅스/MySQL|2022. 6. 20. 11:28
반응형

1. 필요 패키지 설치
# yum -y group install "Development Tools"
# yum -y install openssl openssl-devel ncurses ncurses-base ncurses-libs ncurses-devel perl bison


2. gcc 설치 (gcc 4.8.5 -> 7.3.0)
# yum -y install centos-release-scl
# yum -y install devtoolset-7-gcc*
# scl enable devtoolset-7 bash
# gcc --version

 

* 어떤 경우 gcc 8.3 우선 설치하고 scl.... 명령으로 7.3 으로 다운하여 사용하니 되기도 함

 

* 위와 같이 설치가 되지 않을 경우 아래와 같이 리포지토리 파일을 수동으로 생성합니다.

# vi /etc/yum.repos.d/CentOS-SCLo-scl-rh.repo

# CentOS-SCLo-rh.repo
#
# Please see http://wiki.centos.org/SpecialInterestGroup/SCLo for more
# information

[centos-sclo-rh]
name=CentOS-7 - SCLo rh
#baseurl=http://mirror.centos.org/centos/7/sclo/$basearch/rh/
mirrorlist=http://mirrorlist.centos.org?arch=$basearch&release=7&repo=sclo-rh
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-testing]
name=CentOS-7 - SCLo rh Testing
baseurl=http://buildlogs.centos.org/centos/7/sclo/$basearch/rh/
gpgcheck=0
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-source]
name=CentOS-7 - SCLo rh Sources
baseurl=http://vault.centos.org/centos/7/sclo/Source/rh/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-debuginfo]
name=CentOS-7 - SCLo rh Debuginfo
baseurl=http://debuginfo.centos.org/centos/7/sclo/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

 

# vi /etc/yum.repos.d/CentOS-SCLo-scl.repo

# CentOS-SCLo-sclo.repo
#
# Please see http://wiki.centos.org/SpecialInterestGroup/SCLo for more
# information

[centos-sclo-sclo]
name=CentOS-7 - SCLo sclo
# baseurl=http://mirror.centos.org/centos/7/sclo/$basearch/sclo/
mirrorlist=http://mirrorlist.centos.org?arch=$basearch&release=7&repo=sclo-sclo
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-testing]
name=CentOS-7 - SCLo sclo Testing
baseurl=http://buildlogs.centos.org/centos/7/sclo/$basearch/sclo/
gpgcheck=0
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-source]
name=CentOS-7 - SCLo sclo Sources
baseurl=http://vault.centos.org/centos/7/sclo/Source/sclo/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-debuginfo]
name=CentOS-7 - SCLo sclo Debuginfo
baseurl=http://debuginfo.centos.org/centos/7/sclo/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

 

yum update 로 적용하고 다시 위로 올라가 재설치를 합니다.

 

[필수] MySQL 8.0.29 설치에 필요한 패키지를 추가 설치합니다.

# yum -y install devtoolset-11-gcc devtoolset-11-gcc-c++ devtoolset-11-binutils

 

 

3. cmake 설치
# cd /usr/local/src
# wget https://github.com/Kitware/CMake/releases/download/v3.16.2/cmake-3.16.2.tar.gz
# tar -zxvf cmake-3.16.2.tar.gz
# cd cmake-3.16.2
# ./bootstrap
# gmake
# make install
# cmake --version


4. mysql 설치

 

MySQL 8.0.29 는 설치도중 boost_1_77_0 을 다운로드 받아 압축 풀고 진행하는데,

내부 네트워크에서 인터넷 연결 안될 경우 수동으로 파일을 받아서 옮긴 뒤 아래와 같이 진행하면 됩니다.

 

(# wget https://boostorg.jfrog.io/artifactory/main/release/1.77.0/source/boost_1_77_0.tar.bz2 ) 다운로드경로
# bunzip2 boost_1_77_0.tar.bz2
# tar xvf boost_1_77_0.tar
# mv boost_1_77_0 /usr/local/src/mysql-8.0.29/include/boost_1_77_0/

 

(생략)


cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/local/mysql/data -DENABLED_LOCAL_INFILE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DMYSQL_UNIX_ADDR=/tmp/mysql.sock -DSYSCONFDIR=/etc -DDEFAULT_CHARSET=utf8 -DWITH_SSL=system -DMYSQL_TCP_PORT=3306 -DWITH_EXTRA_CHARSETS=all -DDEFAULT_COLLATION=utf8_general_ci -DDOWNLOAD_BOOST=1 -DWITH_BOOST=/usr/local/src/mysql-8.0.29/include/boost_1_77_0 -DFORCE_INSOURCE_BUILD=1


(생략)

 

 

반응형

댓글()

GCC 원하는 버전으로 업그레이드 하기 (CentOS 7, GCC 10.3.0)

리눅스/OS 일반|2022. 6. 17. 08:12
반응형

1. 현재 버전 확인
# gcc --version


2. 업그레이드
GCC 는 아래 공식 사이트에서 원하는 버전을 다운로드 받을 수 있습니다.

https://gcc.gnu.org/releases.html

# wget https://ftp.kaist.ac.kr/gnu/gcc/gcc-10.3.0/gcc-10.3.0.tar.gz
# tar xvzf gcc-11.3.0.tar.gz
# cd gcc-11.3.0
# ./configure --disable-multilib --enable-languages=c,c++
# make
# make install


3. 변경된 버전 확인
# gcc --version

 

반응형

댓글()

CentOS 7 에서 MySQL client 8.0.21 설치하기 (caching_sha2_password 지원)

리눅스/MySQL|2022. 6. 9. 16:30
반응형

caching_sha2_password 지원이 되는 MySQL client 8 버전을 설치합니다.

 

1. 다운로드

# wget https://repo.mysql.com/yum/mysql-8.0-community/el/7/x86_64/mysql-community-client-8.0.21-1.el7.x86_64.rpm
# wget https://repo.mysql.com/yum/mysql-8.0-community/el/7/x86_64/mysql-community-common-8.0.21-1.el7.x86_64.rpm
# wget https://repo.mysql.com/yum/mysql-8.0-community/el/7/x86_64/mysql-community-libs-8.0.21-1.el7.x86_64.rpm

 

2. 설치

의존성이 걸려 있으므로 아래 순서에 맞게 설치 합니다.

# rpm -ivh mysql-community-common-8.0.21-1.el7.x86_64.rpm 
# rpm -ivh mysql-community-libs-8.0.21-1.el7.x86_64.rpm 
# rpm -ivh mysql-community-client-8.0.21-1.el7.x86_64.rpm

 

이제 mysql 명령으로 외부 DB 서버에 접근이 가능합니다.

반응형

댓글()

MySQL 실시간 쿼리 확인

리눅스/MySQL|2022. 5. 25. 08:58
반응형

mysqladmin 명령어로 상태를 출력

 

# mysqladmin -i5 proc status -u root -p

Enter password:

~~

Uptime: 10578 Threads: 1 Questions: 4809 Slow queries: 589 Opens: 1321 Flush tables: 1 Open tables: 348 Queries per second avg: 0.454

 

 

Uptime : MySQL server 시삭된 후 현재 시간 (초 단위)

Threads : 현제 DB 서버에 연결된 유저수

Questions : 서버 시작후 지금까지 요청된 쿼리수

Slow queries : mysql 설정파일에 슬로우쿼리의 쿼리시간 이상을 가진 요청수

Opens : 서버가 시작된 후 현재까지 열렸던 테이블수

Open tables : 현재 열려 잇는 테이블 수

Queries per second avg : 평균 초단 쿼리수

 

 

[출처] https://jy-p.tistory.com/50

 

반응형

댓글()

Rocky Linux 8.5 에서 Let's Encrypt SSL 발급 및 Lighttpd 적용하기

리눅스/APACHE|2022. 5. 24. 15:09
반응형

Lighttpd 가 설치 되었다는 가정 하에 진행합니다.

 

1. Let's Encrypt 설치

# yum -y install certbot

 

 

2. SSL 인증서 발급
# certbot certonly --webroot -w /var/www/lighttpd -d sysdocu.tistory.com

 

그리고 lighttpd 에서 사용하기 위해 cert.pem 파일과 privkey.pem 파일을 하나의 파일로 합칩니다.

# cat /etc/letsencrypt/live/sysdocu.tistory.com/cert.pem /etc/letsencrypt/live/sysdocu.tistory.com/privkey.pem > /etc/letsencrypt/live/sysdocu.tistory.com/hap.pem

 

 

3. Lighttpd 설정 및 적용

# vi /etc/lighttpd/lighttpd.conf 

$SERVER["socket"] == ":443" {
    ssl.engine = "enable"
    ssl.pemfile = "/etc/letsencrypt/live/sysdocu.tistory.com/hap.pem"           # Combined Certificate & Private Key
    ssl.ca-file = "/etc/letsencrypt/live/sysdocu.tistory.com/chain.pem"           # Root CA
    server.name = "sysdocu.tistory.com"                                                            # Domain Name
    server.document-root = "/var/www/lighttpd"                                               # Document Root Directory
    server.errorlog = "/var/log/lighttpd/sysdocu.tistory.com_error.log"           # Lighttpd error log
    accesslog.filename = "/var/log/lighttpd/sysdocu.tistory.com_access.log"  # Lighttpd access log
}

# systemctl restart lighttpd

 

https:// 가 아닌 http:// 로 접근하는 사용자를 https 로 redirect 하는 방법입니다.

 

# vi /etc/lighttpd/lighttpd.conf

$HTTP["scheme"] == "http" {
    $HTTP["host"] == "sysdocu.tistory.com" {
        url.redirect = ("/.*" => "https://sysdocu.tistory.com$0")
    }
}

# systemctl restart lighttpd

반응형

댓글()

Rocky Linux 8.5 에서 Lighttpd + PHP + MariaDB 설치하기

리눅스/APACHE|2022. 5. 24. 13:41
반응형

1. 패키지 저장소 추가 및 최신화

# yum -y install epel-release
# yum -y update

 

 

2. Lighttpd 설치

# yum install lighttpd
# systemctl start lighttpd
# systemctl enable lighttpd

 

 

3. MariaDB 설치

# yum -y install mariadb mariadb-server
# systemctl start mariadb
# systemctl enable mariadb
# mysql_secure_installation

(모든 선택은 'Y' 로 하고 root 패스워드만 수동 입력)

 

 

4. PHP 설치

# yum -y install php php-mysqlnd php-pdo php-gd php-mbstring php-fpm lighttpd-fastcgi

# systemctl start php-fpm

# systemctl enable php-fpm

 

 

5. 설정 및 적용

# vi /etc/php-fpm.d/www.conf

user = lighttpd
group = lighttpd
listen = 127.0.0.1:9000

# vi /etc/php.ini

cgi.fix_pathinfo=1

# vi /etc/lighttpd/modules.conf

include "conf.d/fastcgi.conf"

# vi /etc/lighttpd/conf.d/fastcgi.conf

fastcgi.server += ( ".php" =>
        ((
                "host" => "127.0.0.1",
                "port" => "9000",
                "broken-scriptfilename" => "enable"
        ))
)

 

# systemctl restart php-fpm

# systemctl restart lighttpd

 

 

6. 확인

지금까지 설치했던 데몬의 상태는 아래와 같이 확인이 가능합니다.

# systemctl status lighttpd

# systemctl status php-fpm

# systemctl status mariadb

 

이제 php 소스가 정상 출력 되는지 브라우저를 통해 확인해봅니다.

http://sysdocu.tistory.com/phpinfo.php

 

 

* php 페이지 접근이 안될 경우 확인 사항

1) 내부 방화벽 (firewall, ufw, iptables, tcp wrapper 등 80번 포트 접근 허용)

2) selinux 설정 (setenforce 0 으로 해제 또는 /etc/selinux/config 수정)

 

 

반응형

댓글()

[MySQL] Slave_IO_Running: Connecting 조치 방법

리눅스/MySQL|2022. 5. 11. 11:47
반응형

Replication 을 구성하다보면 동기화가 되지 않은 상태에서 아래와 같은 메세지를 만날 수 있습니다.

 

(slave 서버에서)

mysql> show slave status\G

...

Slave_IO_Running: Connecting

Slave_SQL_Running: Yes

...

 

[점검1]

이 경우 slave 서버에서 master 서버로 접근 되는지 확인해 봐야 합니다.

 

(slave 서버에서)

# mysql -u replica -p -h 192.168.10.2

Enter password: 
ERROR 1129 (HY000): Host '192.168.10.2' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'

 

위와 같이 출력 된 경우 조치 방법은 아래와 같습니다.

 

(master 서버에서)

mysql> flush hosts;

 

이후 다시 동기화를 하면 정상 구동되는것을 확인 할 수 있습니다.

 

[점검2]

서버 방화벽 등에서 slave 서버가 master 서버의 mysql 로 접근이 될 수 있도록 허용 합니다.

- 방화벽 (ufw, iptables 등)

- tcp wrapper (/etc/hosts.allow)

- mysql 리플리케이션 계정 접근 권한 (mysql.user 테이블 확인)

 

[점검3]

간혹 인터넷 예제를 따라 리플리케이션 설정을 했을때 slave 서버의 쿼리에서 아래 값을 안바꾸고 복사해서 실행한 경우가 있습니다.

확인해보세요.

mysql> change master to master_host='192.168.10.2', master_user='repl',master_password='12345678', master_log_file='binlog.000004',master_log_pos=156; 

 

 

반응형

댓글()

Zabbix API 예제

리눅스/OS 일반|2022. 4. 22. 15:59
반응형

[ PHP 코드 ]

아래 샘플 코드를 이용해 토큰을 출력해 봅니다.

<?php
$curl = curl_init() ;

curl_setopt ( $curl , CURLOPT_URL , 'http://sysdocu.tistory.com/api_jsonrpc.php' ) ;
curl_setopt ( $curl , CURLOPT_TIMEOUT , 10 ) ;
curl_setopt ( $curl , CURLOPT_POST , 1 ) ;
curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , 1 ) ;
curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , FALSE ) ;
curl_setopt ( $curl , CURLOPT_HTTPHEADER , array ( 'Content-Type: application/json'  ) ) ;
curl_setopt ( $curl , CURLOPT_POSTFIELDS , '{"jsonrpc":"2.0" , "method":"user.login" , "params":{"user":"Admin", "password":"12345678"} , "auth":null, "id":1}' ) ;

$result = curl_exec ( $curl ) ;
$err = curl_error ( $curl ) ;

curl_close ( $curl ) ;

if ( $err )
  echo 'Error :' . $err ;
else
  echo $result;


$data = json_decode($result, true);
$token = $data['result'];
echo $token
?>


[ BASH 코드 ]

#!/bin/bash

TOKEN=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "12345678" }, "id":1 }' 'http://sysdocu.tistory.com/api_jsonrpc.php' |sed -e "s/.*\"result\":\"//;s/\".*//"`

echo -e "TOKEN : $TOKEN\n"

 

[ API 종류 ]

더 자세한 API 종류 및 설명은 zabbix 공식 사이트를 참고해주세요.

아래는 curl 명령을 기준으로 작성하였습니다.

PHP 코드는 아래 코드와 맨 위 PHP 예제 파일을 참고해서 작성하면 됩니다.


1) 토큰 생성
Admin 계정으로 토큰을 생성해야 생성된 토큰으로 계정 추가, 삭제가 가능합니다.

(명령)
curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0", 
"method": "user.login", 
"params": { 
    "user": "Admin", 
"password": "12345678" 
}, 
"id":1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php'

 


(결과)
{
    "jsonrpc":"2.0",
"result":"c436f84f928956be8db12704db759376",
"id":1
}


2) 계정 생성
'${TOKEN}' 부분에 위에서 생성한 토큰이 들어갑니다.
usrgrpid 값 16은 임의로 만든 값입니다.

(명령)
curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "user.create",
    "params": {
        "alias": "CDH",
        "passwd": "1234",
        "roleid": "1",
        "usrgrps": [
            {
                "usrgrpid": "16"
            }
        ],
        "medias": [
            {
                "mediatypeid": "16",
                "sendto": [
                    "123456789"
                ],
                "active": 0,
                "severity": 63,
                "period": "1-7,00:00-24:00"
            }
        ]
    },
    "auth": "'${TOKEN}'",
    "id": 2
}' 'http://sysdocu.tistory.com/api_jsonrpc.php'

(결과)
{
  "jsonrpc": "2.0",
  "result": {
    "userids": [
      "20"
    ]
  },
  "id": 2
}


3) 계정 삭제
생성시 부여되었던 userids 값을 사용합니다.

(명령)
curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "user.delete",
    "params": [
        "20"
    ],
        "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php'

(결과)
{
  "jsonrpc": "2.0",
  "result": {
    "userids": [
      "20"
    ]
  },
  "id": 1
}


4) 유저 리스트
(명령)
curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "user.get",
    "params": {
        "output": "extend"
    },
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php'


5) 그룹 리스트
(명령)
curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "usergroup.get",
    "params": {
        "output": "extend",
        "status": 0
    },
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php'

 

아래는 쉘스크립트 코드 입니다. curl 형식은 동일합니다.


# 호스트 그룹 추가
HOSTGROUP_ADD=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "hostgroup.create",
    "params": {
        "name": "sysdocu"
    },
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php' | jq '.'`
echo -e "호스트 그룹 생성 결과\n${HOSTGROUP_ADD}"


# 호스트 그룹 리스트 출력
HOSTGROUP_GET=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "hostgroup.get",
    "params": {
        "output": "extend"
    },
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php' | jq '.'`
echo -e "호스트 그룹 리스트 출력 결과\n${HOSTGROUP_GET}"


# 유저 그룹 추가
GROUP_ADD=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "usergroup.create",
    "params": {
        "name": "sysdocu",
        "rights": {
            "id": "37",       // 호스트 그룹 id
            "permission": 3   // 권한 (RW)
        }
    },
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php' | jq '.'`
echo -e "그룹 생성 결과\n${GROUP_ADD}"


# 유저 그룹 삭제
GROUP_DEL=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "usergroup.delete",
    "params": [ "18" ],
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php' | jq '.'`
echo -e "그룹 삭제 결과\n${GROUP_DEL}"


# 호스트 그룹 삭제
HOSTGROUP_DEL=`curl -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "hostgroup.delete",
    "params": [ "32" ],
    "auth": "'${TOKEN}'",
    "id": 1
}' 'http://sysdocu.tistory.com/api_jsonrpc.php' | jq '.'`
echo -e "호스트 그룹 삭제 결과\n${HOSTGROUP_DEL}"


* 참고

roleid
1 : User role
2 : Admin role
3 : Super role
4 : Guest role

mediatypeid
1 : email
2 : x
3 : sms
4 : email
5 : Mattermost
6 : Opsgenie  
7 : PagerDuty
8 : Pushover
9 : Slack
10 : discord
11 : SIGNL4
12 : Jira
13 : Jira with CustomFields  
14 : MS Teams  
15 : Redmine
16 : Telegram

반응형

댓글()

[PHP] 여러개의 파일 읽기 (fopen multiple files in php)

리눅스/OS 일반|2022. 4. 19. 10:56
반응형

1. 특정 파일을 지정해서 읽을 경우 (array 배열에 파일명을 넣어줍니다)

<?PHP
$filenames = array("../logs/detect.log.1", "../logs/detect.log");
foreach ($filenames as $file) {
    $file_handle = fopen($file, "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        echo $line;
    }
    fclose($file_handle);
}
?>

[출처] https://stackoverflow.com/questions/47992424/using-php-how-to-read-multiple-text-files-and-display-the-file-name

 

존재하는 파일만 읽고 싶은 경우, 파일이 있을때만 array 에 넣는 방법으로 해도 됩니다.

<?php
$filenames = array();

if (file_exists("../logs/detect.log.1")) {
    array_push($filenames, "../logs/detect.log.1");
}

if (file_exists("../logs/detect.log")) {
    array_push($filenames, "../logs/detect.log");
}

if (count($filenames) != "0") {  // 존재하는 파일이 한개라도 있을경우
    foreach ($filenames as $file) {
        $file_handle = fopen($file, "r");
        while (!feof($file_handle)) {
            $line = fgets($file_handle);
            echo $line;
        }
        fclose($file_handle);
    }
}
?>

 

2. 다수의 파일을 읽을 경우 ( * 과 같은 와일드 카드 문자를 이용합니다.)

<?php
foreach (glob("../logs/detect.log*") as $file) {
    $file_handle = fopen($file, "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        echo $line;
    }
    fclose($file_handle);
}
?>

[출처] https://stackoverflow.com/questions/18558445/read-multiple-files-with-php-from-directory

 

반응형

댓글()