* 프로그램 요청이나 산출물 요청은 댓글로 달아주세요!

 

기다리고 기다리던 CVE SCRAPPER의 시현 시간이다. 개발정보는 -계획,진행-편에 들어있다.

2021.06.16 - [Python/Python Project] - [Python Project] CVE Scrapper 만들기 - 계획,진행-

 

[Python Project] CVE Scrapper 만들기 - 계획,진행-

블로그에 올릴 장기적인 프로그램을 만들고자 한다. 정보보안에 관심있는 필자이다 보니, 당연히 취약점에 눈이 들어오는건 당연하다. 속내를 말하자면 "와 이거 하루에 하나씩만 해도 한 3년은

tutoreducto.tistory.com

 


디렉토리 구조

이렇다. 코드 각각의 설명은 -기능도-편을 참고하자

2021.06.19 - [Python/Python Project] - [Python Project] CVE Scrapper 만들기 - 기능도-

 

[Python Project] CVE Scrapper 만들기 - 기능도-

코드별 클래스, 함수명에 대한 설명이다.

tutoreducto.tistory.com

 


시현

CveMain은 다음과 같이 실행된다. vendor의 목록은 cve_list directory에서 긁어온다. 

 

Make Report로 보고서를 만들 수 있다. Exported?가 True인 행은 Information dialog가 띄워지며 export가 안된다. exported 된 여부 판단은 export_cve directory에 해당 cve보고서가 존재하는지 여부로 판단한다.

export 된 보고서는 export_cve directory에서 찾을 수 있다.


OUTPUT

 

보고서는 다음과 같이 제작되어있다.

CVE-2010-4218.pdf
0.18MB


후기

짧은 프로젝트였다. 정식으로 뿌리는 것도 아니고, 디자인을 하나도 안 한 프로젝트였다. 찾아보니 TISTORY API가 있는 거 같은데, 이거 자동화해서 블로그에 보고서를 올리면 좋을 거 같다. 크롤링 코드와 gui를 연습할 수 있는 좋은 경험이었던 거 같다. fpdf를 사용하다 보니 편하다는 것을 느꼈다. body부분의 글자별 스타일 적용이 어렵다는 느낌은 받았지만 다음 자동화 프로젝트도 fpdf로 출력할 거 같다.

파이선에서 날짜에 대한 연산을 도와주는 calendar라는 모듈이다. 현실세계의 날짜 연산에서 사용될 수 있는 계산 함수들을 제공한다. 하나하나 알아보자


Calendar 객체

모든 날짜 연산은 캘린더 객체에서 이루어 진다. 객체는 다음과 같이 생성한다.

>>> my_cal = calendar.Calendar()
### Calendar(firstweekday=0)로 인자지정이 가능하다. firstweekday는 언제가 그 주의 시작요일인지 정하는 것이다)

Calendar객체가 제공하는 연산은 다음과 같다.

  • iterweekdays() : 0~6까지의 요일 인덱스를 담고 있는 iterator를 반환한다. firstweekday가 지정되어있으면 시작 순서가 바뀐다.
  • itermonthdays(year,month) : year년도의 month동안의 iterator를 반환한다. 그니까 itermonthdays(2020,12)면 2020년 12월의 일을 포함한 iterator를 반환하는 건데, 달력에 표기하기 위한 만큼의 넘어가는주와 넘어오는주를 포함해서 반환한다. 그때 값은 0이다.
  • itermonthdays2(year,month) : itermonthdays와 같은 범위이나, (일, 요일)의 튜플형태의 iterator를 반환한다.
  • itermonthdays3(year,month) : itermonthdays와 같은 범위이나, (년, 월, 일)의 튜플형태의 iterator를 반환한다.
  • itermonthdays4(year,month) : itermonthdays와 같은 범위이나, (년, 월, 일, 요일)의 튜플형태의 iterator를 반환한다.
  • monthdatescalendar(year,month) : itermonthdays와 같은 범위이나, 매일매일에 대한 datetime.date객체를 리스트로 반환한다.
  • monthdays2calendar(year,month) : itermonthdays와 같은 범위이나, 하루하루는 (일, 요일)의 튜플로, 주 단위로 리스트로 반환한다.
  • monthdayscalendar(year,month) : itermonthdays와 같은 범위이나, 주 단위 리스트로 반환한다
  • yeardatescalendar(year,width=3) : 연도에 대한 매일매일을 datetime.date객체로 월 단위 리스트로 반환한다. 이때 한 리스트원소에 얼만큼의 월이 들어갈지가 width이다.
  • yeardays2calendar(year,width=3) : 위와 유사하나 datetime.date객체는 아니고 요일이 포함된 튜플을 반환한다.
  • yeardayscalendar(year.width=3) : 위와 유사하나 datetime.date객체는 아니고 날짜만 해당하는 리스트를 반환한다.

 

 

TextCalendar 객체

Calendar는 숫자와 객체로 이루어져 있어 가시성이 떨어진다. 조금 보기 쉬운 표현을 위해서 TextCalendar라는 객체가 존재한다.

>>> my_cal = calendar.TextCalendar()
### TextCalendar(firstweekday=0)로 인자지정가능하다. firstweekday는 어디가 요일의 시작일지 이다.

TextCalendar 객체가 제공하는 연산은 다음과 같다.

  • formatmonth(theyear,themonth,w=0,l=0) : 해당 월의 달력을 출력한다. w, l로 달력 크기 지정을 한다.
  • prmonth(theyear,themonth,w=0,l=0) : formatmonth의 결과를 인쇄한다.
  • formatyear(theyear,w=2,l=1,c=6,m=3) : 해당 년도의 달력을 출력한다. w,l로 달력의 크기를, c로 월 사이사이의 공간의 크기를, m으로 몇 열로 출력할지를 정한다.
  • pryear(theyear,w=2,l=1,c=6,m=3) : formatyear의 결과를 인쇄한다.

 

 

HTMLCalendar 객체

HTMLCalendar은 HTML에서 사용할 수 있게끔 HTML 태그를 붙여준다. 

>>> my_cal = calendar.HTMLCalendar()
### HTMLCalendar(firstweekday=0)로 인자지정가능하다. firstweekday는 어디가 요일의 시작일지 이다.

TextCalendar 객체가 제공하는 연산은 다음과 같다.

  • formatmonth(theyear,themonth,withyear=True) : 월의 달력을 html Table로 반환한다. withyear의 설정으로 연도를 헤더에 표현할지를 선택할 수 있다.
  • formatyear(theyear,width=3) : 연도의 달력을 html Table로 반환한다. width는 행에 얼만큼의 월이 들어 갈지 이다.
  • formatyearpage(theyear,width=3,css='calendar.css',encoding=True) : 연도의 달력을 완전한 html로 생성한다. css를 지정할 수 있다.

* TextCalendar에는 css를 재정의 할 수 있도록 여러가지 Attrib도 있으니 사용이 필요하다면 포스팅 끝의 공식 문서를 참고바란다.

 

 

 

정적 매서드

다음은 calendar에서 제공하는 정적 매서드이다. Calendar.매서드명 으로 객체 생성 없이 이용 가능하다.

  • setfirstweekday(weekday) : 현재 import된 모듈의 calendar weekday를 weeday로 고정한다 주의 첫요일이 바뀐다. calendar에는 리터럴로 calendar.MONDAY등을 제공하니 사용 바란다.
  • firstweekday() : 요일의 현재 설정을 반환한다.
  • leapdays(y1,y2) : y1년과 y2년 사이의 윤년의 수를 반환한다.
  • weekday(year,month,day) : year년 month월 day일의 요일을 반환한다.
  • weekheader(n) : 요일의 헤더를 반환한다. n은 헤더의 길이이다(1 : "F", 3 : "Fri" 등)
  • monthrange(year,month) : year년 month월의 첫날의 요일과 월의 일수를 반환한다.
  • monthcalendar(year,month) : year년 month의 행렬을 반환한다.
  • month(theyear,themonth,w=0,l=0) : TextCalendar의 formatmonth를 바로 이용 가능하게 한다.
  • calendar(year,w=0,l=0,c=6,m=3) : TextCalendar의 formatyear를 바로 이용 가능하게 한다.

 

 

어트리뷰트

다음은 Calendar가 가진 클래스 어트리뷰트이다.

  • calendar.day_name : 현재 로케일의 요일을 나타내는 배열이다.
  • calendar.day_abbr : 현재 로케일의 약식 요일을 나타내는 배열이다.
  • calendar.month_name : 현재 로케일의 연중 월을 나타낸다.
  • calendar.mont_abbr : 현재 로케일의 연중 월을 약식으로 나타낸다.

 

* 출처 : https://docs.python.org/ko/3/library/calendar.html

 

calendar — 일반 달력 관련 함수 — Python 3.9.5 문서

calendar — 일반 달력 관련 함수 소스 코드: Lib/calendar.py 이 모듈을 사용하면 유닉스 cal 프로그램과 같은 달력을 출력할 수 있으며, 달력과 관련된 유용한 추가 함수를 제공합니다. 기본적으로, 이

docs.python.org


정적 매서드의 프린팅 함수는 제외하고 기술했다. 참고하도록 하자

Python을 손에서 놓은 지 한 달이 넘어가고 있다. 어쩔 수 없긴 했는데, 개발언어라는 것이 안 하고 있으면 까먹기 십상이니 조금 기억을 환기할 겸 Python Challenge를 시작하려고 한다,

http://www.pythonchallenge.com/index.php

 

The Python Challenge

What people have said about us: "These sorts of things are in my opinion the best way to learn a language.", brberg at Media Cloisters "It's the best web site of the year so far.", Andy Todd at halfcooked "Addictive way to learn the ins and outs of Python.

www.pythonchallenge.com

필자는 10단계 이상 가본 적이 없다 ㅋㅋㅋㅋㅋㅋㅋㅋ

이번에 공부하면서 공략 글을 올리고 내 실력도 조금 올려놔야 되겠다.

 

Python Challenge는 로그인이 없이 웹 파라미터를 가지고 Url을 이동하면서 문제풀이가 진행된다.(어? directory traversal이나 listing으로 2 ke2 ke 할 수 있나?)

네트워크를 사용해서 프로그래밍을 하다 보면 빼놓을 수 없는 부분이 이 MAC address이다. IP와 같이 쉽게 변경이 불가하고(ARP나 VM은 논외로 하자 자신의 NIC MAC 주소만 두고 보았을 때다.) 앞의 24bit를 이용해서 제조사까지 알아낼 수 있기 때문에, 많은 프로토콜에서 이 MAC Address를 사용한다. 이번 시간에는 getmac모듈과 함께 Python에서 MAC 주소를 알 수 있는 방법을 알아보자


1. Python에서 MAC 주소 가져오기 - GETMAC

getmac은 하나의 매소드만을 제공하는 Python 외장함수이다. >> pip3 install getmac으로 가져와야 한다.(3.X기준)

### getmac의 사용 ###
>>> import getmac

>>> getmac.get_mac_address()
'XX:XX:XX:XX:XX:XX'

간단한 내용이다. getmac의 구현부를 보면 다음과 같은 매서드 정의부를 확인할 수 있다.

def get_mac_address(
    interface=None, ip=None, ip6=None, hostname=None, network_request=True
):
    # type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
    """Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.

    You must only use one of the first four arguments. If none of the arguments
    are selected, the default network interface for the system will be used.

    Exceptions will be handled silently and returned as a None.
    For the time being, it assumes you are using Ethernet.

    NOTES:
    * You MUST provide str-typed arguments, REGARDLESS of Python version.
    * localhost/127.0.0.1 will always return '00:00:00:00:00:00'

    Args:
        interface (str): Name of a local network interface (e.g "Ethernet 3", "eth0", "ens32")
        ip (str): Canonical dotted decimal IPv4 address of a remote host (e.g 192.168.0.1)
        ip6 (str): Canonical shortened IPv6 address of a remote host (e.g ff02::1:ffe7:7f19)
        hostname (str): DNS hostname of a remote host (e.g "router1.mycorp.com", "localhost")
        network_request (bool): Send a UDP packet to a remote host to populate
        the ARP/NDP tables for IPv4/IPv6. The port this packet is sent to can
        be configured using the module variable `getmac.PORT`.
    Returns:
        Lowercase colon-separated MAC address, or None if one could not be
        found or there was an error.
    """

그니까 정리를 하면 NIC에 대한 이름과, mac주소를 가져올 단말기의 ipv4, v6 주소, DNS 호스트네임을 지정할 수 있다는 의미이다.

 

아래의 방법도 MAC Address를 가져오는데 많이 사용된다.

 

 

2. Python에서 MAC 주소 가져오기 - psutil

>>> import psutil
>>> nics = psutil.net_if_addrs()
### nics는 네트워크 정보를 가진 Dictionary가 된다. 보고 추출하면 된다.

psutil module은 프로세스 관리에 주로 사용된다. RAM이나, 스레드의 상태를 확인하고 변경하는데 특화되어있다. 그중 net_if_addr() 함수는 네트워크의 정보를 가져온다.

 

 

3. Python에서 MAC 주소 가져오기 - uuid

>>> import uuid
>>> a = uuid.getnode()
>>> mac = ':'.join(("%012X" % a)[i:i+2] for i in range(0, 12, 2))

사용할 일이 있을 때 퍼가면 좋을 거 같다. 

 

사실 백과사전이라 할 것까지는 없다. Python의 백과사전은 언제까지나 Github와 google일 것이다. pydoc은 Python document의 약자인데, Python에서 사용되는 Keyword, 내장 모듈 등의 설명서를 나타낸다. 크게 2가지 사용법을 알아보겠다.


사용법 - 1 Python 인터프리터로 해석 

필자는 Python개발도구로 IDLE을 보통 사용한다. IDLE에서 다음과 같은 코드를 입력하자

>>> import pydoc
>>> pydoc.help()

Welcome to Python 3.9's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help> 

pydoc에는 내장함수가 help하나 밖에 없다. help를 실행한 순간 help전용 대화형 인터프리터가 나온다. 예시로 yield 키워드를 help로 찾아보겠다.

help> yield
The "yield" statement
*********************

   yield_stmt ::= yield_expression

A "yield" statement is semantically equivalent to a yield expression.
The yield statement can be used to omit the parentheses that would
otherwise be required in the equivalent yield expression statement.
For example, the yield statements

   yield <expr>
   yield from <expr>

are equivalent to the yield expression statements

   (yield <expr>)
   (yield from <expr>)

Yield expressions and statements are only used when defining a
*generator* function, and are only used in the body of the generator
function.  Using yield in a function definition is sufficient to cause
that definition to create a generator function instead of a normal
function.

For full details of "yield" semantics, refer to the Yield expressions
section.

help> 

yield에 대한 사용법이 나온다. 리눅스 계열의 man명령어와 비슷하다고 볼 수 있겠다.  키워드 말고도 모듈도 검색할 수 있다.

help> pydoc
Help on module pydoc:

NAME
    pydoc - Generate Python documentation in HTML or text for interactive use.

MODULE REFERENCE
    https://docs.python.org/3.9/library/pydoc
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    At the Python interactive prompt, calling help(thing) on a Python object
    documents the object, and calling help() starts up an interactive
    help session.
    
    Or, at the shell command line outside of Python:
    
    Run "pydoc <name>" to show documentation on something.  <name> may be
    the name of a function, module, package, or a dotted reference to a
    class or function within a module or module in a package.  If the
    argument contains a path segment delimiter (e.g. slash on Unix,
    backslash on Windows) it is treated as the path to a Python source file.
    
    Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
    of all available modules.
    
    Run "pydoc -n <hostname>" to start an HTTP server with the given
    hostname (default: localhost) on the local machine.
    
    Run "pydoc -p <port>" to start an HTTP server on the given port on the
    local machine.  Port number 0 can be used to get an arbitrary unused port.
    
    Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
    open a Web browser to interactively browse documentation.  Combine with
    the -n and -p options to control the hostname and port used.
    
    Run "pydoc -w <name>" to write out the HTML documentation for a module
    to a file named "<name>.html".
    
    Module docs for core modules are assumed to be in
    
        https://docs.python.org/X.Y/library/
    
    This can be overridden by setting the PYTHONDOCS environment variable
    to a different URL or to a local directory containing the Library
    Reference Manual pages.

DATA
    __all__ = ['help']
    help = <pydoc.Helper instance>

DATE
    26 February 2001

AUTHOR
    Ka-Ping Yee <ping@lfw.org>

CREDITS
    Guido van Rossum, for an excellent programming language.
    Tommy Burnette, the original creator of manpy.
    Paul Prescod, for all his work on onlinehelp.
    Richard Chamberlain, for the first implementation of textdoc.

FILE

이런 식으로 말이다.

 

사용법 - 2 웹페이지를 사용

웹페이지를 호스팅 하여 pydoc을 활용할 수 있다. python 2.X에는 pydocgui라는 tkinter(python의 gui프로그래밍을 도와주는 모듈)로 제작된 별도의 모듈이 있었는데, 3.X 버전부터는 명령 프롬포트에 다음과 같은 명령으로 localhost에 웹페이지를 호스팅 한다.

C:\Users>python -m pydoc -p 12345

이렇게 하면 12345번 포트인 http://localhost:12345에 python documentation이 호스팅 된다. 내부는 이런 모습이다.


자! 이번 시간에는 python의 백과사전인 pydoc에 대해서 알아보았다. 물론 대부분의 경우 공식 API홈페이지나 Github의 형님들의 힘을 빌리겠지만, 네트워크가 안 되는 상황이나, 구글 신의 힘을 빌려도 잘 모르겠는 사용법은 같이 참고할 수 있으면 좋다. 

* 여담인데, pydoc에 문법에 맞추어 내가 추가한 모듈의 사용법을 추가할 수도 있다. 물론 pydoc은 로컬에 한정한다.

Python도 역시 여러 가지 웹 기능을 제공한다. socket과 같은 네트워킹 목적으로 python을 사용하는 사람도 있고, httplib나 requests처럼 특정 사이트와의 패킷 교환을 담당해 주는 라이브러리가 그 대표적인 예시라고 할 수 있겠다. 이번 시간에는 그중 조금 독특한, 네트워크를 컴퓨터 환경에 맞게 사용할 수 있게 해주는 webbrowser를 알아보자


목적

webbrowser 모듈은 웹 기반 문서를 사용자에게 표시할 수 있는 고수준 인터페이스를 제공합니다. 대부분은, 이 모듈의 open() 함수를 호출하면 올바른 작업이 수행됩니다.

- Python 공식 홈페이지 https://docs.python.org/ko/3/library/webbrowser.html -

간단하게 말하면, 내 컴퓨터 환경에 맞추어 웹 통신을 할 수 있게 해준다는 이야기이다.

다음의 코드를 따라 쳐보자

>>> import webbrowser
>>> webbrowser.open("www.google.com")
True

이러면 기본으로 지정된 브라우저로 www.google.com이 열린다. 

 

webbrowser의 제공함수

webbrowser는 다음과 같은 내 컴퓨터에 사용되는 웹 브라우저를 통한 웹 기능을 제공한다.

1. webbrowser.open(url, new=0, autoraise=True) : 웹브라우저로 url을 open한다.

 - url : open할 url

 - new : 1이면 가능한 새로운 브라우저가 open 2면 탭으로 추가됨

 - autoraise 가 True면 창이 올라간다.(최대화같은데 모르겠다. 변화가 없더라)

1-1. webbrowser.open_new(url) : webborowser.open(url,new=1)과 같다.

1-2. webbrowser.open_new_tab(url) : webbrowser.open(url,new=2)와 같다.

2. webbrowser.register(name, constructor, instance, *, preferred=False) : 기본으로 열릴 브라우저를 선택한다. 기본 브라우저는 아래 공식 API를 참조하기 바란다.

docs.python.org/ko/3/library/webbrowser.html

 

webbrowser — 편리한 웹 브라우저 제어기 — Python 3.9.4 문서

webbrowser — 편리한 웹 브라우저 제어기 소스 코드: Lib/webbrowser.py webbrowser 모듈은 웹 기반 문서를 사용자에게 표시할 수 있는 고수준 인터페이스를 제공합니다. 대부분은, 이 모듈의 open() 함수를

docs.python.org

 

제어기 객체

webbrowser는 브라우저를 열어줄 제어기(Controller) 객체를 이용할 수 있다.

### webbrowser와 소통할 수 있는 controller를 가져온다. 
### controller는 webbrowser가 제공하는 위의 기능을 모두 사용할 수 있다. 
>>> controller = webbrowser.get()

 

 

* 출처 : Python API Webbrowser docs.python.org/ko/3/library/webbrowser.html

 

webbrowser — 편리한 웹 브라우저 제어기 — Python 3.9.4 문서

webbrowser — 편리한 웹 브라우저 제어기 소스 코드: Lib/webbrowser.py webbrowser 모듈은 웹 기반 문서를 사용자에게 표시할 수 있는 고수준 인터페이스를 제공합니다. 대부분은, 이 모듈의 open() 함수를

docs.python.org


이번 모듈 탐구 시간에 처음으로 네트워크를 사용한 Python을 써본 거 같다. webbrowser가 사용되는 경우가 흔한 상황은 아닌데, 쓸 때 기억이 안 나면 짜증 나긴 한다.

+ Recent posts