满眼喜欢990 2024-05-08 18:01 采纳率: 0%
浏览 2

python2.7多线程和数据库问题

python2.7版本写了一个活跃主机扫描的代码,用的多线程,现在想将扫描的结果存活主机IP保存至MySQL数据库,但多线程不是很明白,应该怎么修改代码

# !/usr/bin/env python
# coding:utf-8
# Author: Zeroh
 
import os
import platform
import multiprocessing
from IPy import IP
import pymysql
from socket import setdefaulttimeout
import time
 
printLock = multiprocessing.Lock()  # lock Screen print
TimeOut = 5
 
def get_os():
    '''
    get os 类型
    '''
    os = platform.system()
    if os == "Windows":
        return "n"
    else:
        return "c"
 
class find_ip():
    def __init__(self, cidr, threads_num):
        self.threads_num = threads_num
        self.cidr = IP(cidr)
        self.IPs = multiprocessing.Queue()
        for ip in self.cidr:
            self.IPs.put(str(ip))
 
    def request(self):
        while not self.IPs.empty():
            ip = self.IPs.get()
            try:
                cmd = ["ping", "-n" if get_os() == "n" else "-c", "1", ip]
                output = os.popen(" ".join(cmd)).readlines()
                flag = False
                for line in output:
                    if line.upper().find("TTL") >= 0:
                        flag = True
                        break
                if flag:
                    with printLock:  # 使用多进程锁
                        print("ip: %s is ok ***" % ip)
                    try:
                        sqlAdd='insert into activeipscan(IP)VALUES ("%s;")'%ip
                        cursor.execute(sqlAdd)
                        db.commit()
                    except Exception,e:
                        print'2',e
            except Exception as e:
                with printLock:  # 使用多进程锁
                    print("Exception occurred: %s" % e)
 
    def run(self):
        for i in range(self.threads_num):
            multiprocessing.Process(target=self.request).start()
 
def main(cidr):
    global db,cursor
    try:
        db=pymysql.connect('localhost','root','root','test')
        cursor=db.cursor()
        sqlDelete='delete from activeipscan'
        cursor.execute(sqlDelete)
        db.commit()
    except Exception,e:
        print '1',e
    setdefaulttimeout(1)
    
    # print("start time %s" % time.ctime())
    options = {'threads_num': 200}
    s = find_ip(cidr, threads_num=options['threads_num'])
    s.run()
    # print("end time %s" % time.ctime())
 
if __name__ == "__main__":
    main('192.168.242.0/24')


  • 写回答

4条回答 默认 最新

  • 专家-皆知 2024-05-08 18:02
    关注

    引自免费微信小程序:皆我百晓生

    在Python 2.7中,你可以使用threading模块进行多线程编程。为确保线程安全地操作数据库,可以使用线程局部存储(thread-local storage)或队列来收集活跃主机IP,然后在主线程中批量插入到MySQL数据库。

    评论

报告相同问题?

问题事件

  • 创建了问题 5月8日

悬赏问题

  • ¥15 soildworks装配体的尺寸问题
  • ¥100 有偿寻云闪付SDK转URL技术
  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑