2017年11月

Win系列主机/服务器性能测试工具

自己用 C++ 写的一个小玩意, 主要用给客户展示一下当服务器被恶意软件攻击后系统资源被大量占用的场景.
文件下载在最后, 源代码如下:

#include "iostream"
#include <stdio.h>
#include <process.h>
#include <math.h>
#include <string>
#include <typeinfo.h>
#include <stdlib.h>
#include <conio.h>
#include <sys/types.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <csignal>
#include <time.h>  
#pragma comment(lib,"ws2_32.lib")

using namespace std;

void EVILACTION() {}
void NETLISTEN ( char * SERVERIP, int SERVERPORT ) {
    //创建套接字
    WORD myVersionRequest;
    WSADATA wsaData;
    myVersionRequest = MAKEWORD ( 1, 1 );
    int err;
    err = WSAStartup ( myVersionRequest, &wsaData );
    if (!err) {
        //printf ( "已打开端口%d\n",SERVERPORT);
    } else {
        printf ( "ERROR:嵌套字未打开!" );
    }
    SOCKET serSocket = socket ( AF_INET, SOCK_STREAM, 0 );//创建套接字
    SOCKADDR_IN addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr = inet_addr(SERVERIP);
    //inet_pton ( AF_INET, SERVERIP, (void*)&addr.sin_addr.S_un.S_addr );
    addr.sin_port = htons ( SERVERPORT );
    ::bind ( serSocket, (SOCKADDR*)&addr, sizeof ( SOCKADDR ) );
    listen ( serSocket, 5 );
    SOCKADDR_IN clientsocket;
    int len = sizeof ( SOCKADDR );
    SOCKET serConn = accept ( serSocket, (SOCKADDR*)&clientsocket, &len );
}
void CPUINIT (int tmp, int max) {  // CPU 测试
    srand ( (unsigned)time ( NULL ) );
    for (int z = 1; z <= max; z++) {
        int a = rand();
        sqrt ( a / max );
        if(z > max) {
            z = 1;
            Sleep ( 1 );
        }
    }
}
void MEMINIT (int tmp, int max) {  // 内存测试
    long* pl;
    pl = (long*)malloc ( max * sizeof ( long ) );
    for (int i = max; i > 1; i--) {
        long a = 9999999999;
        pl[i] = a;
    }
    while (1) {
        Sleep ( 1 );
    }
}
void NETINIT (string ip, int d,int flag) {  // 端口占用测试
    char szModuleFilePath[MAX_PATH];
    GetModuleFileNameA ( 0, szModuleFilePath, MAX_PATH );  // 获得当前执行文件的路径
    //szModuleFilePath[strrchr ( szModuleFilePath, '\\' ) - szModuleFilePath + 1] = 0;  // 取目录名
    int a = 65535;
    for (int i = d; i > 0; i--) {
        char tmp[5];
        _itoa ( a, tmp, 10 );
        string tmp1 = string ( szModuleFilePath ) + " -p " + string ( tmp );
        WinExec ( tmp1.c_str (), SW_HIDE );
        Sleep ( 200 );
        a--;
    }
}
void KILLRUNNING ( int sig ) {
    if (sig == SIGINT) {
        char szModuleFilePath[MAX_PATH];
        GetModuleFileNameA ( 0, szModuleFilePath, MAX_PATH );
        char name[_MAX_FNAME];
        char suffix[_MAX_EXT];
        string file = "@taskkill /f /im ";
        _splitpath ( szModuleFilePath, NULL, NULL, name, suffix );
        file = file + string ( name ) + string ( suffix );
        //system (file.c_str());
    }
}
void init(int a,int b,string c,int d,int flag){
    char szModuleFilePath[MAX_PATH];
    GetModuleFileNameA ( 0, szModuleFilePath, MAX_PATH );  // 获得当前执行文件的路径
    int i = 0;
    for (i = a; i >= 1; i--) {  // CPU 线程
        char tt[10];
        itoa(i,tt,10);
        string tmp1 = string ( szModuleFilePath ) + " -c " + string(tt);
        WinExec ( tmp1.c_str (), SW_HIDE );
    }
    for (i = b; i >= 1; i--) {  // 内存 线程
        char tt[10];
        itoa(i,tt,10);
        string tmp1 = string ( szModuleFilePath ) + " -m " + string(tt);
        WinExec ( tmp1.c_str (), SW_HIDE );
    }
    NETINIT ( c, d,flag);
    EVILACTION();
}
void usage () {
    printf ( "Usage: tester.exe\r\n" );
    printf ( "options:\r\n" );
    printf ( "  -n (int)range  \tnetwork listen range, for <65535~(65535-range)>\r\n" );
    printf ( "  -c (int)process \tcpu process count\r\n" );
    printf ( "  -m (int)process \tmemory process count\r\n" );
    printf ( "  -d (int)second \tdealy seconds\r\n" );
    printf ( "Example:\r\n" );
    printf ( "  tester.exe -n 5 -c 1 -m 5 -d 3\r\n" );
    printf ( "that will be listen local:65535~65530" );
}
int main ( int argc, char * argv[] ) {
    /**
     * args1 CPU 线程数量
     * args2 内存线程数量
     * args3 网络对象 IP 地址
     * args4 网络线程数量
    */
    signal ( SIGINT, KILLRUNNING );
    int a = 1, b = 1, d = 1;
    string c = "127.0.0.1";
    int timeout = 0;
    int port = 0;
    if (argc == 3) {
        if (string ( argv[1] ) == "-p") {
            port = atoi ( argv[2] );
            NETLISTEN ( "127.0.0.1", port );  // 开监听端口
            exit ( 1 );
        }
        if (string ( argv[1] ) == "-c") {
            port = atoi ( argv[2] );
            CPUINIT ( 1, port*99 );  // 开CPU进程
            exit ( 1 );
        }
        if (string ( argv[1] ) == "-m") {
            port = atoi ( argv[2] );
            MEMINIT ( 1, port*1000000 );  // 开内存进程
            exit ( 1 );
        }
        usage ();
        exit( 1 );
    } else if (argc != 9) {
        usage ();
        exit ( 1 );
    } else {
        for (int i = 1; i < argc; i += 2) {
            if (string ( argv[i] ) == "-n") {
                d = atoi ( argv[i + 1] );  // network
            }
            if (string ( argv[i] ) == "-c") {
                a = atoi ( argv[i + 1] );  // cpu
            }
            if (string ( argv[i] ) == "-m") {
                b = atoi ( argv[i + 1] );  // memory
            }
            if (string ( argv[i] ) == "-d") {
                timeout = atoi ( argv[i + 1] );  // dealy
            }
        }
    }
    cout << "CPU 占用线程: " << a << endl;
    cout << "内存占用线程: " << b << endl;
    cout << "端口范围: 65535 ~ " << 65536 - d << endl;
    cout << "延时 :" << timeout << "秒" << endl;
    Sleep ( timeout * 1000 );
    cout << "######### START ############" << endl;
    init ( a, b, c, d, 0 );
    //init ( a, b, c, 1);
    return 0;
}

ConsoleForWindows.zip

文件: E:\delovt\tools\ConsoleForWindows.zip
大小: 117479 字节
修改时间: 2017?11?30?, 10:09:37
MD5: D6D578D8C9BF595B7E30E4760F3ECB08
SHA1: 356FEC7A1EB291B4EEE311CEF4F9B1FA54A6304B
CRC32: 3068F610
文件: E:\delovt\tools\ConsoleForWindows.exe
大小: 223744 字节
修改时间: 2017年11月29日, 11:28:03
MD5: 8D99523ABB15BEB1AE6A9B7542B7CC02
SHA1: FD4E29029A1DE56C074C59DF89FC1E4FF15CCAFE
CRC32: D109932F

使用方法: tester.exe -h

[python] excel 文档解析导出 html

因为 excel 默认情况下对于长文本显示不太友好.
提取第一行的内容作为 key, 将余下的内容分别对应到每一列的 key 然后导出为 html 的表格.

效果图如下:
效果图
代码如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# author: help@sys7em.info
# desript: excel 文档解析, 生成友好的需求文件
import os,sys;
import xlrd;
import time,re;
reload(sys)
sys.setdefaultencoding('utf-8')

def saveFile(i,file = False,Data = False):
    if file == False or Data == False:
        print '[!] Error: file or data is not found'
        sys.exit(0)
    path = os.path.splitext(file)[0]
    path = path + '-' +i.encode('gb2312')
    path = path + time.strftime(".%Y.%m.%d.%H.%M.%S.html", time.localtime())
    try:
        file = open(path,"w+")
    except Exception,e:
        print '[!] Error'
        print e;
    file.write('<html><head><meta charset="GB2312"></head><body bgcolor="#f4f4f4"><center><div><table width="860" border="3" style="background-color:#fff" bordercolor="#336699" cellspacing="3" cellpadding="10" align="CENTER"><thead><tr><th>'+i.encode('gb2312')+'</th></tr></thead><tbody>');
    for i in xrange(0,len(Data)):
        rowData = Data[i];
        file.write('<tr><td><table cellpadding="5">');
        for j  in rowData.items():
            key = j[0]
            value = j[1]
            file.write('<tr><td width="15%">'+key+':</td>')
            value = re.sub(re.compile(u"\r\n"),'<br>',str(value))
            file.write('<td width="85%" style="word-wrap:break-word;word-break:break-all;">'+str(value)+'</td></tr>')
        file.write("</table></tr></td>");
    file.close();
    print '[+] Exported => '+path;
    
def export(file = False,count = False):
    if file == False or count == False:
        print '[!] Error: args is Fail'
        sys.exit(0)
    try:
        data = xlrd.open_workbook(file)
    except Exception,e:
        print '[!] Error'
        print str(e);
        sys.exit(0)
    for i in data.sheet_names():
        print '[+] ==== '+i+'===='
        localData = data.sheet_by_name(i);
        print '[+] rows => '+str(localData.nrows)
        print '[+] cols => '+str(localData.ncols)
        print '[+] count => '+str(count)
        # get dist
        dist = []
        for col in xrange(0,localData.ncols):
            tmp = localData.cell(count-1,col).value
            tmp = str(tmp)
            dist.append(tmp.encode('gb2312'))
        # save data
        rowData = [];
        for row in xrange(count,localData.nrows):
            currData = {};
            for col in xrange(0,localData.ncols):
                key = dist[col]
                try:
                    currData[key] = localData.cell(row,col).value.encode('gb2312');  # a["dist"] = "value"
                except Exception,e:
                    currData[key] = localData.cell(row,col).value;  # a["dist"] = "value"
            rowData.append(currData) # b["row"] = {"aa":"value"}
        saveFile(i,file,rowData);
def init(fileName,count):
    localDir = os.getcwd();
    targetFile = localDir+"\\"+fileName;
    print '[+] Check File...'
    if os.path.isfile(targetFile) != True:
        print '[!] Error: is no file', targetFile
        sys.exit();
    if "xls" not in os.path.splitext(targetFile)[1]:
        print '[!] Error: is no file'
        sys.exit();
    print '[+] exporting..'
    export(targetFile,int(count))
    print '[+] Done.'
    
def main():
    if len(sys.argv) == 3:
        init(sys.argv[1],1);
    elif len(sys.argv) == 4:
        init(sys.argv[1],sys.argv[2])
    else:
        print 'informationSplit.py'
        print 'Author: help@sys7em.info'
        print 'Descript: Excel 信息提取工具'
        print 'Usage: python split.py <a.xls>(string:file name) [count](int:title row,default: 1)'
        sys.exit()
if __name__ == '__main__':
    main()