반응형

 


 

작성일: 2023년 10월 10일

 

패킷 보내기 (Send a packet)

예제 코드

/**
 * How to build
 *  $  gcc send-raw-packet.c -o send-raw-packet
 *
 * How to run
 *  $ ./send-raw-packet
 *    or
 *  $ ./send-raw-packet  eth0
 */

#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <linux/ip.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <errno.h>


// FIXME: MY_DEST_MACX 값은 각자 테스트 환경이 맞게 수정해서 사용.
#define MY_DEST_MAC0	0x52
#define MY_DEST_MAC1	0x54
#define MY_DEST_MAC2	0x00
#define MY_DEST_MAC3	0xcf
#define MY_DEST_MAC4	0xab
#define MY_DEST_MAC5	0x76

// FIXME: DEFAULT_IF 값은 각자 테스트 환경이 맞게 수정해서 사용.
#define DEFAULT_IF	"enp7s0"

#define BUF_SIZ		1024


int main(int argc, char *argv[])
{
	int                  sockfd;
	int                  tx_len = 0;
	char                 sendbuf[BUF_SIZ];
	char                 ifName[IFNAMSIZ];
	struct ifreq         if_idx;
	struct ifreq         if_mac;
	struct ether_header  *eh = (struct ether_header *) sendbuf;
	struct iphdr         *iph = (struct iphdr *) (sendbuf + sizeof(struct ether_header));
	struct sockaddr_ll   socket_address;

	// Network interface name 지정하기 (예: eth0)
	if (argc > 1)
	{
		strcpy(ifName, argv[1]);
	}
	else
	{
		strcpy(ifName, DEFAULT_IF);
	}

	// RAW socket 사용을 위한 File descriptor 생성하기
	if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1)
	{
		printf("socket() error: %d (%s)\n", errno, strerror(errno));
		return 0;
	}

	// Network interface의 index 값 구하기
	memset(&if_idx, 0, sizeof(struct ifreq));
	strncpy(if_idx.ifr_name, ifName, IFNAMSIZ-1);
	if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0)
	{
		printf("ioctl(SIOCGIFINDEX, %s) error: %d (%s)\n", ifName, errno, strerror(errno));
		return 0;
	}

	// Network interface의 MAC address 구하기
	memset(&if_mac, 0, sizeof(struct ifreq));
	strncpy(if_mac.ifr_name, ifName, IFNAMSIZ-1);
	if (ioctl(sockfd, SIOCGIFHWADDR, &if_mac) < 0)
	{
		printf("ioctl(SIOCGIFHWADDR, %s) error: %d (%s)\n", ifName, errno, strerror(errno));
		return 0;
	}

	// Ehternet header 구성하기 (참고: sendbuf pointer가 eh 주소를 pointing)
	memset(sendbuf, 0, BUF_SIZ);
	/*
	 * ioctl() 함수를 이용해서 얻은 'enp7s0' NIC에 대한 MAC Address 값을
	 * ethernet header 구조체의 ether_shost 변수에 복사한다.
	 */
	printf("( %s )  MAC address = ", ifName);
	for (int idx = 0; idx < 6; idx++)
	{
		eh->ether_shost[idx] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[idx];
		printf("%02x", eh->ether_shost[idx]);
		if (idx < 5)
		{
			printf(":");
		}
	}
	printf("\n");

	/*
	 * 일반적으로 NIC port의 MAC address를 ethernet frame의 source address로 사용하지만
	 * Ethernet packet 전송 테스트를 위해서 가짜 Source MAC address를 만들었다.
	 */
	eh->ether_shost[3] = 0x01;
	eh->ether_shost[4] = 0x02;
	eh->ether_shost[5] = 0x03;

	// Ethernet frame - Destination host MAC address
	eh->ether_dhost[0] = MY_DEST_MAC0;
	eh->ether_dhost[1] = MY_DEST_MAC1;
	eh->ether_dhost[2] = MY_DEST_MAC2;
	eh->ether_dhost[3] = MY_DEST_MAC3;
	eh->ether_dhost[4] = MY_DEST_MAC4;
	eh->ether_dhost[5] = MY_DEST_MAC5;

	// Ethertype:  Internet Protocol (0x0800)
	eh->ether_type = htons(ETH_P_IP);
	tx_len += sizeof(struct ether_header);

	// FIXME: IP Header
	//   각자 테스트 환경에 맞게 iph 변수를 수정하여 사용하기
  	iph->ihl = 20 >> 2;  // NOTE: (20 >> 2) * 4 = 20 bytes (IHL은 4 byte 단위로 해석되기 때문)
	iph->version = 4;
	iph->protocol = IPPROTO_IP;
	iph->saddr = inet_addr("10.1.1.10");
	iph->daddr = inet_addr("10.1.1.11");
	iph->tot_len = 46 + 32;

	tx_len += sizeof(struct iphdr);

	/* Payload (Packet data) */
	for (char idx = 0; idx < 32; idx++)
	{
		sendbuf[tx_len++] = idx;
	}

	/* Index of the network device */
	socket_address.sll_ifindex = if_idx.ifr_ifindex;
	/* Address length*/
	socket_address.sll_halen = ETH_ALEN;
	/* Destination MAC */
	socket_address.sll_addr[0] = MY_DEST_MAC0;
	socket_address.sll_addr[1] = MY_DEST_MAC1;
	socket_address.sll_addr[2] = MY_DEST_MAC2;
	socket_address.sll_addr[3] = MY_DEST_MAC3;
	socket_address.sll_addr[4] = MY_DEST_MAC4;
	socket_address.sll_addr[5] = MY_DEST_MAC5;

	/* Send packet */
	if (sendto(sockfd, sendbuf, tx_len, 0, (struct sockaddr*)&socket_address, sizeof(struct sockaddr_ll)) < 0)
	    printf("Send failed\n");

	return 0;
}

 

 

패킷 받기 (Receive a packet)

예제 코드

/**
 * How to build
 *  $  gcc recv-raw-packet.c -o recv-raw-packet
 *
 * How to run
 *  $ ./recv-raw-packet
 *    or
 *  $ ./recv-raw-packet  eth0
 */

#include <unistd.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <errno.h>

#define ETHER_TYPE	0x0800

#define DEFAULT_IF	"enp7s0"
#define BUF_SIZ		1024

int main(int argc, char *argv[])
{
	char sender[INET6_ADDRSTRLEN];
	int sockfd, ret;
	int sockopt;
	ssize_t pktbytes;
	struct ifreq ifopts;	// To set promiscuous mode
	struct ifreq if_ip;	    // To get IP address of this host NIC
	struct sockaddr_storage peer_addr;
	uint8_t buf[BUF_SIZ];
	char ifName[IFNAMSIZ];

	// Network interface name 지정하기 (예: eth0)
	if (argc > 1)
	{
		strcpy(ifName, argv[1]);
	}
	else
	{
		strcpy(ifName, DEFAULT_IF);
	}

	// Ethernet + IP + UDP header
	struct ether_header *eh = (struct ether_header *) buf;
	struct iphdr *iph = (struct iphdr *) (buf + sizeof(struct ether_header));
	struct udphdr *udph = (struct udphdr *) (buf + sizeof(struct iphdr) + sizeof(struct ether_header));

	if ((sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETHER_TYPE))) == -1)
	{
		printf("socket(PF_PACKET, SOCK_RAW, ETHER_TYPE) error: %d (%s)\n", errno, strerror(errno));
		return -1;
	}

	// Set interface to promiscuous mode
	strncpy(ifopts.ifr_name, ifName, IFNAMSIZ-1);
	ioctl(sockfd, SIOCGIFFLAGS, &ifopts);
	ifopts.ifr_flags |= IFF_PROMISC;
	ioctl(sockfd, SIOCSIFFLAGS, &ifopts);
	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof sockopt) == -1) {
		printf("setsockopt(SO_REUSEADDR) error: %d (%s)\n", errno, strerror(errno));
		close(sockfd);
		exit(0);
	}

	// Bind to device
	if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, ifName, IFNAMSIZ-1) == -1)	{
		printf("setsockopt(SO_BINDTODEVICE, %s) error: %d (%s)\n", ifName, errno, strerror(errno));
		close(sockfd);
		exit(0);
	}

repeat:
	printf("\nWaiting to recvfrom...\n");
	pktbytes = recvfrom(sockfd, buf, BUF_SIZ, 0, NULL, NULL);
	printf("  Got packet %lu bytes\n", pktbytes);

	printf("Destination  MAC address = ");
	for (int idx = 0; idx < 6; idx++)
	{
		printf("%02x", eh->ether_dhost[idx]);
		if (idx < 5)
		{
			printf(":");
		}
	}
	printf("\n");

	// Get source IP
	((struct sockaddr_in *)&peer_addr)->sin_addr.s_addr = iph->saddr;
	inet_ntop(AF_INET, &((struct sockaddr_in*)&peer_addr)->sin_addr, sender, sizeof sender);

	// Look up my device IP addr
	memset(&if_ip, 0, sizeof(struct ifreq));
	strncpy(if_ip.ifr_name, ifName, IFNAMSIZ-1);
	if (ioctl(sockfd, SIOCGIFADDR, &if_ip) >= 0) {
		printf("Source IP: %s\n My IP: %s\n", sender,
				inet_ntoa(((struct sockaddr_in *)&if_ip.ifr_addr)->sin_addr));
		// Ignore if I sent it
		if (strcmp(sender, inet_ntoa(((struct sockaddr_in *)&if_ip.ifr_addr)->sin_addr)) == 0)	{
			printf("but I sent it :(\n");
			ret = -1;
			goto done;
		}
	}

	/* UDP payload length */
	ret = ntohs(udph->len) - sizeof(struct udphdr);

	/* Print packet */
	printf("\tData:");
	for (int idx = 0; idx < pktbytes; idx++)
	{
		printf("%02x ", buf[idx]);
	}
	printf("\n");

done:
	goto repeat;

	close(sockfd);
	return ret;
}

 

 

 

 

 


 

반응형

작성일: 2023년 9월 20일

 

 

 

Client 장비에 network port가 여러개 있는 경우, 특정 network port를 지정하여 IP 패킷을 전송하고 싶을 때가 있다.

이럴 때, source IP address를 binding하면 특정 network port를 통해 IP 패킷이 전송된다.

참고:
  일반적으로 Target IP address로 가기 위한 routing path 및 network port는 
  OS에 있는 Routing table을 통해서 자동으로 결정된다.
  그러나 Target IP address로 가기 위한 routing path가 1개가 아닌 2개 이상인 경우에는
  어느 network port를 통해서 IP 패킷이 나갈지 예측하기 어렵다.  
package main

import (
    "fmt"
    "io/ioutil"
    "net"
    "net/http"
    "time"
)


func main() {
##
## NOTE:  14.33.80.179를 Source IP address로 지정한다. (즉, Source IP address binding)
##
    localAddr, err := net.ResolveIPAddr("ip", "14.33.80.179")
    if err != nil {
        panic(err)
    }

    localTCPAddr := net.TCPAddr{
        IP: localAddr.IP,
    }

    d := net.Dialer{
        LocalAddr: &localTCPAddr,
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
    }

    tr := &http.Transport{
        Proxy:               http.ProxyFromEnvironment,
        Dial:                d.Dial,
        TLSHandshakeTimeout: 10 * time.Second,
    }

    webclient := &http.Client{Transport: tr}

    // Use NewRequest so we can change the UserAgent string in the header
    req, err := http.NewRequest("GET", "https://www.naver.com", nil)
    if err != nil {
        panic(err)
    }

    res, err := webclient.Do(req)
    if err != nil {
        panic(err)
    }

    fmt.Println("DEBUG", res)
    defer res.Body.Close()

    content, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s", string(content))
}

 

 

 

 


 

반응형
테스트 및 블로그 작성한 날짜: 2023년 6월 13일

 

Prometheus 설치

아래 Web page에서 내 운영 환경에 맞는 파일을 다운로드한다.

https://prometheus.io/download/

 

아래와 같이 명령을 따라 수행하여 Prometheus 서버를 구동한다.

##
## Prometheus 서버 설치 파일을 다운로드
## 

$ wget https://github.com/prometheus/prometheus/releases/download/v2.45.0-rc.0/prometheus-2.45.0-rc.0.linux-amd64.tar.gz

##
## 압축 풀기
##

$ tar xf prometheus-2.45.0-rc.0.linux-amd64.tar.gz

$ cd prometheus-2.45.0-rc.0.linux-amd64

##
## 설정 파일 수정하기
##

$ cat prometheus.yml

# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    # 나는 아래 부분을 수정했다.
    # 10.1.4.56:8080은 Python으로 작성한 Exporter의 접속점이다.
    static_configs:
      - targets: ["10.1.4.56:8000", "10.1.3.241:9090"]
      
##
## Prometheus 서버 구동하기
##

$ ./prometheus --config.file="./prometheus.yml" &
... 중간 생략 ...
ts=2023-06-13T08:24:54.837Z caller=main.go:1004 level=info msg="Server is ready to receive web requests."
ts=2023-06-13T08:24:54.837Z caller=manager.go:995 level=info component="rule manager" msg="Starting rule manager..."

 

Prometheus Client 예제 작성

테스트용 Metric data를 만들기 위해서 아래와 같이 Example code를 작성한다.

from prometheus_client import start_http_server, Summary
from prometheus_client import Counter
import random
import time


# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')

# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
    """A dummy function that takes some time."""
    time.sleep(t)


if __name__ == '__main__':
    # Start up the server to expose the metrics.
    start_http_server(8000)

    c = Counter('sejong_packet_bytes', 'http request failure', ['src_ip', 'dst_ip', 'src_port', 'dst_port'])
    # Generate some requests.
    while True:
        process_request(random.random()/10)
        c.labels(src_ip='10.1.4.11', dst_ip='192.168.5.22', src_port='11111', dst_port='').inc(1322)
        c.labels(src_ip='10.1.8.33', dst_ip='192.168.9.66', src_port='12345', dst_port='23456').inc(1500)
        c.labels(src_ip='172.16.8.33', dst_ip='192.168.9.66', src_port='12345', dst_port='23456').inc(1500)
        c.labels(src_ip='172.17.7.33', dst_ip='192.168.33.66', src_port='80808', dst_port='90909').inc(1500)

 

위에서 작성한 example code를 실행한다.

$ pip install prometheus-client

$ python3 my_example.py

 

좀 더 다양한 Python example code를 보려면, GitHub 저장소를 볼 것!

https://github.com/prometheus/client_python

 

Web UI에서 Metric 확인

Query 입력하는 공간에 "increase(sejong_packet_bytes_total[30s])" 를 입력한다.

 

 

블로그 작성자: sejong.jeonjo@gmail.com

 

반응형

 


 

작성일: 2024년 2월 21일

 

Shell script 작성할 때마다 책꽂이 어딘가에 있을 책을 찾는 것이 귀찮고, 인터넷에서 검색하는 것도 귀찮아서, 
내가 자주 사용하는 Shell script use case를 정리하는 것이 편하겠다는 생각이 들었다.

 

 

Bash Shell Programming 추천 문서

추천 문서 1

  • Link: https://www.lesstif.com/lpt/bash-shell-script-programming-26083916.html
  • 이 문서가 다루는 내용
    • For loop
    • Script parameter, argument ($0, $1, ... $n, $@)   // CLI를 통해서 받은 argument를 처리하는 방법
    • getopt
    • compare operator (비교 연산자, if then fi, else, elif, ... )
    • File test (디렉토리 존재 여부, 파일 존재 여부, 실행 파일 여부 등 검사)
    • String test (문자열이 공백인지 검사,  Regular expression 정규식)
    • File 읽기 (Text file을 line by line으로 읽어서 변수에 담기)
    • nohup + stdin/out redirect (스크립트를 background로 실행시켜 terminal이 끊길 때 스크립트가 종료되는 것을 방지)
    • EUID 활용법 (일반 계정, root 계정으로 실행했는지 테스트)
    • $? 변수 체크 (외부 명령을 실행 후, 그 결과가 성공/실패인지를 체크)

추천 문서 2

  • Link: https://velog.io/@markyang92/declaretypeset
  • 이 문서가 다루는 내용
    • 변수 이름 작명 규칙
    • 변수 선언, 변수 사용(값 참조)
    • eval 키워드 사용법
    • export, declear, set 키워드를 사용하는 이유 및 활용 사례
    • unset, typeset 키워드 사용 사례
    • 미리 정의된 환경 변수 (HOME, PATH, LANG, SHELL, USER, DISPLAY, PS1, PS2, LINES, LS_COLORS 등)

추천 문서 3

  • Link: https://blog.gaerae.com/2015/01/bash-hello-world.html
  • 이 문서가 다루는 내용
    • function 선언, function 참조
    • 변수 선언, 변수 사용(값 참조)
    • 예약 변수(Reserved Variable): FUNCNAME, SECONDS, SHLVL, PPID, BASH_ENV, BASH_VERSION, OSTYPE
    • 위치 매개 변수(Positional Parameters): $0,  $1,  $*,  $@,  $#
    • 특수 매개 변수(Special Parameters): $$,  $?,  $!,  $-,  $_
    • 매개 변수 확장(Parameter Expansion): ${변수:-단어}  ${변수#단어}  ${변수/%찾는단어/변경단어}
    • 배열 변수(Array Variable): ${array[3]}  ${array[@]}
    • 변수 타입 지정(Variables Revisited): declare, typeset
    • 논리 연산자(Logical Operator):  &&  -a   ||  -o
    • 산술 연산자(Arithmetic Operator):  **  +=  -=  *=  /= %=
    • 비트 연산자(Bitwise Operator):  <<   <<=  >>=  &   &=  |   |=  ~   ~  ^   ^=
    • 정수 비교(Integer Comparison):  -eq  -ne  >  -gt  >=  -ge  <  -lt  <=  -le
    • 문자열 비교(String Comparision):  =  ==  !=  <  >  -z   -n
    • 파일 비교 연산자(File Test Operator):  -e  -f  -s  -d -b  -c  -p  -nt  -ot  -ef
    • 반복문: for  while  until
    • 조건문:  if elif  else  fi
    • 선택문:  case ... esac
    • 디버깅 방법: Dry run (bash -n my-run.sh)

 


 

유용한 스크립트 예제 모음

 

Remote node의 파일을 가져와서 Local node의 파일과 동일한지 확인 후 Local 장비에 반영하거나 삭제

아래 스크립트에서 유용한 부분은

  • date(날짜) 출력 포맷을 가공
  • 여러 단어(Word)로 구성된 문자열을 cut 명령으로 자르기(cut, split, delimiter)
  • if 조건문 사용
#!/usr/bin/bash

MY_REMOTE_ACCT=my-id@my-domain.kr

CUR_DATE=`date +%+4Y-%m-%d-%H-%M-%S`
ORIGIN_FILE="my-domain.kr.zone"
REMOTE_FILE="${ORIGIN_FILE}_remote"
BACKUP_FILE="${ORIGIN_FILE}_${CUR_DATE}_bkup"
DIR_PATH=/var/cache/bind

cd $DIR_PATH

scp ${MY_REMOTE_ACCT}:${DIR_PATH}/${ORIGIN_FILE} $REMOTE_FILE

## cksum 명령의 결과가 3개의 컬럼으로 출력되는데, 
## 실제 필요한 데이터는 첫번째 column이라서 출력 내용을 cut -f 1 명령으로 잘라냄.
CKSUM_REMOTE_FILE=$(cksum $REMOTE_FILE | cut -d " " -f 1)
CKSUM_ORIGIN_FILE=$(cksum $ORIGIN_FILE | cut -d " " -f 1)

if [ $CKSUM_REMOTE_FILE -eq $CKSUM_ORIGIN_FILE ]; then
        echo "The ${CKSUM_REMOTE_FILE} and the $CKSUM_ORIGIN_FILE are equivalent"
        exit 1
fi

echo "The ${CKSUM_REMOTE_FILE} and the $CKSUM_ORIGIN_FILE are different"

cp $ORIGIN_FILE $BACKUP_FILE
cp $REMOTE_FILE $ORIGIN_FILE

systemctl restart bind9

 

 

##

## TODO: 나중에 추가로 예제를 작성하기

##

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

반응형

준비 작업:  Elastic 8.0 및 Kibana 설치하기

아래 김종민 님의 설명을 읽고, ElasticsearchKibana 설치하는 것이 제일 쉽고 간단하다.

 

 

Elastic 8.0 설치하기 - Jongmin's Lifelog

정말 오랬만에 블로그 포스팅을 하네요. 얼마 전에 드디어 Elastic 8.0 이 출시되었습니다. 6.x 릴리스 까지는 보통 1년 ~ 18개월 정도의 텀을 두고 비교적 빠르게 버전 업데이트를 했는데 7.x 릴리스

kimjmin.net

 

##
## Elasticsearch 기동하기
##

$  bin/elasticsearch


##
## Kibana 기동하기
##   주의: 명령 옵션으로 --host를 지정하지 않으면, 기본값이 127.0.0.1로 설정된다.
##        만약 Web Browser가 kibana 서버와 다른 곳에 있다면 반드시 아래와 같이 
##        외부에서 접근 가능한 서버 주소를 지정해주어야 한다.

$ bin/kibana  --host=192.168.0.11

 

 


 

Elasticsearch 서버와 Kibana 서버를 설치했으면, 아래의 문서를 보면서 Python Example App을 작성한다.

 

Elasticsearch Python Client Example

2022년 11월 현재, 아래의 Web Docs가 가장 쉽게 설명된 것 같다.

Python PKG 설치, 인증/연결, 설정, Client Example Code 등 필요한 내용을 다 포함하고 있다.

 

 

Elasticsearch Python Client [8.5] | Elastic

 

www.elastic.co

 

 

아래  Docs는 초반에 "Elastic Cloud"를 먼저 예시로 설명하고 있는데,
만약 Private 환경(즉, self-managed cluster)에서 Client Example을 테스트할 것이라면
이 Docs의 아래 부분만 읽으면 된다.

[ 즉, 바로 이 부분부터 읽고 따라하면 된다 ]
https://www.elastic.co/guide/en/elasticsearch/client/python-api/master/connecting.html#connect-self-managed-new

 

 

Connecting | Elasticsearch Python Client [master] | Elastic

The async client shouldn’t be used within Function-as-a-Service as a new event loop must be started for each invocation. Instead the synchronous Elasticsearch client is recommended.

www.elastic.co

 

CRUD(Create, Read, Update, Delete) 예제를 보고 싶다면, 아래  Web Docs를 열람.

 

https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/examples.html

 

Examples | Elasticsearch Python Client [8.5] | Elastic

Below you can find examples of how to use the most frequently called APIs with the Python client. Indexing a documentedit To index a document, you need to specify three pieces of information: index, id, and a body: from datetime import datetime from elasti

www.elastic.co

 

 

실제로 위 Web Docs를 보고 조금 변경해서 작성해본 예시이다.

그냥 Copy & Paste해서  `python3  myexample.py` 명령을 수행하면 된다.

 

Document 1개를 Elasticsearch에 저장하는 예제

from datetime import datetime
from elasticsearch import Elasticsearch

##
## NOTE : Configuration for multi node
##
NODES = [ "https://10.1.3.166:9200" ]

##
## Password for the 'elastic' user generated by Elasticsearch
##
ELASTIC_PASSWORD = "mypasswd"

##
## Create the client instance
##
es = Elasticsearch(
    NODES,
    ca_certs="/MyWorkSpace/elastic-stack-metal-install/elasticsearch-8.5.1/config/certs/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

## Create documents
doc = {
    'my-key-example-a': 'my-value-1',
    'my-key-example-b': 'my-value-2',
    'date': datetime.now(),
    'msg': "my log message example... hello~  world ^^",
}

resp = es.index(index="example-index-0", id=0, document=doc)
print(resp['result'])

 

Bulk로 많은 Document를 Elasticsearch에 저장하는 예제

from datetime import datetime
from elasticsearch import Elasticsearch
from randmac import RandMac


NODES = [ "https://10.1.3.166:9200" ]

##
## Password for the 'elastic' user generated by Elasticsearch
##
ELASTIC_PASSWORD = "mypasswd"

##
## Create the client instance
##
es = Elasticsearch(
    NODES,
    ca_certs="/MyWorkSpace/elastic-stack-metal-install/elasticsearch-8.5.1/config/certs/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

doc_id = 0
loop_cnt = 0

##
## Create documents
##
##   참고: 아래 for 문은 document 예시를 그럴듯하게 만들기 위함이다.
##        실제 Elasticsearch와는 아무런 관련이 없다. ^^
ip_networks = ["10", "172", "192"]

for ii in ip_networks:
    for xx in range(254):
        for yy in range(254):
            for zz in range(254):
                macaddress = str(RandMac())
                doc = {
                    'app': 'nac-server',
                    'level': 'info',
                    'date': datetime.now(),
                    'ip-address': ii + '.' + str(xx) + '.' +  str(yy) + '.' + str(zz),
                    'mac-address': macaddress,
                    'msg': 'Device ' + macaddress + ' is started',
                }

                doc_id += 1
                loop_cnt += 1
                resp = es.index(index="example-index-0", id=doc_id, document=doc)
            print("Count: " + str(loop_cnt) + "   " + str(resp['_index']) + "   " + str(resp['_id']) + "   " + str(resp['result']) + "   shard:" + str(resp['_shards']) + "   " + str(resp['_seq_no']))

print("\nTotal Document: " + str(doc_id))

 

Document를 조회하기

from datetime import datetime
from elasticsearch import Elasticsearch

NODES = [ "https://10.1.3.166:9200" ]

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "mypasswd"

# Create the client instance
es = Elasticsearch(
    NODES,
    ca_certs="/MyWorkSpace/elastic-stack-metal-install/elasticsearch-8.5.1/config/certs/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
) 

resp = es.get(index="test-index", id=5)
print(resp)

 

 

Kibana Web GUI로 결과 확인하기

Kibana Web GUI의 'dev tool'을 이용하여 아래와 같이 index, document를 조회할 수 있다.

Kibana Web UI

 

위 Web GUI에서 사용했던 Elasticsearch Query 참고.
##
## Index 정보를 가져온다.
##

GET _cat/indices?v

## 응답은 이런 모양이다.
health status index           uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   example-index-0 Up1jqY3PTG2pLHdOLJcLGQ   1   1   18126912          739      2.9gb          2.9gb
yellow open   test-index      nGaLdNNORHKfJF1maBlNvw   1   1          2            0     11.2kb         11.2kb




##
## "example-index-0" 인덱스에 있는 모든 document 중에서 3개만 가져온다.
##

GET example-index-0/_search?size=3
{  
  "query": {
    "match_all": { }
  }
}
 

##
## "app" 항목 중에서 "server"라는 어휘가 포함돠ㅣㄴ 문서를 모두 가져온다.
##

GET example-index-0/_search
{  
  "query": {
    "match": { "app": "server" }
  }
}


##
## "mac-address" 항목 중에서 정확하게 "0e:c3:0d:97:ba:f0" 와 일치하는 document만 가져온다.
##

GET example-*/_search
{  
  "query": {
    "match_phrase": { "mac-address": "0e:c3:0d:97:ba:f0" }
  }
}


##
## Elasticsearch Cluster 상태 정보를 가져온다. 
##

GET /_cluster/state

GET /_cluster/state?filter_path=metadata.indices.*.stat*

GET /example-index-0/_stats


##
## Elasticsearch Cluster에 저장된 전체 Document 개수를 가져온다.
##

GET /_count


##
## 위 _count 정보 중에서 _shard 정보를 제외한 정보를 가져온다.
##

GET /_count?filter_path=-_shards

 

 

반응형

 

##
## Cluter Network 설정 정보 보기
##

$ kubectl get network.config/cluster -o jsonpath='{.status}{"\n"}'
{"clusterNetwork":[{"cidr":"10.128.0.0/14","hostPrefix":23}],"clusterNetworkMTU":1450,"networkType":"OpenShiftSDN","serviceNetwork":["172.30.0.0/16"]}


##
## CNI Network Type 설정 정보 보기
##

$ oc get network.config/cluster -o jsonpath='{.status.networkType}{"\n"}'
OpenShiftSDN

$
반응형

아래 Script는 Kuberentes Node의 IP Address를 얻어와서, 이 IP Address로 Node에 SSH 접속하여 'shutdown' 명령을 수행하는 예제이다.

 

#!/bin/bash

for ip in $(oc get nodes  -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}')
do
   echo "reboot node $ip"
   ssh -o StrictHostKeyChecking=no core@$ip sudo shutdown -r -t 3
done
반응형

 

작성일: 2024년 1월 25일

 

 

##
## Container Image 목록 조회하기
##
$  curl -X GET http://192.168.2.2:5000/v2/_catalog

##
## 특정  Image의 tag list 조회하기
##
$  curl -X GET http://192.168.2.2:5000/v2/almighty/tags/list

 

 


 

+ Recent posts