반응형

출처 : https://stackoverflow.com/questions/27981545/suppress-insecurerequestwarning-unverified-https-request-is-being-made-in-pytho


python 으로 https 요청을 하는데... https 라서 ssl 인증서를 검증받는다..

그래서 

requests.post(url, data, verify=False)

라고 옵션을 넣어서 검증을 하지 않도록 한다.


그랬더니 실행이 될때마다 system warning 메세지가 자꾸 뜬다..

Unverified HTTPS Request......


request is being made to host '192.168.1.100'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

  InsecureRequestWarning,


error

InsecureRequestWarning 이라고 시스템 에러가 자꾸 발생한다.

처음엔 그냥 냅뒀는데.. 시간이 지나고 보니 뭔가 계속 뜨는게 신경쓰였다..;;;;

그!래!서!

이걸 안뜨게 싶어서 검색을 좀 해봤더니.. 방법을 겟!! 


#impport urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


에러가 나는 urllib3 에서 insecureRequestWarning 메세지를 예외처리(except)하는 방법이 있었음..!!

반응형
반응형

fortigate automation using rest api python 모듈


늘 누가 만들어둔것에 감사를

조금만 수정해서 쓰거나 기본 양식을 활용하여 만들거나..


굿

반응형

'작업공간 > Tool' 카테고리의 다른 글

paloalto rest api with python  (0) 2020.04.29
안드로이드 디컴파일러(유료)  (2) 2013.02.13
Malware Crawler  (0) 2013.02.12
Retina Free Network Scanner  (2) 2011.04.07
xwodi  (0) 2011.02.28
반응형

사설SSL 인증서(certificate)을 이용하여 서비스 중인 사이트에 요청을 하게되면.. 인증서를 확인할 수 없다고 에러가 많이 뜨죠


그래서

1. python 으로 request할때 ssl cert verification 안하도록 검증 안하도록 하는 방법  (요기 링크)

을 썼었고

2. curl을 쓸때도 마찬가지로 ssl cert를 검증 안하도록 -k 옵션을 넣는 방법 (요기 링크)

도 있었죠


근데.. 이러지 않아도 될 것 같아요

혹시 모르니 코딩상에는 저렇게 해놓고

서비스 시작할때 환경변수를 아래와 같이 설정하면 될 것 같습니다.


2번째 방법도 아래 환경변수를 추가하면 먹히는지 모르겠네요

pythonhttpsverify라는 환경변수값을 0으로 설정하면 python 에서는 검증을 안하도록 기본 설정이 되더라고요! 굿굿


저는 .service 파일에 배치파일을 실행하게하고 그 전에 환경변수를 추가하도록 했습니다.

끄읏. finish


export PYTHONHTTPSVERIFY=0


반응형
반응형

paloalto rest api를 사용해서 일단 시스템 리소스 확인하는 거 완성하고

PRTG에 알람 발생시 mattermost 로 incomming webhook에 전송하는걸.. 하려고 했으나..  그게 지원이 좀 힘들어서

arcsight 로 syslog 전송하고 syslog받으면 arcsight에서 내부 sh을 실행하고.. sh 에는 python 파일을 실행하도록 해놓고..

python 은 전달받은 파라메터를 이용하여 mattermost 로 전송

mattermost는 push로 담당자에게 전달..

그리고 다시 또 메세지를 띄우고 incomming webhook으로 다시 전송해서

메세지 분석해서 띄워놓은 python bot에서 추가 rest api를 호출해서 시스템 자원 확인해서 다시 mattermost 에게 전달.. 그 후 다시 담당자에게 push..


일단 여기까지 하려고 하는데

paloalto -> PRTG -> Arcsight -> sh실행 -> python 실행 -> mattermost -> push and incomming webhook -> python bot -> push


paloalto rest api 를 python bot에서 호출해야되니 key 받아서 호출하고.. 필요한 리소스들 가져오는 것까지 짰는데..


python - paloalto rest api module (클릭)


맙소사..

이런게 있었네요...

이미 모듈화가 있었어요 ㅠㅠㅠ 된장....

괜히 고생했어.... ㅠㅠ


[yad2nus@VM mattermost]$ panxapi.py --help

panxapi.py [options] [xpath]

    -d                    delete object at xpath

    -e element            edit XML element at xpath

    -g                    get candidate config at xpath

    -k                    generate API key

    -s                    show active config at xpath

    -S element            set XML element at xpath

    -U cmd                execute dynamic update command

    -C cmd                commit candidate configuration

    --validate            validate candidate configuration

    --force               force commit when conflict

    --partial part        commit specified part

    --sync                synchronous commit

    -A cmd                commit-all (Panorama)

    --ad-hoc query        perform ad hoc request

    --modify              insert known fields in ad hoc query

    -o cmd                execute operational command

    --export category     export files

    --log log-type        retrieve log files

    --report report-type  retrieve reports (dynamic|predefined|custom)

    --name report-name    report name

    --src src             clone source node xpath

                          export source file/path/directory

    --dst dst             move/clone destination node name

                          rename new name

                          export destination file/path/directory

    --move where          move after, before, bottom or top

    --rename              rename object at xpath to dst

    --clone               clone object at xpath, src xpath

    --override element    override template object at xpath

    --vsys vsys           VSYS for dynamic update/partial commit/

                          operational command/report

    -l api_username[:api_password]

    -h hostname

    -P port               URL port number

    --serial number       serial number for Panorama redirection/

                          commit-all/threat-pcap

    --group name          device group for commit-all

    --merge               merge with candidate for commit-all

    --nlogs num           retrieve num logs

    --skip num            skip num logs

    --filter filter       log selection filter

    --interval seconds    log/commit/report job query interval

    --timeout seconds     log/commit/report job query timeout

    --stime time          search time for threat-pcap

    --pcapid id           threat-pcap ID

    -K api_key

    -x                    print XML response to stdout

    -p                    print XML response in Python to stdout

    -j                    print XML response in JSON to stdout

    -r                    print result content when printing response

    --text                print text response to stdout

    -X                    convert text command to XML

    --ls                  print formatted PCAP listing to stdout

    --recursive           recursive export

    -H                    use http URL scheme (default https)

    -G                    use HTTP GET method (default POST)

    -D                    enable debug (multiple up to -DDD)

    -t tag                .panrc tagname

    -T seconds            urlopen() timeout

    --cafile path         file containing CA certificates

    --capath path         directory of hashed certificate files

    --version             display version

    --help                display usage


반응형

'작업공간 > Tool' 카테고리의 다른 글

fortigate automation using rest api python 모듈  (0) 2020.04.30
안드로이드 디컴파일러(유료)  (2) 2013.02.13
Malware Crawler  (0) 2013.02.12
Retina Free Network Scanner  (2) 2011.04.07
xwodi  (0) 2011.02.28
반응형

python을 이용한 xml 사이트 파싱 


인터넷 검색하면 죄다 xml  파일을 파싱하는 것만 나옵니다...

순간 저도 혹해서 xml 파일을 다운로드 받아서 저장하고 저장된 파일을 파싱하려고 했는데

너무 불필요한 IO가 일어나는게 싫었습니다..


근데 이게 참 안되네요..


처음엔

import requests

import xml.etree.ElementTree as elementTree


url = 'https://blabla..'

이렇게 받은 이후

elementTree.parse(url)

이렇게 하니 안됩니다.....

elementTree.parse에 들어가는 변수는 url이 아니라 filename 이랍니다.. 저장된 파일이름...


이제 다른 방버을 찾아봅니다..

docs를 찾아보니까 data일때는 elementTree.fromstring() 으로 변환을 시켜줘야 한다고 합니다.

root = elementTree.formstring(requests.get(url, verify=False).text)

이런 방식으로 requests.get 을 통해 웹페이지를 string 형태로 받아서 string 을 elementTree 형태로 변경해 줍니다.


여기서 또 2시간 정도 삽질을 했는데.. docs를 잘 안본 제 탓이죠.. ㅠㅠ

보면 2가지 방법으로 값을 가져올 수 있는데 하나는 [] 로, 하나는 find 같은 함수를 이용하는 방법이 나옵니다.


당연히 편한 find()나 findtext() 함수를 사용하였으나 안됩니다.. none을 반환하네요...

찾아보니 none 은 값을 못찾을때 return 한다고 합니다..


그래서 이번엔 배열 방식인 []로 찾아봅니다..


print(root[0][0].text) 이런식!!

잘찾아오네요..? -_-;;


도대체 왜 find 함수를 쓰면 안되는거냐!! 고 엄청나게 헤매던 그때..

docs 페이지를 더 아래로 내리니...

xpathpython xpath xml parse

이렇게 나오네요....

와.. 순간 화가 확.. ㅠㅠ

이걸 왜 못봤을까요...


string 형식을 elementTree 형태로 변환을 했기 때문에 당연히 find로 할 수 있는 줄 알았는데.. ㅠㅠ

XPATH 방식으로 처리가 가능합니다..


저렇게 find를 쓰되, parse()로 분석했을때는 해당 element 이름만 적으면 되는 반면

string을 변환하여 사용할때는 xpath 방식으로 find(.//element name) 형식으로 찾을 수 있습니다


결론. XPATH 형태로 호출하면 된다


반응형
반응형

python 으로 https 사이트 응답값을 받아올때 못받아 오는 경우들이 있습니다.

보면 대부분 ssl 인증서 문제죠


OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 672, in urlopen

    chunked=chunked,

  File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 376, in _make_request

    self._validate_conn(conn)

  File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 994, in _validate_conn

    conn.connect()

  File "/usr/local/lib/python3.6/site-packages/urllib3/connection.py", line 360, in connect

    ssl_context=context,

  File "/usr/local/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 383, in ssl_wrap_socket

    return context.wrap_socket(sock)

  File "/usr/local/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 491, in wrap_socket

    raise ssl.SSLError("bad handshake: %r" % e)

ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)


내부 시스템 REST API를 호출하기 위해서 호출을 하면.. 100%죠.. 

보통 내부 시스템들은 local 인증서를 쓰기 때문입니다.


앞에서 curl 로 -k 옵션으로 인증서를 무시하는 게 있었던거.. 기억나시나요?


python 에서 requests 모듈에도 그런 옵션이 있습니다.

reqeust ssl cert verificationpython 에서 requests 모듈을 사용 시 ssl 인증을 무시하는 방법

requests 모듈 사이트에서 가져온 화면 입니다.


보면 reqeusts.get(url, verify=False) 로 해결할 수 있는 것을 확인할 수 있습니다.


끝.

반응형
반응형

Nullege is a search engine for Python source code.


http://nullege.com/


파이썬 코드를 검색할 수 있는 사이트.

MSDN 같은 느낌이라 참 좋다.

반응형

'작업공간 > 기본적인 삽질 & 기록' 카테고리의 다른 글

2012년 12월 19일 해커와의 대화  (2) 2013.01.10
Secuinside 예선  (0) 2012.06.11
Cool Messenger 연구  (0) 2012.04.24
롯데마트에선 안파는게 없군요.  (0) 2012.04.23
음?? 당했나?  (3) 2012.03.15
반응형


펌 : http://dirk-loss.de/python-tools.htm



If you are involved in vulnerability research, reverse engineering or penetration testing, I suggest to try out the Python programming language. It has a rich set of useful libraries and programs. This page lists some of them.

Most of the listed tools are written in Python, others are just Python bindings for existing C libraries, i.e. they make those libraries easily usable from Python programs.

Some of the more aggressive tools (pentest frameworks, bluetooth smashers, web application vulnerability scanners, war-dialers, etc.) are left out, because the legal situation of these tools is still a bit unclear in Germany -- even after the decision of the highest court. This list is clearly meant to help whitehats, and for now I prefer to err on the safe side.

Network

  • Scapy: send, sniff and dissect and forge network packets. Usable interactively or as a library
  • pypcap, Pcapy and pylibpcap: several different Python bindings for libpcap
  • libdnet: low-level networking routines, including interface lookup and Ethernet frame transmission
  • dpkt: fast, simple packet creation/parsing, with definitions for the basic TCP/IP protocols
  • Impacket: craft and decode network packets. Includes support for higher-level protocols such as NMB and SMB
  • pynids: libnids wrapper offering sniffing, IP defragmentation, TCP stream reassembly and port scan detection
  • Dirtbags py-pcap: read pcap files without libpcap
  • flowgrep: grep through packet payloads using regular expressions
  • httplib2: comprehensive HTTP client library that supports many features left out of other HTTP libraries

Debugging and reverse engineering

  • Paimei: reverse engineering framework, includes PyDBG, PIDA, pGRAPH
  • Immunity Debugger: scriptable GUI and command line debugger
  • IDAPython: IDA Pro plugin that integrates the Python programming language, allowing scripts to run in IDA Pro
  • PyEMU: fully scriptable IA-32 emulator, useful for malware analysis
  • pefile: read and work with Portable Executable (aka PE) files
  • pydasm: Python interface to the libdasm x86 disassembling library
  • PyDbgEng: Python wrapper for the Microsoft Windows Debugging Engine
  • uhooker: intercept calls to API calls inside DLLs, and also arbitrary addresses within the executable file in memory
  • diStorm64: disassembler library for AMD64, licensed under the BSD license
  • python-ptrace: debugger using ptrace (Linux, BSD and Darwin system call to trace processes) written in Python

Fuzzing

  • Sulley: fuzzer development and fuzz testing framework consisting of multiple extensible components
  • Peach Fuzzing Platform: extensible fuzzing framework for generation and mutation based fuzzing
  • antiparser: fuzz testing and fault injection API
  • TAOF, including ProxyFuzz, a man-in-the-middle non-deterministic network fuzzer
  • untidy: general purpose XML fuzzer
  • Powerfuzzer: highly automated and fully customizable web fuzzer (HTTP protocol based application fuzzer)
  • FileP: file fuzzer. Generates mutated files from a list of source files and feeds them to an external program in batches
  • SMUDGE
  • Mistress: probe file formats on the fly and protocols with malformed data, based on pre-defined patterns
  • Fuzzbox: multi-codec media fuzzer
  • Forensic Fuzzing Tools: generate fuzzed files, fuzzed file systems, and file systems containing fuzzed files in order to test the robustness of forensics tools and examination systems
  • Windows IPC Fuzzing Tools: tools used to fuzz applications that use Windows Interprocess Communication mechanisms
  • WSBang: perform automated security testing of SOAP based web services
  • Construct: library for parsing and building of data structures (binary or textual). Define your data structures in a declarative manner
  • fuzzer.py (feliam): simple fuzzer by Felipe Andres anzano

Web

  • ProxMon: processes proxy logs and reports discovered issues
  • WSMap: find web service endpoints and discovery files
  • Twill: browse the Web from a command-line interface. Supports automated Web testing
  • Windmill: web testing tool designed to let you painlessly automate and debug your web application
  • FunkLoad: functional and load web tester

Forensics

  • Volatility: extract digital artifacts from volatile memory (RAM) samples
  • SandMan: read the hibernation file, regardless of Windows version
  • LibForensics: library for developing digital forensics applications
  • TrIDLib, identify file types from their binary signatures. Now includes Python binding

Malware analysis

  • pyew: command line hexadecimal editor and disassembler, mainly to analyze malware
  • Didier Stevens' PDF tools: analyse, identify and create PDF files (includes PDFiD, pdf-parser and make-pdf and mPDF)
  • Origapy: Python wrapper for the Origami Ruby module which sanitizes PDF files
  • Exefilter: filter file formats in e-mails, web pages or files. Detects many common file formats and can remove active content
  • pyClamAV: add virus detection capabilities to your Python software

Misc

  • InlineEgg: toolbox of classes for writing small assembly programs in Python
  • Exomind: framework for building decorated graphs and developing open-source intelligence modules and ideas, centered on social network services, search engines and instant messaging
  • RevHosts: enumerate virtual hosts for a given IP address
  • simplejson: JSON encoder/decoder, e.g. to use Google's AJAX API

Other useful libraries and tools

  • IPython: enhanced interactive Python shell with many features for object introspection, system shell access, and its own special command system
  • Beautiful Soup: HTML parser optimized for screen-scraping
  • matplotlib: make 2D plots of arrays
  • Mayavi: 3D scientific data visualization and plotting
  • RTGraph3D: create dynamic graphs in 3D
  • Twisted: event-driven networking engine
  • Suds: lightweight SOAP client for consuming Web Services
  • M2Crypto: most complete OpenSSL wrapper
  • NetworkX: graph library (edges, nodes)
  • pyparsing: general parsing module
  • lxml: most feature-rich and easy-to-use library for working with XML and HTML in the Python language
  • Pexpect: control and automate other programs, similar to Don Libes `Expect` system
  • Sikuli, visual technology to search and automate GUIs using screenshots. Scriptable in Jython

반응형

+ Recent posts