카테고리

asm (27) bootloader_x86_grub (1) C (92) compile (11) config (76) CPP (13) CSS (1) debugging (7) gimp (1) Go (1) html (1) Java (1) JavaScript (1) kernel (19) LibreOffice (3) Linux system progamming (21) MFC (1) opencv (4) OpenGL (1) PHP (1) Python (4) qemu (29) shell (3) socket (7) troubleshooting (2) ubuntu18.04 (2) windows (1)

2018/12/24

양의 정수, 음의 정수 구분, 중첩문 사용

#include <stdio.h>
int main(void) {
double number;

printf("Enter a number: ");
scanf("%lf", &number);

// 입력된 숫가 0 보다 작은 경우 참
if(number < 0.0)
printf("You entered a negative number.");

// 입력된 숫가 0 보다 큰 경우 참
else if(number > 0.0)
printf("You entered a positive number.");

// 두 개의 조건식이 전부 거짓으로 판단 되면
else
printf("You entered 0.");
return 0;
}

양의 정수, 음의 정수 분별.

#include <stdio.h>

int main(void) {
double number;

printf("Enter a number: ");
scanf("%lf", &number);

if (number <= 0.0)
{
if (number == 0.0)
printf("You entered 0.");
else
printf("You entered a negative number.");
} else
printf("You entered a positive number.");
return 0;
}

재귀 함수 factorial

#include <stdio.h>
long int multiplyNumbers(int n);

int main(void){
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld\n", n, multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n){
if(n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}

정수 입력  : 6
6 = 720

factorial

#include <stdio.h>

int main(void){
int n, i;
unsigned long long factorial = 1;

printf("Enter an integer: ");
scanf("%d", &n);

// 사용자 음의 정수 입력시 오류
if(n < 0)
printf("Error! Factorial of a negative number doesn't exist.\n");
else{
for(i=1; i<=n; ++i){
factorial *= i; // factorial = factorial * 1;
}
printf("Factorial of %d = %llu\n", n, factorial);
}
return 0;
}

운분투 18.04 kali Linux 사용 설치 유틸

운분투 18.04 kali Linux 사용 설치 유틸

katoolin을 사용해 원하는 프로그램만 설치 가능하다.

파일썬 및 git 설치
sudo apt-get install python git

복사
git clone https://github.com/LionSec/katoolin.git

실행 파일 이동
sudo cp katoolin/katoolin.py /usr/bin/katoolin

실행 권한
sudo chmod +x /usr/bin/katoolin
sudo vi /usr/bin/katoolin
첫줄 파있너 버전 변경
#!/usr/bin/env python2.7

실행
sudo katoolin

1. 저장수 추가 및 업데이트
1) Add Kali repositories & Update
2) View Categories
3) Install classicmenu indicator
4) Install Kali menu
5) Help

kat > 1

하위 메뉴 생성 저장소 추가 1 입력
1) Add kali linux repositories
2) Update
3) Remove all kali linux repositories
4) View the contents of sources.list file

What do you want to do ?> 1

저장소 업데이트 2 입력
저장소 제거 3 입력
저장소 리스트 항목(/etc/apt/source.list) 보기
1) Add kali linux repositories
2) Update
3) Remove all kali linux repositories
4) View the contents of sources.list file

What do you want to do ?> 2

이전 메뉴 이동
What do you want to do ?> back
1) Add Kali repositories & Update
2) View Categories
3) Install classicmenu indicator
4) Install Kali menu
5) Help

주 메뉴 이동
kat > gohome
1) Add Kali repositories & Update
2) View Categories
3) Install classicmenu indicator
4) Install Kali menu
5) Help

kat >

2. 카테고리
kat > 2
**************************** All Categories *****************************
1) Information Gathering 8) Exploitation Tools
2) Vulnerability Analysis 9) Forensics Tools
3) Wireless Attacks    10) Stress Testing
4) Web Applications    11) Password Attacks
5) Sniffing & Spoofing    12) Reverse Engineering
6) Maintaining Access    13) Hardware Hacking
7) Reporting Tools    14) Extra
0) All
Select a category or press (0) to install all Kali linux tools .

총 14 개의 카테고리, 전체 설치가 있음.
전체 설치시 디스크 용량을 많이 사용 하므로 필요한 프로그램만 설치한다.

kat > 8

=+[ Exploitation Tools

1) Armitage
 2) Backdoor Factory
 3) BeEF
 4) cisco-auditing-tool
 5) cisco-global-exploiter
 6) cisco-ocs
 7) cisco-torch
 8) commix
 9) crackle
10) jboss-autopwn
11) Linux Exploit Suggester
12) Maltego Teeth
13) SET
14) ShellNoob
15) sqlmap
16) THC-IPV6
17) Yersinia

0) Install all Exploitation Tools

Insert the number of the tool to install it .

kat >
3. Classic 메뉴  설치
클래식 메뉴 GUI
sudo apt-get install classicmenu-indicator

4. 칼리 메뉴 설치
주 메뉴로 이동 후 
key> 4
종료 Ctrl + C

프로젝트 사이트: https://github.com/LionSec/katoolin

우분투 18.04 하드디스크 관리 유틸

기본 제공 디스크 관리
sudo apt-get install gnome-disk-utility

baobab: 사용량 확인
usb-creator-gtk : 부팅 디스크 만들기
gnome-shell-extension-hard-disk-led : 확장 셜
localepurge : /etc/locale.nopurge 지정한 언어로만 man page 설정, 나머지는 제거
sudo apt-get install baobab usb-creator-gtk gnome-shell-extension-hard-disk-led localepurge

우분투 마메설정(MAME)

ubuntu 16.04 MAME Install

MAME(Multiple Arcade Machine Emulator)

1 기본 흐름.
1.1 저장소 등록
sudo add-apt-repository universe

1.2 업데이트
sudo apt update

1.3 MAME 설치
sudo apt-get install mame

2. 우분투 설치
2.1 sudo add-apt-repository ppa:c.falco/mame
2.2 sudo apt-get update
2.3 sudo apt-get install mame

3. 실행
cd ~/.mame
mame -createconfig
mame.ini 생성
vi mame.ini
롬파일 위치 지정

mkdir -p ~/mame/roms

굳이 압축 파일을 풀 필요는 없습니다. mame에서 알아서 해독하고 실행합니다.

4. 조이스틱
sudo add-apt-repository ppa:gregory-hainaut/pcsx2.official.ppa
sudo apt-get udpate

sudo apt-get install pcsx2
검색: pcsx

설정창 확인 -> 조이스틱 버튼 설정

우분투 18.04 의존성 문제

우분투 16.04에서 18.04로 업데이트 한 후 gtk3-dev와 wayland 에서 문제가 발생한다.

기본 16.04에서 wayland 테스트 때문에 작성하고 테스트 했던 파일의 문제인듯 하다.

설치했던 파일 부터 확인해 본다.
dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]'
dpkg -l libwayland* | grep -e '^i' | grep -e 'libgtk-*[0-9]'

의존성 파일을 가지고 있는 파일 백업, 수정.
/var/lib/dpkg/status
16.04 검색 후 필요 없는 프로그램 삭제.

중복 파일 제거.
/var/lib/dpkg/triggers/File

sudo apt-get remove --purge

libwayland-client0
libwayland-cursor0
libwayland-server0

sudo apt-get install libwayland-client0 libwayland-cursor0 libwayland-server0
sudo apt-get install lightdm
sudo apt-get install gnome-shell
sudo apt install ubuntu-restricted-extras
sudo apt install mate-control-center

우분투 비쥬얼 스튜디오 설치 및 사용방법

1. 설치
1.1 윈도우
1.1.1 다운로드: https://code.visualstudio.com/download
1.1.2 환경설정
기타: "Code(으로 열기" 작업를 Windows 탐색기 파일의 상항에 맞는 메뉴에 추가
기타: "Code(으로 열기" 작업를 Windows 탐색기 디렉토리의 상항에 맞는 메뉴에 추가
기타: Code를 지원되는 파일 형식에 대한 편집기로 등록한다.
기타: PATH에 추가(다시 시작한 후 사용 가능)

1.2 우분투
1.2.1 다운로드
저장소 GPG 키 등록
sudo sh -c 'curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg'

저장소 추가
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'

설치
sudo apt-get update
sudo apt-get install git
sudo apt-get install code

실행
arlt + F2 : code

2. 언어 설정
2.1 인터페이스 검색
검색 : ctrl + shipt + p
입력 : display
변경 : "local": "en" -> "ko"
적용 : clrs + s

2.2 인터페이스 한글 저장소 패키지 다운로드
검색 : ctrl + shipt + x
입력 : korea language pack
변경 : install 클릭
적용 : reset now 클릭

2.3 사용할 언어 문법 강조 패키지 다운로드
검색 : ctrl + p
입력 : ext install c/c++
선택 : c/c++ IntelliSense, debugging, and code bro....
적용 : 다시로드

2.4 MinGW 문법 강조(리눅스에서 윈도우 프로그램)
2.4.1 구성
- 리눅스 파티션에 윈도우 설치
- 윈도우 개발환경 구성
- 리눅스 부팅후 마운팅
- apt-get install g++-mingw-w64 mingw-w64 ---> 상항에 맞게 설치

검색 : ctrl + shift + p
입력 : c/pp
선택 : c/cpp: edit configurations...
변경 :
a) 이동: 프로젝트 .vscode 디렉토리
b) 확인: vi c_cpp_propertiess.json
c) 검색: /compilePath
d) 설명: https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/MinGW.md
e) 설정:
{

    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceRoot}",
                "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++",
                "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/mingw32",
                "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/backward",
                "mount_driver_C:/MinGW/include",
                "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
                "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "__GNUC__=6",
                "__cdecl=__attribute__((__cdecl__))"
            ],
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "${workspaceRoot}",
                    "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++",
                    "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/mingw32",
                    "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include/c++/backward",
                    "mount_driver_C:/MinGW/include",
                    "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include-fixed",
                    "mount_driver_C:/MinGW/lib/gcc/mingw32/6.3.0/include"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            }
        }
    ],
    "version": 4
}
f) 다시로드

3. 프로젝트 생성
3.1 프로젝트 위치 지정
검색 : ctrl + shift + e (탐색기 창)
열기 : ctrl + k, ctrl + o
생성 : 디렉토로 만들기(아이콘 클릭) 생성

3.2 디렉토리 생성
검색 : 오른쪽 패널창 -> 디렉토리 아이콘 생성 클릭
입력 : 디렉토리 이름

3.2.1 추가
영역 : 생성할 디렉토리 빈 공간 영역 선택
검색 : 오른쪽 패널창 -> 디렉토리 아이콘 생성 클릭
입력 : 디렉토리 이름

3.3 파일 생성
검색 : 오른쪽 패널창 -> 파일 아이콘 생성 클릭
입력 : 파일 이름



4. 컴파일
4.1 빌드 환경 구성
이동: 오른쪽 패널창 -> .vscode::{} tasks.json
입력: tasks.json
수정:
{
    "version": "2.0.0",
    "runner": "terminal",
    "type": "shell",
    "echoCommand": true,
    "presentation" : { "reveal": "always" },
    "tasks": [
          // g++ compile
          {
            "label": "save and compile for C++",
            "command": "g++",
            "args": [
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": "build",

            // compile error editer apply
            // reference:   https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

            "problemMatcher": {
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                    // The regular expression.
                   //Example to match: helloWorld.c:5:3: warning: implicit declaration of function 'prinft'
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        //gcc compile
        {
            "label": "save and compile for C",
            "command": "gcc",
            "args": [
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": "build",

            // compile error editer apply
            // reference:   https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

            "problemMatcher": {
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                   // The regular expression.
                   //Example to match: helloWorld.c:5:3: warning: implicit declaration of function 'prinft'
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        // linux binary execution

        {
            "label": "execute",
            "command": "cd ${fileDirname} && ./${fileBasenameNoExtension}",
            "group": "test"
        }
        // // windows binary execution
        // {
        //     "label": "execute",
        //     "command": "cmd",
        //     "group": "test",
        //     "args": [
        //         "/C", "${fileDirname}\\${fileBasenameNoExtension}"
        //     ]
 
        // }
    ]
}
4.2 단축키 설정
선택: 파일 > 기본 설정 > 바로 가기 키
이동: 오른쪽 패널창 -> 열려 있는 편집기 -> Keyboard Shortcuts
입력: 고급 사용자 지정의 경우 다음 파일을 열고 편집하세요. keybinding.json <- 클릭
우선 순위: 1. 사용자 환경 단축키 
           2. 기본 제공 단축키 설정

// Place your key bindings in this file to override the defaults
[
// compile
    { "key": "ctrl+alt+c", "command": "workbench.action.tasks.build" },
 
    // execute
    { "key": "ctrl+alt+r", "command": "workbench.action.tasks.test" }
]

단축키 : Ctrl +Alt + C
컴파일: save and compile for C
확인: 오른쪽 패널창 컴파일 결과 파일 생성
실행: Ctrl  + Alt + R -> execute

5. 디버깅
이동: 오른쪽 패널창 -> .vscode::{} tasks.json
입력: tasks.json
수정:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "runner": "terminal",
    "type": "shell",
    "echoCommand": true,
    "presentation" : { "reveal": "always" },
    "tasks": [
          // g++ compile
          {
            "label": "save and compile for C++",
            "command": "g++",
            "args": [
                "${file}",
                "-g",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": "build",

            // compile error editer apply
            // reference:   https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

            "problemMatcher": {
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                    // The regular expression.
                   //Example to match: helloWorld.c:5:3: warning: implicit declaration of function 'prinft'
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        //gcc compile
        {
            "label": "save and compile for C",
            "command": "gcc",
            "args": [
                "${file}",
                "-g",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": "build",

            // compile error editer apply
            // reference:   https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

            "problemMatcher": {
                "fileLocation": [
                    "relative",
                    "${workspaceRoot}"
                ],
                "pattern": {
                   // The regular expression.
                   //Example to match: helloWorld.c:5:3: warning: implicit declaration of function 'prinft'
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        // linux binary execution

        {
            "label": "execute",
            "command": "cd ${fileDirname} && ./${fileBasenameNoExtension}",
            "group": "test"
        }
        // // windows binary execution
        // {
        //     "label": "execute",
        //     "command": "cmd",
        //     "group": "test",
        //     "args": [
        //         "/C", "${fileDirname}\\${fileBasenameNoExtension}"
        //     ]
 
        // }
    ]
}

선택: 오른쪽 패널창 -> 디버그 아이콘 클릭
이동: 환경설정 아이콘 클릭 -> 사용할 GDB 선택
수정: launch.json
{
    // IntelliSense를 사용하여 가능한 특성에 대해 알아보세요.
    // 기존 특성에 대한 설명을 보려면 가리킵니다.
    // 자세한 내용을 보려면 https://go.microsoft.com/fwlink/?linkid=830387을(를) 방문하세요.
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            // "program": "enter program name, for example ${workspaceFolder}/a.out",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            //"externalConsole": true,
            "externalConsole": false,
            "MIMode": "gdb",
            // windows gdb
            // "miDebuggerPath": "C:/MinGW/bin/gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]

적용: 비쥬얼 스튜디오 디시 시작

참고:
윈도우에서 사용하는 디버깅 창 및 단축키,
비주얼 스튜디오 버전마다 단축키 차이가 있음.

자동/조사식/메모리 창
자동창 생성: 디버그 -> 창 -> 자동
단축키 : ctrl + alt + v, a

조사식창 생성: 디버그 -> 창 -> 조사식 -> 조사식 1~4
단축키 : ctrl + alt + w, 1~4
Shift+F9: 다른 창을 띄워서 변수의 값이 얼마인지 계산할 수있고, 그 자리에서 조사식을 추가 할 수도 있다.

메모리창 생성: 디버그 -> 메모리 -> 메모리 1~4
단축키 : ctrl + alt + m, 1~4
기본 메모리 창 : alt + 6

F9 : 브레이크 포인트 설정 및 해제

전체 브레이크 포인트 해제 : 디버그 -> 모든 중단점 해제
단축키 : Ctrl + Shift + F9

F5 : 디버깅 연결 프로그램과 시작.
Shift + F5 : 디버깅 없이 실행

F10: 디버깅 모드에서 한줄씩 코드를 진행하되, 다른 함수를 호출하게 되는 경우에 그 프로시저를 모두 실행하고 원래 코드로 돌아와서 한줄을 실행하는 기능
Ctrl + F10 : 커서까지 실행, 디버깅 모드에서 커서가 위치한 줄을 만날때 까지 실행하는 기능
Shift + F10 : 프로시저 나가기

F11: 한줄씩 실행
Shift + F11: 프로시저 나가기, 디버깅 모드에서 현재 현재 프로시저의 나머지를 모두 실행하고 나가는 기능

디버깅 공식
1) 중단점을 설정한다.
2) 디버깅 시작
3) F11 을 누르며 한단계씩 코드 실행 or  F10 으로 프로시저 단위 실행
4) 조사식을 추가하여 변수의 변화를 살펴본다.

함수 추적시.
stdio.h, iostream 라이브러리 호출 부분으로 진입시.
Shift + F10 : 프로시저 나가기

우분투 18.04 OpenCV 4.0 가상 개발 환경 구성.

0. 기존 버전 제거.
pkg-config --modversion opencv
설치 버전 정보 출력

기존 패키지 삭제.
sudo apt-get remove --purge  libopencv* python-opencv
sudo apt-get autoremove

삭제 확인
pkg-config --modversion opencv

동적 라이브러리 삭제(--purge) 옵션만 사용할 경우
sudo find /usr/local/ -name "*opencv*" -exec rm -i {} \;

sudo apt-get update
sudo apt-get upgrade

0. 저장소 지원하는 패키지 설치 할 경우.
OpenCV 설치
sudo apt update
sudo apt install python3-opencv

설치 확인.
python3 -c "\
import cv2
print(cv2.__version__)"
이 방법은 자동 설치는 쉬우나 개발에 유연성이 없으므로 소소코드 버전으로 설치한다.

기존 패키지 삭제.
sudo apt-get purge  libopencv* python-opencv
sudo apt-get autoremove

파일썬 버전 확인
python3 --version
Python 3.6.5

파일썬 간단하게 테스트
python3
>> print("OpenCV!")
OpenCV!
>> quit()

1. 개발 도구 설치
sudo apt install build-essential cmake git pkg-config libgtk-3-dev

OpenCV 비디오 스트림 처리, 개별 프레임 접근 하기 위해 다음 라이브러리 설치
sudo apt install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libxine2-dev

실시간 비디오 캡처 API
sudo apt-get install v4l-utils

GStreamer는 비디오 스트리밍을 위한 라이브러리 설치
sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev

OpenCV는 JPEG, PNG, TIFF등 디스크에 있는 이미지 파일을 로드 할 수 있다.
디스크에 있는 이미지 파일을 로드 하려면 이미지 I/O 패키지가 필요함
sudo apt install libjpeg-dev libpng-dev libtiff-dev gfortran openexr

로드 된 후 모니터 화면에 보여주기 위해서는 highgui 모듈, GUI에 의존하는 GTK 개발 라이브러리 필요.
sudo apt install libgtk-3-dev

만약 다른 GUI 일 경우 선택 가능
libgtk2.0-dev
libqt4-dev
libqt5-dev

OpenGL 지원 라이브러리 설치
sudo apt-get install mesa-utils libgl1-mesa-dri libgtkgl2.0-dev libgtkglext1-dev

OpenCV 기본 개발 라이브러리 및 이미지 다차원 처리 패키지 등
sudo apt install python3-dev python3-numpy libtbb2 libtbb-dev libdc1394-22-dev libatlas-base-dev libeigen3-dev
sudo apt install libatlas-base-dev gfortran

python2-7 OpenCv-Python 바인딩 필요 라이브러리 추가.
sudo apt-get install python2.7-dev python-numpy

2. 소스코드 복사
mkdir ~/opencv_build && cd ~/opencv_build
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git

3. Python 환경 설정
파이썬 패키기 관린 pip 설치
cd ~
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

가상 개발 환경 구성
https://virtualenv.pypa.io/en/latest/ 및 https://virtualenvwrapper.readthedocs.io/en/latest/ 를 설치한다.
이 두개의 패키지는 별도의 파이썬 버전과 개발 환경을 생성할 수 있게 한다.
sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/get-pip.py ~/.cache/pip

사용자 환경 설정.
vi /home/username/.bashrc
# virtualenv 및 virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh
:wq
로그아웃 또는 재부팅, 아니면 source /home/username/.bashrc

가상 cv 환경 구축
mkvirtualenv cv -p python3

cv 가상 환경 확인
workon cv
(cv) username:~$

OpenCV 이미지 다차원 처리 NumPy 배열로 표현하며 최종 단계 숫자로 처리함.
pip install numpy -> 이 부분은 apt-get는 일반 환경이며 여기서는 가상 환경에서의 라이브러리.

4. CMake로 OpenCV 설정
workon cv
cd ~/opencv_build/opencv
git checkout 4.0.0

cd ~/opencv_build/opencv_contrib
git checkout 4.0.0

컴파일 구성
mkdir build
cd build

a) 가상환경 
cmake -D CMAKE_BUILD_TYPE=RELEASE \
 -D CMAKE_INSTALL_PREFIX=/usr/local \
 -D INSTALL_PYTHON_EXAMPLES=ON \
 -D INSTALL_C_EXAMPLES=OFF \
 -D OPENCV_ENABLE_NONFREE=ON \
 -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
 -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
 -D BUILD_EXAMPLES=ON ..

b) 일반 환경 구성 라이브러리 경로 설정 없음
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_TBB=OFF \
-D WITH_IPP=OFF \
-D WITH_1394=OFF \
-D BUILD_WITH_DEBUG_INFO=OFF \
-D BUILD_DOCS=OFF \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D WITH_QT=OFF \
-D WITH_GTK=ON \
-D WITH_OPENGL=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
-D WITH_V4L=ON  \
-D WITH_FFMPEG=ON \
-D WITH_XINE=ON \
-D BUILD_NEW_PYTHON_SUPPORT=ON \

c) 일반 환경구성 라이브러리 경루 추가
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_TBB=OFF \
-D WITH_IPP=OFF \
-D WITH_1394=OFF \
-D BUILD_WITH_DEBUG_INFO=OFF \
-D BUILD_DOCS=OFF \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D WITH_QT=OFF \
-D WITH_GTK=ON \
-D WITH_OPENGL=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
-D WITH_V4L=ON  \
-D WITH_FFMPEG=ON \
-D WITH_XINE=ON \
-D BUILD_NEW_PYTHON_SUPPORT=ON \
-D PYTHON2_INCLUDE_DIR=/usr/include/python2.7 \
-D PYTHON2_NUMPY_INCLUDE_DIRS=/usr/lib/python2.7/dist-packages/numpy/core/include/ \
-D PYTHON2_PACKAGES_PATH=/usr/lib/python2.7/dist-packages \
-D PYTHON2_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7.so \
-D PYTHON3_INCLUDE_DIR=/usr/include/python3.6m \
-D PYTHON3_NUMPY_INCLUDE_DIRS=/usr/lib/python3/dist-packages/numpy/core/include/  \
-D PYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages \
-D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
-D BUILD_EXAMPLES=ON ..

경로 패스 지정의 경우: CMAKE 출력 파일의 패스 정보 출력 부분이 없다면 추가 해준다.

OpenCV 4.0.0에서 pkg-config 지원하지 않음.
OPENCV_GENERATE_PKGCONFIG=ON 옵션 추가해, pkg-config의 사용.
https://github.com/opencv/opencv/issues/13154

현재 cv 이름의 가상 환경을 만든 후 일반 환경 구성으로 컴파일해 적용 테스트 중.

4. OpenCV 컴파일 및 설치
cat /proc/cpuinfo | grep processor | wc -l
time make -j4

Makefile:162: recipe for target 'all' failed
make clean
make
sudo make install

동적 라이브러리 설정 확인
cat /etc/ld.so.conf.d/*
/usr/local/lib ---> 존재 여부 확인

없을 경우 /usr/local/lib 동적 라이브러리 추가
sudo sh -c 'echo '/usr/local/lib' > /etc/ld.so.conf.d/opencv.conf'

적용.
sudo ldconfig

5. 확인
pkg-config --modversion opencv

6.심볼 링크 
가상 개발 환경
ls /usr/local/python/cv2/python-3.6/
cv2.cpython-36m-x86_64-linux-gnu.so

일반 개발 환경.
ls /usr/lib/lib/python3/dist-packages/
cv2.cpython-36m-x86_64-linux-gnu.so

이름 변경.
가상 개발 환경
cd /usr/local/python/cv2/python-3.6
sudo mv cv2.cpython-36m-x86_64-linux-gnu.so cv2.so

일반 개발 환경
cd /usr/lib/python3/dist-packages
이름 변경 없이 사용.

심볼 링크
가상 개발 환경
cd ~/.virtualenvs/cv/lib/python3.6/site-packages/ 
ln -s /usr/local/python/cv2/python-3.6/cv2.so cv2.so

일반 개발 환경
cd /usr/lib/python3/dist-packages
이름 변경 없이 사용

특정 버전의 개발 환경.
cv2.so 파일 이름을 변경해 관리한다.
cv2.so의 이름을 변경하는 대신, cv2.opencv3.4.4.so 사용.
심볼릭 링크에서 버전별로 적절하게 사용한다.

참고:
apt-get remove --purge 삭제시 cv2.so 파일 삭제 됨.
즉, 가상 환경에서는 문제 없시 동작, 만약 일반 환경에서도 동작 하기 위해서는 cv2.so 파일을 복사한다.
sudo cp /usr/local/python/cv2/python-2.7/cv2.so /usr/local/lib/python2.7/disk-packages/
sudo cp /usr/local/python/cv2/python-2.7/cv2.so /usr/lib/python2.7/disk-packages/

sudo cp /usr/local/python/cv2/python-Version/cv2.cpython-36m-x86_64-linux-gnu.so /usr/lib/pythonVersionVersionVersion/disk-packages/
sudo cp /usr/local/python/cv2/python3/cv2.cpython-36m-x86_64-linux-gnu.so /usr/local/lib/pythonVersionVersion3.6/disk-packages/

6 단계 : OpenCV 테스트
cd /home/username/
workon cv
python
>>> import cv2
>>> cv2.__version__
'4.0.0'