Python基礎雜點

 

 

Black Hat Python

 

Python Programming for Hackers and Pentesters
by 
Justin Seitz
December 2014, 192 pp.
ISBN-13: 
978-1-59327-590-7

「The difference between script kiddies and professionals is the difference between merely using other people's tools and writing your own.」
—Charlie Miller, from the Forewordhtml

Featured in ZDNet's list of "Cybersecurity reads for every hacker's bookshelf"node

When it comes to creating powerful and effective hacking tools, Python is the language of choice for most security analysts. But just how does the magic happen?python

In Black Hat Python, the latest from Justin Seitz (author of the best-selling Gray Hat Python), you’ll explore the darker side of Python’s capabilities—writing network sniffers, manipulating packets, infecting virtual machines, creating stealthy trojans, and more. You’ll learn how to:linux

  • Create a trojan command-and-control using GitHub
  • Detect sandboxing and automate com­mon malware tasks, like keylogging and screenshotting
  • Escalate Windows privileges with creative process control
  • Use offensive memory forensics tricks to retrieve password hashes and inject shellcode into a virtual machine
  • Extend the popular Burp Suite web-hacking tool
  • Abuse Windows COM automation to perform a man-in-the-browser attack
  • Exfiltrate data from a network most sneakily

Insider techniques and creative challenges throughout show you how to extend the hacks and how to write your own exploits.ios

When it comes to offensive security, your ability to create powerful tools on the fly is indispensable. Learn how in Black Hat Python.git

Uses Python 2web

Author Bio 

Justin Seitz is a senior security researcher for Immunity, Inc., where he spends his time bug hunting, reverse engineering, writing exploits, and coding Python. He is the author of Gray Hat Python (No Starch Press), the first book to cover Python for security analysis.正則表達式

Table of contents 

Introductionshell

Chapter 1: Setting Up Your Python Environment
Chapter 2: The Network: Basics
Chapter 3: The Network: Raw Sockets and Sniffing
Chapter 4: Owning the Network with Scapy
Chapter 5: Web Hackery
Chapter 6: Extending Burp Proxy
Chapter 7: GitHub Command and Control
Chapter 8: Common Trojaning Tasks on Windows
Chapter 9: Fun With Internet Explorer
Chapter 10: Windows Privilege Escalation
Chapter 11: Automating Offensive Forensicsexpress

Index

View the detailed Table of Contents (PDF)
View the Index (PDF)

Reviews 

"Another incredible Python book. With a minor tweak or two many of these programs will have at least a ten year shelf life, and that is rare for a security book."
—Stephen Northcutt, founding president of the SANS Technology Institute

"A great book using Python for offensive security purposes."
—Andrew Case, Volatility core developer and coauthor of The Art of Memory Forensics

"If you truly have a hacker’s mindset, a spark is all you need to make it your own and do something even more amazing. Justin Seitz offers plenty of sparks."
—Ethical Hacker (Read More)

"Whether you're interested in becoming a serious hacker/penetration tester or just want to know how they work, this book is one you need to read. Intense, technically sound, and eye-opening."
—Sandra Henry-Stocker, IT World (Read More)

"Definitely a recommended read for the technical security professional with some basic previous exposure to Python."
—Richard Austin, IEEE Cipher (Read More)

"A well-written book that will put you on track to being able to write powerful—and potentially scary—tools. It’s up to you to use them for good."
—Steve Mansfield-Devine, editor of Elsevier's Network Security Newsletter

"A well implemented read with lots of good ideas for fun offensive Python projects. So enjoy, and don't forget it's all about the code!"
—Dan Borges, LockBoxx

"A useful eye-opener."
—MagPi Magazine

Updates 

The download location for Kali Linux has changed. You can grab various virtual machines here:

https://www.offensive-security.com/kali-linux-vmware-arm-image-download/

 
 
 
 
 

import math

dir(math)    列出math全部的...

help(math.sin)          q  #退出

exit()   #退出命令行

---------------二進制存儲----------------

>>> 1.1+2.2
3.3000000000000003

由於二進制只能表示2的n次方的數,n能夠取負值,3.3沒法用2的n次方的數組合計算出來,因此沒法精確表示:3.3=1*2+1*1+0*1/2+1*1/4+0*1/8+0*1/16+1*1/32+...
其中分式的分母只能是2的倍數(二進制所限),3.3的二進制表示是11.01001.....
有些數好比1/3就沒法精確計算,只能無限逼近

 

 

bin()、oct()、hex()的返回值均爲字符串,且分別帶有0b、0o、0x前綴

---------------**冪次運算------------------------------

2**2**3      #  2的2次方的3次方  =256

‘abc’**3       # abc的三次方        = abcabcabc或者‘abcabcabc’

 -------------and or not--邏輯與或非  false true-----------優先級:非與或(由高到低----

123and456     #456 
123or456 #123

and: 若是全部值都爲真,那麼 and 返回最後一個值。

   若是某個值爲假,則 and 返回第一個假值。

or  若是有一個值爲真,or 馬上返回該值。

   若是全部的值都爲假,or 返回最後一個假值。

通俗講就是程序讀到哪裏可以被知足而後就能夠結束,而後返回最後的知足值。

>>> help('and')
Boolean operations
******************

or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test

In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: "False", "None", numeric zero of all types, and empty
strings and containers (including strings, tuples, lists,
dictionaries, sets and frozensets). All other values are interpreted
as true. (See the "__nonzero__()" special method for a way to change
this.)

The operator "not" yields "True" if its argument is false, "False"
otherwise.

The expression "x and y" first evaluates *x*; if *x* is false, its
value is returned; otherwise, *y* is evaluated and the resulting value
is returned.

The expression "x or y" first evaluates *x*; if *x* is true, its value
is returned; otherwise, *y* is evaluated and the resulting value is
-- More --

 -----------------------------標識符----

首:字母、下劃線

含:字母 下劃線 數字 不能關鍵字(查看關鍵字類型的    x = '10.0'  print type(x)        --程序結果--<type 'str'>)

 

標準【控制檯輸入輸出:  raw_input("prompts")   print

for instance

1.

pi = 3.14

radius = float(raw_input ('Radius:'))   #The default is a character string , here requires a cast float.

area = pi * radius ** 2

print area

----

2.

input =   raw_input()

>>>123

print input * 3

123123123

-----------------------------

input = int (raw_input())

>>>123

print input * 3

369

---------------------

數據量比較大時,使用生成器表達式     並不建立列表而是返回一個生成器    # ()

數據量不太大時,考慮使用列表解析      #{}

[i+1 for i in range(10)]

Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[i+1 for i in range(10) if i%2 == 0]
Out[2]: [1, 3, 5, 7, 9]

(i+1 for i in range(10) if i%2 == 0)
Out[3]: <generator object <genexpr> at 0x09B648C8>

 -----------------

from random import randint

 

x = randint(0,300)

for count in range(0,5):

print 'please input a number between 0~300:'

digit = input()

if digit == x:

print'Bingo!'

elif digit > x:

print'too lare!'

elif digit < x:

print'too small!'

 -------------------

哥德巴赫猜測

2-100 prime

 

 ----第二週測試---------

3填空(1分)
對於一元二次方程,如有 ,則其解是什麼?如有多個解,則按照從小到大的順序在一行中輸出,中間使用空格分隔。解保留2位小數(四捨五入)。

正確答案:-3.58 -0.42
4填空(1分)
假設你每一年初往銀行帳戶中1000元錢,銀行的年利率爲4.7%。
一年後,你的帳戶餘額爲:
1000 * ( 1 + 0.047) = 1047 元
第二年初你又存入1000元,則兩年後帳戶餘額爲:
(1047 + 1000) * ( 1 + 0.047) = 2143.209 元
以此類推,第10年年底,你的帳戶上有多少餘額?
注:結果保留2位小數(四捨五入)。

total = 0
for x in xrange(0,10):
  total = (total + 1000) * (1 + 0.047)
print total

  
正確答案:12986.11
5填空(1分)
Python提供了衆多的模塊。你能找到一個合適的模塊,輸出今天的日期嗎?格式爲「yyyy-mm-dd」。能夠查找任何搜索引擎和參考資料,並在下面的空白處寫出相應的模塊名。

正確答案:datetime 或 time 或 calendar

 

 

------------二分法求平方根-------

x = 2

low = 0

high = x

guess = (high+ low) / 2

while abs(guess ** 2 -x) >1e-4:

  if guess ** 2 > x:

    high = guess

  else :

    low  guess

 

guess = (low + high)/2

print "the root of x is :", guess

------

x<0?  

x<1?

ERROR: execution aborted

 

 ----------------------prime----

x = 8
for i in range(2,x):
if x % i == 0:
print'x is not a prime!'
break
else:
print'x is a prime'

---------------enhanced edition prime-

x = 8
for i in range (2, int(math.sqrt(x)+1)):
if x % i == 0:
print'x is not a prime!'
break
else:
print'x is a prime'

 

假設一個合數c(非素數)能夠因式分解成兩個大於其開方結果的數a,b

則有以下表達式:c=a*b

a*b>c

與假設c=a*b矛盾

因此假設不成立

即合數的因式分解時,至少有一個結果不大於該數開方結果。

不存在這個結果,就說明是素數。

------python格式等快捷鍵----

-----前50個素數-------

x = 2
count = 0

while count < 50:
for i in range(2,x):
if x%i == 0:
#print x,' is not a prime'
break
else:
print x,'is a prime!'
count += 1
x += 1

-------迴文數---

num = 123

num_p = 0

num_t = num

while num != 0:

  num_p = num_p * 10 + num% 10

  num = num / 10 

if num_t == num_p :

  print'yes!'

else:

  print'NO!'

------

 

 

  

 

----------------------先存着------------

Python | 靜覓
http://cuiqingcai.com/category/technique/python

零基礎寫python爬蟲之爬蟲編寫全記錄_python_腳本之家
http://www.jb51.net/article/57161.htm

--------------------------------------------

 

感受電腦神經兮兮的,明明下的正版,還一遍一個樣。。。。

媽賣批,剛纔真的試了好屢次不行,重啓,tm的就行了。。。。。

好吧,這種狀況不少軟件都會有,,,٩(๑òωó๑)۶

 

還有版本不一樣有些東西還真tm的徹底不一樣。。。。。

絕逼有問題,往右一動,再回來曾經被覆蓋的就不再出現了,媽賣批。。。。。

 

 

 

 

粘貼的正確姿式:

 

 ------------------------------

也不知這是進了什麼模式仍是安裝包有問題,真噁心。。。

 

 

------------------2運行不出來準備換3或者在虛擬機中運行----------------------

import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):
try:
r = requests.get(url,timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return""
#return""


def fillUnivList(ulist,html):
soup = BeautifulSoup(html,"html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[2].string])
#pass


def printUnivList(uList,num):
# print("Suc"+str(num))
print("{:^10}\t{:^6}\t{:^10}".format("排名","學校","總分"))
for i in range(num):
u = ulist[i]
print("{:^10}\t{:^6}\t{:^10}".format(u[0],u[1]),u[2])
#print("Suc"+str(num))


def main():
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20) # 20 univs
main()

------------------------------------------

如何打開requests庫get方法的源代碼?
-------------------------------
-------------若是有Python3你還用2 那我就呵呵呵了-----------

安裝Python3_沒毛病,就是不識字。。。。。
http://jingyan.baidu.com/article/a17d5285ed78e88098c8f222.html?st=2&net_type=&bd_page_type=1&os=0&rst=&word=www.10010

安裝python2-這個別用了除非你有毛病!!!還要配置環境變量,3貌似不用了,,,,
http://jingyan.baidu.com/article/7908e85c78c743af491ad261.html

 

3.6.1rc1 Documentation
https://docs.python.org/3.6/index.html

 

---------------------

慢的要死

-------------------

 

--------------------------

 

有坑-----------------------

 

----呵呵卸載了python立刻就行了-----

千萬別把兩個功能相同的軟件同時安裝,指不定就出什麼毛病,畢竟操做系統等等好多內容都不會

 

 -----------------------------------好特麼慢!!!!---------------------

 

 -----------------3.21------------------

conda list  列出自帶的庫

1.Python3

Q:

pip install scrapy(失敗!!!!)

A:

我安裝了一個C++ 14.0的編譯器,而後安裝就不報錯了
http://www.lfd.uci.edu/~gohlke/pythonlibs/這個網站上下載編譯好的庫

下載好的是一個whl文件

而後pip install xxx.whl就好了

 


把它放D盤,而後pip install D:\Scrapy-1.3.3-py2.py3-none-any.whl 


爲啥..我用whl仍是提示我沒有c庫..

那就須要安裝一下缺乏的庫了,我剛安裝完,而後再次pip install 就不報錯了

-------------------------

2.

anaconda

conda install scrapy(成)

 

 

 

--------------結論:版本不一樣,不少東西都tm不一樣----------------------要是本身玩,會死的很慘--------

 

 

------------Python3的33個關鍵字----------

-------------3.27.2017------

四種遍歷方式:

--------------

--------------------------------

Q: if __name__ == "__main__":

A:

__name__是指示當前py文件調用方式的方法。若是它等於"__main__"就表示是直接執行,若是不是,則用來被別的文件調用,這個時候if就爲False,那麼它就不會執行最外層的代碼了。
好比你有個Python文件裏面
def XXXX():
#body
print "asdf"
這樣的話,就算是別的地方導入這個文件,要調用這個XXXX函數,也會執行print "asdf",由於他是最外層代碼,或者叫作全局代碼。可是每每咱們但願只有我在執行這個文件的時候才運行一些代碼,不是的話(也就是被調用的話)那就不執行這些代碼,因此通常改成
def XXXX():
#body
if __name__="__main__":
print "asdf"

這個表示執行的是此代碼所在的文件。 若是這個文件是做爲模塊被其餘文件調用,不會執行這裏面的代碼。 只有執行這個文件時, if 裏面的語句纔會被執行。 這個功能常常能夠用於進行測試。

 

 

>>> import re
>>> match = re.match(r'[1-9]\d{5}','100081 BIT')
>>> if match:
... match.group(0)
...
'100081'
>>> print(match.group(1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: no such group

------------------------

>>> import re
>>> re.split(r'[1-9]\d{5}','BIT100032 BIO100067 BOF100025 BFC100027',maxsplit =2)
['BIT', ' BIO', ' BOF100025 BFC100027']
>>>

------------------------

>>> import re
>>> re.sub(r'[1-9]\d{5}',':zipcode','BIT100032 BIR100065 BSM123035')
'BIT:zipcode BIR:zipcode BSM:zipcode'


。即。
\. 即任意字符
【】裏只取一個字符
{n}前一字符重複n次

 

-------------------------

函數性用法:一次性操做

>>> rst = re.search(r'[1-9]\d{5}','BIT 100081')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 're' is not defined
>>> import re
>>> rst = re.search(r'[1-9]\d{5}','BIT 100081')
>>>
>>> rst
<_sre.SRE_Match object; span=(4, 10), match='100081'>
>>>

------------------------

 面向對象的用法:編譯後的屢次操做(regex可換成其餘英文變量表示)

 

re型字符串編譯成正則表達式類型生成regex對象;而後直接調用regex的search方法

>>> import re
>>> regex = re.compile(r'[1-9]\d{5}')
>>> rst = regex.search('BIT 100049')
>>>
>>> rst
<_sre.SRE_Match object; span=(4, 10), match='100049'>
>>>

 

 

相關文章
相關標籤/搜索