使用python 配置网络ubuntu14.04(多网卡,route,wpa,mac,dns,sqlite3)

使用python涉及了,很多常见的使用,方便查找和学习使用。

直接上代码:

1.(以下是设备启动时配置,还有一些公司查找数据库部分功能)

#coding:utf-8
import os
import subprocess
from locale import str
from _dbus_bindings import Byte
from builtins import set, bytes
import sqlite3
import re

#/proc
ret = subprocess.Popen("cat /proc/net/dev", shell=True, stdout = subprocess.PIPE)
str_b = ret.stdout.read()
str_cmd = bytes.decode(str_b)
listproc_cardname = re.findall("(\S+):", str_cmd)

#interfaces
fr = open("/etc/network/interfaces", "r")
interfaces_content = fr.read(1000)
listface_info = re.findall("(^auto\s(\S+)\n(\S+.*\n){0,4})", interfaces_content, re.M)  #re.M:^$标志将会匹配每一行
listface_cardname = []
mapfaces = {}
for item in listface_info:
    listface_cardname.append(item[1])
    mapfaces[item[1]] = item[0]
    
#samelist,otherlist
samelist = list(set(listface_cardname) & set(listproc_cardname))    #相同的已在interfaces里注册过的
otherlist = list(set(samelist) ^ set(listproc_cardname))     #多出的

print (samelist)
print (listproc_cardname)

#down
for iproc in listproc_cardname:
    if iproc == "lo":
        continue
    cmd = "ifconfig " + iproc + " down"
    os.system(cmd)

#写入到interfaces-------------------------
strfinal = ""
for same in samelist:
    strfinal += mapfaces[same]
    strfinal += "\n"

f = open("./interfaces", "w+")
for other in otherlist:             
    listAlUse = re.findall("^auto\s\S+\n.*\n^address\s\d+.\d+.(\d+).\d+", strfinal, re.M)
    ilistAlUse = []
    for item in listAlUse:
        ilistAlUse.append(int(item))
    sx = 1
    for isx in range(1, 11):
        if isx in ilistAlUse:
            isx += 1
        else:
            sx = isx
            break     
    if "lo" in other:
        strfinal += "auto " + other + "\n"
        strfinal +=  "iface " + other + " inet loopback\n\n"   
        continue 
    elif "wlan" in other:
        continue
    else:
        strfinal += "auto " + other + "\n"
        strfinal += "iface " + other + " inet static\n"
        strfinal += "address 192.168." + str(sx)  + ".5\n"
        strfinal += "netmask 255.255.255.0\n"
        strfinal += "gateway 192.168." + str(sx)  + ".1\n\n"
f.write(strfinal + "\n")                  
f.close()
os.system("mv ./interfaces /etc/network/interfaces") #move

#mac
mapMac = {}
for iproc in listproc_cardname:
    if iproc == "lo":
        continue
    cmd = "cat /sys/class/net/%s/address" % iproc
    ret = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
    str_b = ret.stdout.read()
    str_cmd = bytes.decode(str_b)
    mapMac[iproc] = str_cmd
listkey = list(mapMac.keys())

for keymapMac in listkey:
    need_while = 1
    need_modify = 0
    while need_while:
        need_while = 0
        item_value = mapMac[keymapMac]
        for ikeymapMac in listkey:
            if keymapMac == ikeymapMac:
                continue
            if item_value != mapMac[ikeymapMac]:
                continue
            same_mac = "%s" % item_value
            lastlist = same_mac.split(":")
            last = lastlist[-1]
            intx = int("%s" % last, 16)
            newintx = hex(intx + 1)
            str_netintx = "%s" % newintx
            str_netintx = str_netintx.split("x")[-1]
 
            if intx + 1 < 10:
                str_netintx = "0" + str_netintx
            elif intx + 1 > 255:
                str_netintx = str_netintx[-2:]    
            lastlist[-1] = str_netintx
            same_mac = ":".join(lastlist)
            mapMac[keymapMac] = same_mac + "\n"
            need_while = 1
            need_modify = 1
            break
        
    if need_modify == 1:    
        cmd = "ifconfig %s hw ether %s" % (keymapMac, same_mac)
        os.system(cmd)
        print(cmd)

#up
listaddrmask = re.findall("^auto\s(\S+)\n.*\naddress\s(\d+.\d+.\d+.\d+)\nnetmask\s(\d+.\d+.\d+.\d+)\n", strfinal, re.M)
for item in listaddrmask:
    cmd = "ifconfig " + item[0] + " up"
    os.system(cmd)
    cmd = "ifconfig %s %s netmask %s" % (item[0], item[1], item[2])
    os.system(cmd)

#up wlan
for iproc in listproc_cardname:
    if "wlan" in iproc:
        cmd = "ifconfig " + iproc + " up"
        os.system(cmd)
        print("up wlan")

#------------------------------------- 
#网关及wifi设置
try:
    sql = sqlite3.connect("./PARAM.db")
    curs = sql.cursor()
    infouse = 0
    cursor_name = curs.execute("select value from sysparam where name='CntNet_UseName'")
    for row in cursor_name:
        info = row[0]
    cursor_use = curs.execute("select value from sysparam where name='CntNet'")
    for srow in cursor_use:
        infouse = srow[0]
        break
    strinfouse = "%s" % infouse
    for itemstrinfouse in strinfouse:
        infouse = itemstrinfouse
        break
    strname = "%s" % info
    strinfouse = "%s" % infouse
    sql.close()
    if strname == "" or strinfouse == "0":    #有确定使用联网网卡 和 使用联网
        raise Exception("no need use net or no such use card")
    
    if strname not in listproc_cardname:
        raise Exception("card %s not in /proc list" % strname)
    
    if "wlan" not in strname: 
        gateway = "null"
        touch = "^auto\s%s\n(.*\n){3}gateway\s(\d+.\d+.\d+.\d+)\n" % strname
        listUsecard = re.findall(touch, strfinal, re.M)
        if len(listUsecard):
            gateway = listUsecard[0][1]

        if gateway == "null":
            raise Exception("find interfaces netcard route error")
        
        os.system("route add default gw %s" % gateway)
        #base
        fb = open("./base", "w+")
        fb.write("nameserver %s\n" % gateway)
        fb.close()
        os.system("mv ./base /etc/resolvconf/resolv.conf.d/base")  
    else:
        os.system("wpa_supplicant -i%s -Dwext -c /etc/wpa_supplicant/wlanpwd.conf &" % strname)
        #os.system("ifconfig %s %s" % (strname, address))
        os.system("dhclient %s &" % strname)
        #os.system("route add default gw %s" % gateway)
        os.system("rm /etc/resolvconf/resolv.conf.d/base")
                
except sqlite3.OperationalError:
    print("cls:can not find sqlitefile")
except Exception as value:
    print(value)
except NameError:
    print("cls:some param error in db")
finally:
    print("up finish")  














2.(python的一些异常,可以用于查找和学习)

#coding:utf-8
import os
import subprocess
import sqlite3
import argparse
import re
from time import sleep

if __name__ != "__main__":
    exit(0)

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    
def checkping(addr):
    strcmd = "ping %s -w 2" % addr
    ret = subprocess.Popen(strcmd, shell=True, stdout = subprocess.PIPE)
    str_b = ret.stdout.read()
    strback = bytes.decode(str_b)
    for item in strback.split(" "):
        if "time=" in item:
            strftime = item[item.find("=") + 1:]
            ftime = float(strftime)
            if ftime != 0:
                return "connected"
                break
    return "disconnect"

# def addfileonces():
#     fr = open("./cnt_net/chknettimes", "w+")
#     buf = fr.read(10)
#     print(buf)
#     ibuf = re.findall("\d+", buf)
#     if len(ibuf) == 0 :
#         sibuf = "1" 
#         fr.write(sibuf)
#     else:
#         sibuf = "%d" % (int(ibuf[0]) + 1)  
#         fr.write(sibuf)
#     fr.close()    
# 
#     times = int(sibuf)
#     return times
    
def relineEth(strname, serverip):
    try:    
        strcmd = "ifconfig %s" % strname
        ret = subprocess.Popen(strcmd, shell=True, stdout = subprocess.PIPE)
        str_b = ret.stdout.read()
        strback = bytes.decode(str_b)
    
        result = re.findall(".*\n.*inet\s\D+:(\d+.\d+.\d+.\d+).*",strback)
        if len(result) == 0:
            raise MyError("no find ip by card")
        fr = open("/etc/network/interfaces", "r")
        facesstrall = fr.read(1000)
        #获取处理网关
        right = "auto\s+%s.*(\s.*){4}gateway\s(\d+.\d+.\d+.\d+).*" % strname
        route = re.findall(right, facesstrall)
        itemroute = "null"
        if len(route) != 0:
            if len(route[0]) == 2:
                itemroute = route[0][1]
        itemroute = "%s" % itemroute
        if itemroute == "null":
            raise MyError("no such 'eth' route")
        
        ip = result[0]
        os.system("ifconfig %s up" % (strname))
        os.system("ifconfig %s %s" % (strname, ip))
        os.system("/etc/init.d/networking restart")
        os.system("route add default gw %s" % itemroute)
        
        sleep(5)
        
        ret = checkping(serverip)
        return ret
    except MyError as contain :
        print(contain.value)
        exit(0)
    except IndexError:
        print("list index out of range")
        exit(0)
    
def relineWlan(strname, serverip = "192.168.1.1"):
    try:
        ret = subprocess.Popen("ps -a", shell=True, stdout = subprocess.PIPE)
        str_b = ret.stdout.read()
        strback = bytes.decode(str_b)
        
        for item in strback.split("\n"):
            if "wpa_supplicant" in item:
                os.system("killall wpa_supplicant")
            elif "dhclient" in item:
                os.system("killall dhclient")
        
        #去除其他同网段的网卡
        ret = subprocess.Popen("ifconfig", shell=True, stdout = subprocess.PIPE)
        str_b = ret.stdout.read()
        strback = bytes.decode(str_b)
        dictcard = {}
        for item in strback.split("\n\n"):
            result = re.findall("(\S+)\s+Link.*\n\s+inet\s\S+:(\d+.\d+.\d+.\d+).*", item)
            if len(result) != 0:
                listcardinfo = list(result[0])
                if len(listcardinfo) == 2:
                    dictcard[listcardinfo[0]] = listcardinfo[1]
        if strname not in dictcard.keys():
            os.system("ifconfig %s up" % (strname))
        else:
            usewlanip = dictcard[strname]
            for item in dictcard.keys():
                if item != strname and dictcard[item] == usewlanip:
                    os.system("ifconfig %s down" % (item))
        
        os.system("wpa_supplicant -i%s -Dwext -c /etc/wpa_supplicant/wlanpwd.conf &" % strname)
        os.system("dhclient %s &" % strname)
        
        sleep(10)
  
        ret = checkping(serverip)
        return ret
        
    except IndexError:
        print("list index out of range")
        exit(0)
    except KeyError:
        print("use card name have no find card in system")
        exit(0) 

parser = argparse.ArgumentParser(description="yes or no to close netclient, ,please enter -close")
parser.add_argument('-close', type=bool, help="close netclient")
args = parser.parse_args()
isCloseNet = args.close

#获取进程列表
ret = subprocess.Popen("ps -a", shell=True, stdout = subprocess.PIPE)
str_b = ret.stdout.read()
str_cmd = bytes.decode(str_b)

#判断是否已经启动netclient,有进程时清除占用
listprocess = str_cmd.split("\n")
for item in listprocess:
    if "NetClient2" in item:
        os.system("killall NetClient2")
        
#输入参数:-close时关闭编码进程
if isCloseNet:
    print(isCloseNet)
    exit(0)
    
#获取主程序联网设置
paramsql = sqlite3.connect("./PARAM.db")
paramcurs = paramsql.cursor()
try:
    #判断是否有需求联网
    isUseNetAll = "0"
    isUseNet = "0"
    cursor_use = paramcurs.execute("select value from sysparam where name='CntNet'")
    for row in cursor_use:
        isUseNetAll = "%s" % row[0]
    for itemstrinfouse in isUseNetAll:
        isusenet = itemstrinfouse
        break
    strisusenet = "%s" % isusenet
    if strisusenet == "0":
        raise MyError("no need use net")
    #判断联网网卡名称
    cardname = "null"
    cursor_name = paramcurs.execute("select value from sysparam where name='CntNet_UseName'")
    for row in cursor_name:
        cardname = "%s" % row[0]
    if cardname == "null":
        raise MyError("get card name error")
    
except sqlite3.OperationalError:
    print("cls:can not find sqlitefile param")
    exit(0)
except MyError as contains:
    print(contains.value)
    exit(0)
finally:
    paramsql.close()

#获取服务器连接
sql = sqlite3.connect("./cnt_net/sysconf.db")
curs = sql.cursor()
try:
    apppath = "null"
    infopath = "null"
    addrpath = "null"
    cursor_app = curs.execute("SELECT 值 from info_sysconf where 信息名称='apppath_send'")
    for row in cursor_app:
        apppath = row[0]
    cursor_info = curs.execute("SELECT 值 from info_sysconf where 信息名称='thispath'")
    for rows in cursor_info:
        infopath = rows[0]
    cursor_addr = curs.execute("SELECT 值 from info_sysconf where 信息名称='serverip_info'")
    for rowss in cursor_addr:
        addrpath = rowss[0]
    if apppath == "null" or infopath == "null" or addrpath == "null":
        raise MyError("no such db value")
    
    #测试网络连接
    ret = checkping(addrpath)
    isThrough = False
    if ret == "disconnect" and "wlan" in cardname:
        isThrough = relineWlan(cardname, addrpath)
    elif ret == "disconnect":
        isThrough = relineEth(cardname, addrpath)
    elif ret == "connected":
        isThrough = ret
    print("reline result %s" % isThrough)

    if isThrough == "connected":
        cmd = apppath + " " + infopath + " &"
        os.system(cmd)
except sqlite3.OperationalError:
    print("cls:can not find sqlitefile sysconf")
except NameError:
    print("cls:can not find item by db")
except MyError as contain:
    print(contain.value)
    exit(0)
finally:
    sql.close()





你可能感兴趣的:(ubuntu,python)