# Database connection

 

Python으로 각 DB별 연결 내용 정리

# python3 설치
yum install python3 -y

 

1. PostgreSQL

# PostgreSQL 드라이버 설치
pip install psycopg2
python3 -m pip install psycopg2

 

import psycopg2
 
try:
    conn = psycopg2.connect(
        host="192.168.123.50",
        port="5432",
        database="postgres",
        user="user1",
        password="password")
 
    cur = conn.cursor()
 
    cur.execute("select version()")
 
    print(cur.fetchone())
 
except Exception as e:
    print("Error while fetching Schema")
    print(e)
 
finally:
    conn.close()

 

2. MySQL/MariaDB

# MySQL/MariaDB 드라이버 설치
pip install pymysql
python3 -m pip install pymysql

 

import pymysql
 
try:
    conn = pymysql.connect(
        host='192.168.123.50',
        port=3306 ,
        user='user1',
        password='password',
        db='mysql',
        charset='utf8'
    )
 
    cur = conn.cursor()
    cur.execute("select version()")
 
    rows = cur.fetchall()
    cur.close()
    conn.close()
    print(rows)
 
except Exception as e:
    print("Error while fetching Schema")
    print(e)

 

3. ClickHouse

# clickhouse 드라이버 설치
pip3 install clickhouse-driver[lz4]
python3 -m pip install clickhouse-driver[lz4]

 

from clickhouse_driver import Client
 
try:
    client = Client('192.168.123.50',
                user='user',
                password='password',
                verify=False,
                database='default',
                compression=True)
 
    result = client.execute('SELECT now(), version()')
    result2 = client.execute('SHOW databases')
    print(result)
 
except:
    print("Error while fetching Schema")

 

4. MongoDB

# MongoDB 드라이버 설치
pip install pymongo
python3 -m pip install pymongo

 

 

import pymongo
 
try:
    #conn = pymongo.MongoClient('mongodb://{user}:{password}@127.0.0.1:27017')
    conn = pymongo.MongoClient('mongodb://127.0.0.1:27017')
    db = conn.get_database('testdb')
    collection = db.get_collection('testcollection')
 
    for x in collection.find():
        print(x)
 
except Exception as e:
    print("Error while fetching Schema")
    print(e)

 

5. ElasticSearch

# ElasticSearch 드라이버 설치
pip install elasticsearch
python3 -m pip install elasticsearch

 

from elasticsearch import Elasticsearch
 
try:
    es = Elasticsearch('192.168.123.50:9200')
 
    # elastic info
    print(es.info())
 
    # get all index
    print(list(es.indices.get_alias().keys()))
 
    print(es.indices.get_mapping("products"))
    print(es.indices.get_mapping("work"))
 
except Exception as e:
    print("Error while fetching Schema")
    print(e)

 

6. Redis

# Redis 드라이버 설치
pip install scylla-driver
python3 -m pip install scylla-driver

 

import redis
 
try:
    r = redis.Redis(host='192.168.123.50', port=6379, db=0)
    r.set('k_test','v_test')
    print(r.get('k_test'))
    r.close()
except Exception as e:
    print("error")
    print(e)

 

7. ScyllaDB

# ScyllaDB 드라이버 설치
pip install scylla-driver
python3 -m pip install scylla-driver

 

import cassandra
 
print(cassandra.__version__)

 

 

 

To be continued.........

 

 

Made by 꿩

 

'IT > Bash' 카테고리의 다른 글

[Linux] SSH 공개키 설정  (0) 2022.03.28
[Bash] 스크립트 #! 의미  (0) 2021.10.19
[Bash] 터미널 jar 파일 생성  (0) 2021.10.05
[centos] java openjdk 설치 및 삭제  (0) 2021.10.05
Redis 메모리 & 시간 측정 스크립트  (0) 2021.05.14

# SSH 공개키 설정

 

root 계정으로 서비스를 실행하는 것은 보안상 좋은 습관이 아니다

HDFS를 설치할 때 ssh 공개키에 대한 지식이 필요해서 포스팅을 한다

 

우선, 모든 서버에 hadoop이라는 계정을 생성해보자

groupadd hadoop
useradd -c "Apache Hadoop" -d /home/hadoop -g hadoop -s /bin/bash -u 9000 hadoop
passwd hadoop

 

ssh는 public key 암호방식을 사용한다

public key 암호방식은 비대칭 키로 양방향 암호화 방식이다.

public key와 private key를 사용한다

 

public key로 암호화된 데이터는 private key로만 복호화가 가능하다

private key로 암호화 된데이터는 public key로만 복호화가 가능하다

 

SSH Key를 생성하면 public key와 private key가 만들어진다

# 키 생성
ssh-keygen -t rsa -C "hadoop@localhost"

ssh-keygen이라는 프로그램을 이용하여 키를 생성하면 된다

-t rsa 옵션은 rsa 암호화 방식으로 키를 생성한다

-C 옵션은 코멘트이다

Enter file in which to save the key (/root/.ssh/id_rsa):

ssh 키가 저장될 위치를 말한다

기본 경로는 로그인한 사용자의 홈디렉토리의 {사용자}/.ssh/ 이다.

그냥 엔터 누르면 된다.

Enter passphrase (empty for no passphrase):

passphrase는 암호화시 salt처럼 사용하는 값이다.

The key fingerprint is:
SHA256:uIm++us4lxkLQoQJ3c3tp7ygxFsncmBKtBoN2TLGVWk hadoop@localhost

SHA256 해시 알고리즘을 사용했다는 것을 알려준다

 

위와 같이 키를 생성하면 public key와 private key가 생성된다.

### Public 키
# cat ~/.ssh/id_rsa.pub
ssh-rsa (키 내용) (코멘트)

### Private 키
# cat ~/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----

id_rsa는 private key로 타인에게 노출되면 안되는 키이고

id_rsa.pub은 public key로 remote 서버의 authorized_keys에 입력한다

authorized_keys 파일을 직접 생성할 경우 chmod 644 설정해줘야 한다.

authorized_keys는 public key 값을 저장하는 파일로 remote 서버에 생성하면 된다

 

HDFS에서는 네임노드가 private key를 가지고 있고

데이터노드가 public key를 가지고 있다고 보면 된다.

 

추가적으로 확인해야 할 사항이 한가지 더 있다

리눅스 접근 통제(tcpwrapper) 설정이 되어 있으면 허용해줘야 한다

# cat /etc/pam.d/sshd
...
account    required     pam_access.so accessfile=/etc/security/access.conf
...

# cat /etc/security/access.conf
...
-:hadoop:ALL EXCEPT 127.0.0.1 192.168.11.60

# cat /etc/hosts.allow
# cat /etc/hosts.deny

 

access.conf 파일에서

hadoop 계정으로 접근하는 ip를 허용해준다

더불어서 hosts.allow와 hosts.deny 파일도 체크하고

허용이 필요하면 허용해준다

 

위의 모든 과정이 끝나면

ssh hadoop@localhost로 비밀번호 없이 접속이 되는지 확인한다

[hadoop@localhost .ssh]$ ssh localhost
Last login: Mon Mar 28 20:12:07 2022 from ip
[hadoop@localhost ~]$

 

[참고자료]

https://storycompiler.tistory.com/112

https://brunch.co.kr/@sangjinkang/52

https://opentutorials.org/module/432/3742

https://gukii.tistory.com/19

To be continued.........

 

 

Made by 꿩

'IT > Bash' 카테고리의 다른 글

[Python] Database connection  (0) 2022.05.09
[Bash] 스크립트 #! 의미  (0) 2021.10.19
[Bash] 터미널 jar 파일 생성  (0) 2021.10.05
[centos] java openjdk 설치 및 삭제  (0) 2021.10.05
Redis 메모리 & 시간 측정 스크립트  (0) 2021.05.14

# [Bash] 스크립트 #! 의미

 

#!는 스크립트 제일 앞에서

어떤 명령어 해석기를 이용하여 파일을 실행할 것인지를 명시하는 것이다.

 

리눅스에서는 기본적으로 파일을 실행할때 bash 쉘로 설정되어 있어서

따로 명시를 하지 않아도

#!/bin/bash
#!/bin/sh

위의 bash 쉘로 자동 실행되게 한다.

 

다음의 예시를 통해 눈으로 확인해보자.

[root@chuchu test]# cat test1.sh 
#!/bin/bash

echo "Hello World!"
[root@chuchu test]# cat test2.sh 
#!/bin/cat

echo "Hello World!"
[root@chuchu test]# 
[root@chuchu test]# ./test1.sh 
Hello World!
[root@chuchu test]# ./test2.sh 
#!/bin/cat

echo "Hello World!"

 

참고: https://hahoital.tistory.com/145

To be continued.........

 

 

Made by 꿩

'IT > Bash' 카테고리의 다른 글

[Python] Database connection  (0) 2022.05.09
[Linux] SSH 공개키 설정  (0) 2022.03.28
[Bash] 터미널 jar 파일 생성  (0) 2021.10.05
[centos] java openjdk 설치 및 삭제  (0) 2021.10.05
Redis 메모리 & 시간 측정 스크립트  (0) 2021.05.14

# [Bash] 터미널 jar 파일 생성

 

1. java 파일 생성

# cat Hello.java 
public class Hello {
  public static void main(String args[]){
    System.out.println("hello world");
  }
}

 

2. 컴파일

# javac Hello.java

 

3. manifest.txt 파일 생성

# cat manifest.txt 
Main-class: Hello

※ manifest.txt 파일이란? jar로 패키지된 파일 구성요소의 메타 정보를 가지고 있는 파일이다.

 

4. jar 파일 생성

# jar -cvmf manifest.txt hello.jar Hello.class 
Manifest를 추가함
추가하는 중: Hello.class(입력 = 415) (출력 = 286)(31%를 감소함)

 

5. jar 파일 실행

# java -jar hello.jar 
hello world

To be continued.........

 

 

Made by 꿩

 

'IT > Bash' 카테고리의 다른 글

[Python] Database connection  (0) 2022.05.09
[Linux] SSH 공개키 설정  (0) 2022.03.28
[Bash] 스크립트 #! 의미  (0) 2021.10.19
[centos] java openjdk 설치 및 삭제  (0) 2021.10.05
Redis 메모리 & 시간 측정 스크립트  (0) 2021.05.14

# [centos] java openjdk 설치 및 삭제

 

1. java 설치현황 파악

# rpm -qa | grep jdk
java-11-openjdk-11.0.12.0.7-0.el7_9.x86_64
java-1.8.0-openjdk-headless-1.8.0.302.b08-0.el7_9.x86_64
copy-jdk-configs-3.3-10.el7_5.noarch
java-11-openjdk-devel-11.0.12.0.7-0.el7_9.x86_64
java-11-openjdk-headless-11.0.12.0.7-0.el7_9.x86_64
java-1.7.0-openjdk-headless-1.7.0.261-2.6.22.2.el7_8.x86_64

 

2. java 삭제

yum remove java-11-openjdk-devel.x86_64 -y

 

3. java 설치

yum install java-11-openjdk-devel.x86_64 -y

echo 'export JAVA_HOME=/usr/lib/jvm/jre-openjdk' > /etc/profile.d/java.sh
echo 'setenv JAVA_HOME "/usr/lib/jvm/jre-openjdk"' > /etc/profile.d/java.csh

 

4. java 설치 확인

# java -version
openjdk version "11.0.12" 2021-07-20 LTS
OpenJDK Runtime Environment 18.9 (build 11.0.12+7-LTS)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.12+7-LTS, mixed mode, sharing)

# javac -version
javac 11.0.12

To be continued.........

 

 

Made by 꿩

'IT > Bash' 카테고리의 다른 글

[Python] Database connection  (0) 2022.05.09
[Linux] SSH 공개키 설정  (0) 2022.03.28
[Bash] 스크립트 #! 의미  (0) 2021.10.19
[Bash] 터미널 jar 파일 생성  (0) 2021.10.05
Redis 메모리 & 시간 측정 스크립트  (0) 2021.05.14

# Redis 메모리 & 시간 측정 스크립트

 

Python으로 redis 테스트 시 메모리와 시간 측정을 위한 스크립트

#!/bin/sh
 
### help message
function help() {
/bin/cat << EOF
Usage :
    redis_test.sh [-n/--filename] filename [-f/--flushall] [-h/--help]
EOF
}
    
### flag
INPUT_FILE=False
  
### check parameter
while (("$#")); do
    case "$1" in
        -n|--filename)
            if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
                INPUT_FILE=$2
                shift 2
            else
                echo "[Error] Argument for $1 is missing" >&2
                exit 1
            fi
            ;;
        -f|--flushall)
            FLUSHALL=True
            shift
            ;;
        -h|--help)
            help
            exit 1
            ;;
        -*|--*) # unsupported flags
            echo "[Error] Unsupported flag: $1" >&2
            echo "$0 -h for help message" >&2
            exit 1
            ;;
        *)
            echo "[Error]: Arguments with not proper flag: $1" >&2
            echo "$0 -h for help message" >&2
            exit 1
            ;;
    esac
done
   
  
### check if input filename
if [ $# -eq 0 ] && [ "$INPUT_FILE" == "False" ]
  then
    echo "[Error] Please give me test file"
    help;
    exit 1;
fi
   
 
### flushall execution
if [[ "$FLUSHALL" == True ]]
then
    ok=`redis-cli FLUSHALL`
    echo "[Info] redis memory flush all : ${ok}"
fi
 
  
### check memory and time before test
before=`redis-cli INFO memory | grep 'used_memory:' | awk -F: '{print $2}'`
b=`echo "${before//[$'\t\r\n ']}"`
StartTime=$(date +%s)
  
### test execution
echo "[Info] test start"
################################################ 테스트 실행 파일
python3 $INPUT_FILE
echo "[Info] test end"
  
### check memory and time after test
after=`redis-cli INFO memory | grep 'used_memory:' | awk -F: '{print $2}'`
a=`echo "${after//[$'\t\r\n ']}"`
EndTime=$(date +%s)
  
used=$(expr $a - $b)
  
echo ""
echo ""
echo "####################################[result]################################################"
echo "[result] redis used memory ${used}"
echo "[result] It takes $(($EndTime - $StartTime)) seconds to complete this task."

 

 

[참고문서]
https://tyanjournal.com/tips/bash-command-line-option-parsing%ED%95%98%EA%B8%B0-%EC%98%B5%EC%85%98-%EB%B0%9B%EA%B8%B0/
https://knight76.tistory.com/entry/Redis-%EB%A0%88%EB%94%94%EC%8A%A4-%ED%85%8C%EC%8A%A4%ED%8A%B8%ED%9B%84-%EB%A9%94%EB%AA%A8%EB%A6%AC-%EC%B8%A1%EC%A0%95%ED%95%98%EA%B8%B0-redis-used-memory

 

To be continued.........

 

 

Made by 꿩

'IT > Bash' 카테고리의 다른 글

[Python] Database connection  (0) 2022.05.09
[Linux] SSH 공개키 설정  (0) 2022.03.28
[Bash] 스크립트 #! 의미  (0) 2021.10.19
[Bash] 터미널 jar 파일 생성  (0) 2021.10.05
[centos] java openjdk 설치 및 삭제  (0) 2021.10.05

+ Recent posts