多进程编程习题(Python语言实现)

IP 地址归属地批量查询任务

注意: 使用创建子类的方式实现多线程任务

实现代码:

import json
import requests
from threading import Thread


class GetHostAliveThread(Thread):
    def __init__(self, ip):
        super(GetHostAliveThread, self).__init__()
        self.ip = ip

def run(self):
    url = 'http://ip-api.com/json/%s' % (ip)
    count = requests.get(url).text
    dict_data = json.loads(count)
    city = dict_data.get('city')
    country = dict_data.get('country')
    print('%s的所在城市为%s' % (self.ip, city))
    print('%s的所在城市为%s' % (self.ip, country))


if __name__ == '__main__':
    for i in range(25):
        ip = str('1.1.1.') + str(1 + i)
        thread = GetHostAliveThread(ip)
        thread.start()

基于多线程的批量主机存活探测

项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态,
则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。这可以在 Python
中编程,在 IP 地址的地址范围内有一个 for 循环和一个 os.popen(“ping -q -c2”+ ip)。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。
注意: 使用实例化对象的方式实现多线程任务

实现代码:

import json
import requests
from threading import Thread
import pymysql
conn = pymysql.connect(host='172.25.254.149', user='root', password='990038', db='mysql')#连接数据库
cursor = conn.cursor()#设立邮标
# create_sqli = 'create table IP(ipid varchar(20),ipcity varchar(20),ipcountry varchar(20));'(如果没有表则进行建表)
# cursor.execute(create_sqli)

class GetHostAliveThread(Thread):
    def __init__(self, ip):
        super(GetHostAliveThread, self).__init__()
        self.ip = ip

def run(self):
    url = 'http://ip-api.com/json/%s' % (ip)
    count = requests.get(url).text
    dict_data = json.loads(count)
    city = dict_data.get('city')
    country = dict_data.get('country')
    #print('%s的所在城市为%s' % (self.ip, city))
    #print('%s的所在城市为%s' % (self.ip, country))
    insert_sqli = 'insert into IP(ipid,ipcity,ipcountry) values("%s", "%s", "%s");' % (ip, city, country)#将信息导入数据库
    print(insert_sqli)
    cursor.execute(insert_sqli)
    conn.commit()#上传修改


if __name__ == '__main__':
    for i in range(25):
        ip = str('1.1.1.') + str(1 + i)
        thread = GetHostAliveThread(ip)
        thread.start()
        cursor.close()
        conn.close()
上一篇:MySQL学习笔记(二)


下一篇:MySql外键设置方式1