byrefpython
⑴ python怎麼修改某個內存地址的數據
使用ctypes模塊調用WriteProcessMemory函數,在創建程序進程後,就可以修改該程序指定內存地址。WriteProcessMemory的函數原型如下所示。
BOOL WriteProcessMemory(
HANDLE hProcess,
LPVOID lpBaseAddress,
LPCVOID lpBuffer,
SIZE_T nSize,
SIZE_T* lpNumberOfBytesWritten
);
其參數含義如下。
· hProcess:要寫內存的進程句柄。
· lpBaseAddress:要寫的內存起始地址。
· lpBuffer:寫入值的地址。
· nSize:寫入值的大小。
· lpNumberOfBytesWritten :實際寫入的大小。
python代碼示例如下:
fromctypesimport*
#定義_PROCESS_INFORMATION結構體
class_PROCESS_INFORMATION(Structure):
_fields_=[('hProcess',c_void_p),
('hThread',c_void_p),
('dwProcessId',c_ulong),
('dwThreadId',c_ulong)]
#定義_STARTUPINFO結構體
class_STARTUPINFO(Structure):
_fields_=[('cb',c_ulong),
('lpReserved',c_char_p),
('lpDesktop',c_char_p),
('lpTitle',c_char_p),
('dwX',c_ulong),
('dwY',c_ulong),
('dwXSize',c_ulong),
('dwYSize',c_ulong),
('dwXCountChars',c_ulong),
('dwYCountChars',c_ulong),
('dwFillAttribute',c_ulong),
('dwFlags',c_ulong),
('wShowWindow',c_ushort),
('cbReserved2',c_ushort),
('lpReserved2',c_char_p),
('hStdInput',c_ulong),
('hStdOutput',c_ulong),
('hStdError',c_ulong)]
NORMAL_PRIORITY_CLASS=0x00000020#定義NORMAL_PRIORITY_CLASS
kernel32=windll.LoadLibrary("kernel32.dll")#載入kernel32.dll
CreateProcess=kernel32.CreateProcessA#獲得CreateProcess函數地址
ReadProcessMemory=kernel32.ReadProcessMemory#獲得ReadProcessMemory函數地址
WriteProcessMemory=kernel32.WriteProcessMemory#獲得WriteProcessMemory函數地址
TerminateProcess=kernel32.TerminateProcess
#聲明結構體
ProcessInfo=_PROCESS_INFORMATION()
StartupInfo=_STARTUPINFO()
file='ModifyMe.exe'#要進行修改的文件
address=0x0040103c#要修改的內存地址
buffer=c_char_p("_")#緩沖區地址
bytesRead=c_ulong(0)#讀入的位元組數
bufferSize=len(buffer.value)#緩沖區大小
#創建進程
ifCreateProcess(file,0,0,0,0,NORMAL_PRIORITY_CLASS,0,0,byref(StartupInfo),byref(ProcessInfo)):
#讀取要修改的內存地址,以判斷是否是要修改的文件
ifReadProcessMemory(ProcessInfo.hProcess,address,buffer,bufferSize,byref(bytesRead)):
ifbuffer.value=='x74':
buffer.value='x75'#修改緩沖區內的值,將其寫入內存
#修改內存
ifWriteProcessMemory(ProcessInfo.hProcess,address,buffer,bufferSize,byref(bytesRead)):
print'成功改寫內存!'
else:
print'寫內存錯誤!'
else:
print'打開了錯誤的文件!'
TerminateProcess(ProcessInfo.hProcess,0)#如果不是要修改的文件,則終止進程
else:
print'讀內存錯誤!'
else:
print'不能創建進程!'
⑵ python怎麼調用c的動態鏈接庫
Python調用C/C++動態鏈接庫的需求
在自動化測試過程中,難免會遇到語言混合使用的情況,這不,我們也遇到了。初步決定採用Robot Framework作為自動化測試框架後,其支持Java和Python,而Python作為主流的語言,怎麼能放棄使用它的機會^_^。 然而產品採用是古老90年代開發的C/S結構,因為古老,當時也沒有考慮到對產品的測試進行自動化,Client端並沒有預留CLI(Command Line interface)形式的介面,真是雪上加霜啊。
那怎麼自動化?採用AutoIT來對客戶端界面進行自動化測試?可惜AutoIT對當初開發採用的控制項識別不是很好,如果採用控制項所在位置來進行控制的方式,又會導致自動化測試並不是很穩定。那麼!!!只有自己開發介面了,目前在Client端開發出CLI形式的介面,將其封裝為DLL,然後在Robot FrameWork框架中採用Python對DLL進行調用。任務艱巨哪!
Python調用DLL例子
示例一
首先,在創建一個DLL工程(本人是在VS 2005中創建),頭文件:
[cpp] view plain 在CODE上查看代碼片派生到我的代碼片//hello.h
#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif
extern "C"
{
HELLO_API int IntAdd(int , int);
}
CPP文件:
[cpp] view plain 在CODE上查看代碼片派生到我的代碼片//hello.cpp
#define EXPORT_HELLO_DLL
#include "hello.h"
HELLO_API int IntAdd(int a, int b)
{
return a + b;
}
這里有兩個注意點:
(1)弄清楚編譯的時候函數的調用約定採用的__cdecl還是__stdcall,因為根據DLL中函數調用約定方式,Python將使用相應的函數載入DLL。
(2)如果採用C++的工程,那麼導出的介面需要extern "C",這樣python中才能識別導出的函數。
我的工程中採用__cdecl函數調用約定方式進行編譯鏈接產生hello.dll,然後Python中採用ctypes庫對hello.dll進行載入和函數調用:
[python] view plain 在CODE上查看代碼片派生到我的代碼片from ctypes import *
dll = cdll.LoadLibrary('hello.dll');
ret = dll.IntAdd(2, 4);
print ret;
OK,一個小例子已經完成了,如果你感興趣,但還沒試過,那就嘗試一下吧。
示例二
示例一隻是一個"hello world"級別的程序,實際運用中更多的需要傳遞數據結構、字元串等,才能滿足我們的需求。那麼這個示例將展示,如何傳遞數據結構參數,以及如何通過數據結構獲取返回值。
首先編寫DLL工程中的頭文件:
[cpp] view plain 在CODE上查看代碼片派生到我的代碼片//hello.h
#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif
#define ARRAY_NUMBER 20
#define STR_LEN 20
struct StructTest
{
int number;
char* pChar;
char str[STR_LEN];
int iArray[ARRAY_NUMBER];
};
extern "C"
{
//HELLO_API int IntAdd(int , int);
HELLO_API char* GetStructInfo(struct StructTest* pStruct);}
CPP文件如下:
[cpp] view plain 在CODE上查看代碼片派生到我的代碼片//hello.cpp
#include <string.h>
#define EXPORT_HELLO_DLL
#include "hello.h"
HELLO_API char* GetStructInfo(struct StructTest* pStruct){
for (int i = 0; i < ARRAY_NUMBER; i++)
pStruct->iArray[i] = i;
pStruct->pChar = "hello python!";
strcpy (pStruct->str, "hello world!");
pStruct->number = 100;
return "just OK";
}
GetStructInfo這個函數通過傳遞一個StructTest類型的指針,然後對對象中的屬性進行賦值,最後返回"just OK".
編寫Python調用代碼如下,首先在Python中繼承Structure構造一個和C DLL中一致的數據結構StructTest,然後設置函數GetStructInfo的參數類型和返回值類型,最後創建一個StructTest對象,並將其轉化為指針作為參數,調用函數GetStrcutInfo,最後通過輸出數據結構的值來檢查是否調用成功:
[python] view plain 在CODE上查看代碼片派生到我的代碼片from ctypes import *
ARRAY_NUMBER = 20;
STR_LEN = 20;
#define type
INTARRAY20 = c_int * ARRAY_NUMBER;
CHARARRAY20 = c_char * STR_LEN;
#define struct
class StructTest(Structure):
_fields_ = [
("number", c_int),
("pChar", c_char_p),
("str", CHARARRAY20),
("iArray", INTARRAY20)
]
#load dll and get the function object
dll = cdll.LoadLibrary('hello.dll');
GetStructInfo = dll.GetStructInfo;
#set the return type
GetStructInfo.restype = c_char_p;
#set the argtypes
GetStructInfo.argtypes = [POINTER(StructTest)];objectStruct = StructTest();
#invoke api GetStructInfo
retStr = GetStructInfo(byref(objectStruct));#check result
print "number: ", objectStruct.number;
print "pChar: ", objectStruct.pChar;
print "str: ", objectStruct.str;
for i,val in enumerate(objectStruct.iArray):
print 'Array[i]: ', val;
print retStr;
總結
1. 用64位的Python去載入32位的DLL會出錯
2. 以上只是些測試程序,在編寫Python過程中盡可能的使用"try Except"來處理異常3. 注意在Python與C DLL交互的時候位元組對齊問題4. ctypes庫的功能還有待繼續探索
⑶ 我在網上找到的用python寫的在windows下控制滑鼠的操作,求高手講解一下這個代碼,本人新手,看不懂~~
這個就是直接用的winapi,你到msdn上搜相應的函數就知道了。
⑷ python byref是指針嗎
handle = ctypes.c_int(0) ret = lib.XF_OpenDev(0, ctypes.byref(handle)) handle作為指針傳進去後如果被改掉,返回的是一個c_int 或者c_long, 你可以通過handle.value來獲得可以在python中靈活運用的真正的python整形
⑸ python3.2 下的抓包庫。。無論是pypcap還是scapy。貌似都沒有py3的版本。。跪求一個可以python3用
有一個py3kcap是pycap的封裝版本,可以用於python3版本。
給你一個使用的示例代碼:
#!/usr/bin/env python3.2
import ctypes,sys
from ctypes.util import find_library
#pcap = ctypes.cdll.LoadLibrary("libpcap.so")
pcap = None
if(find_library("libpcap") == None):
print("We are here!")
pcap = ctypes.cdll.LoadLibrary("libpcap.so")
else:
pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
# required so we can access bpf_program->bf_insns
"""
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;}
"""
class bpf_program(ctypes.Structure):
_fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)]
class sockaddr(ctypes.Structure):
_fields_=[("sa_family",ctypes.c_uint16),("sa_data",ctypes.c_char*14)]
class pcap_pkthdr(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)]
pkthdr = pcap_pkthdr()
program = bpf_program()
# prepare args
snaplen = ctypes.c_int(1500)
#buf = ctypes.c_char_p(filter)
optimize = ctypes.c_int(1)
mask = ctypes.c_uint()
net = ctypes.c_uint()
to_ms = ctypes.c_int(100000)
promisc = ctypes.c_int(1)
filter = bytes(str("port 80"), 'ascii')
buf = ctypes.c_char_p(filter)
errbuf = ctypes.create_string_buffer(256)
pcap_close = pcap.pcap_close
pcap_lookupdev = pcap.pcap_lookupdev
pcap_lookupdev.restype = ctypes.c_char_p
#pcap_lookupnet(dev, &net, &mask, errbuf)
pcap_lookupnet = pcap.pcap_lookupnet
#pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms,
#char *errbuf
pcap_open_live = pcap.pcap_open_live
#int pcap_compile(pcap_t *p, struct bpf_program *fp,const char *str, int optimize,
#bpf_u_int32 netmask)
pcap_compile = pcap.pcap_compile
#int pcap_setfilter(pcap_t *p, struct bpf_program *fp);
pcap_setfilter = pcap.pcap_setfilter
#const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);
pcap_next = pcap.pcap_next
# int pcap_compile_nopcap(int snaplen, int linktype, struct bpf_program *program,
# const char *buf, int optimize, bpf_u_int32 mask);
pcap_geterr = pcap.pcap_geterr
pcap_geterr.restype = ctypes.c_char_p
#check for default lookup device
dev = pcap_lookupdev(errbuf)
#override it for now ..
dev = bytes(str("wlan0"), 'ascii')
if(dev):
print("{0} is the default interface".format(dev))
else:
print("Was not able to find default interface")
if(pcap_lookupnet(dev,ctypes.byref(net),ctypes.byref(mask),errbuf) == -1):
print("Error could not get netmask for device {0}".format(errbuf))
sys.exit(0)
else:
print("Got Required netmask")
handle = pcap_open_live(dev,snaplen,promisc,to_ms,errbuf)
if(handle is False):
print("Error unable to open session : {0}".format(errbuf.value))
sys.exit(0)
else:
print("Pcap open live worked!")
if(pcap_compile(handle,ctypes.byref(program),buf,optimize,mask) == -1):
# this requires we call pcap_geterr() to get the error
err = pcap_geterr(handle)
print("Error could not compile bpf filter because {0}".format(err))
else:
print("Filter Compiled!")
if(pcap_setfilter(handle,ctypes.byref(program)) == -1):
print("Error couldn't install filter {0}".format(errbuf.value))
sys.exit(0)
else:
print("Filter installed!")
if(pcap_next(handle,ctypes.byref(pkthdr)) == -1):
err = pcap_geterr(handle)
print("ERROR pcap_next: {0}".format(err))
print("Got {0} bytes of data".format(pkthdr.len))
pcap_close(handle)
⑹ python裡面如何釋放DLL文件
調用dll的代碼採用如下順序:
dll = CDLL(dllPath)
update_out = UpdateParamStruct()
dll.SeUpdaterGetParam(case.updateType, byref(update_out))
win32api.FreeLibrary(dll._handle)
這樣就可以在執行完後,dll文件不會處於佔用的狀態了~
⑺ 如何用python解析獲取C源文件的函數名
class stdata(Structure):
_fields_ = [('pBuf', c_char_p), ('buflen', c_int)]
N=100
buf = create_string_buffer(N)
d = stdata()
d.buflen = N
d.pBuf = cast(buf, c_char_p)
n = CallMyCFunc_GetData(byref(d))
關鍵在於create_string_buffer創建可寫buffer;cast轉換為char*類型。
⑻ 如何使用python 語言來實現測試開發
對於各種驅動介面,Python來編寫測試用例的好處是:由於Python不需要編譯,你所執行的也就是你所編寫的,當發生異常的時候,你無須打開集成開發環境,載入測試工程、並調試,你能夠很方便的看到python測試腳本的內容,什麼地方出了異常可以立刻發現,例如:
from ctypes import *
rc =c_int(-12345);
dll = windll.LoadLibrary("dmodbc.dll");#載入被測試組件
#=================#
SQLHANDLE_env = pointer(c_long(0));
SQLHANDLE_cnn = pointer(c_long(0));
SQLHANDLE_stmt = pointer(c_long(0));
pdns = c_char_p("FASTDB");
puid = c_char_p("SYSDBA");
ppwd = c_char_p("SYSDBA");
#env handle
rc = dll.SQLAllocHandle(1,None,byref(SQLHANDLE_env));
print "result of henv handle alloc :%d" %rc;
#cnn handle
rc = dll.SQLAllocHandle(2,SQLHANDLE_env,byref(SQLHANDLE_cnn));
print "result of cnn handle alloc :%d" %rc;
#connect!
rc = dll.SQLConnect(SQLHANDLE_cnn,pdns,-3,puid,-3,ppwd,-3)
print "result of connect :%d" %rc;
#stmt handle
rc = dll.SQLAllocHandle(3,SQLHANDLE_cnn,byref(SQLHANDLE_stmt));
print "result of stmt handle alloc:%d" %rc;
#exec
rc = dll.SQLExecDirect(SQLHANDLE_stmt,"insert into t values(1)",-3);
print "result of exec:%d" %rc;
#free========================
rc = dll.SQLFreeHandle(3, SQLHANDLE_stmt);
print rc;
rc = dll.SQLDisconnect(SQLHANDLE_cnn);
print rc;
rc = dll.SQLFreeHandle(2, SQLHANDLE_cnn);
print rc;
rc = dll.SQLFreeHandle(1, SQLHANDLE_env);
print rc;
在上面我們可以看到,Python調用c/c++介面是十分容易的,只需要把動態庫載入進來,然後把這個動態庫當作一個對象實例來使用就可以了。下面將是一個使用ado.net介面的例子:
import System;
from Dm import *#Dm是DMDBMS提供的ado.Net的DataProvider
#print dir(Dm.DmCommand);
i =0;
cnn = Dm.DmConnection("server = 127.0.0.1; User ID = SYSDBA; PWD = SYSDBA; Database = SYSTEM; port = 12345");
cmd = Dm.DmCommand();
cmd.Connection = cnn;
cmd.CommandText = "insert into t values(1);";
cnn.Open();
i=cmd.ExecuteNonQuery();
print i;
cmd.Dispose();
cnn.Close();
可以看到,.net對象的使用與在VisualStdio上進行開發幾乎沒有任何區別。
通過使用Python進行測試用例的開發,最大的好處莫過於:學習成本非常低,測試工程師只需要學習Python,對於其他語言稍有了解就可以了。同時只需要少量的測試開發工程師對Python測試框架進行維護。
這樣的好處就是便於測試人員將精力專精在一個方向,免於「什麼都會一點,但什麼都不精」的情況。當然測試人員具備廣闊的知識面,會使用各種常見的開發工具與平台是好事情,並且也是必要的,不過在短時間內要求迅速能夠勝任大多數任務也是企業在人才培養上的期望目標。