先补充子网掩码的计算:如255.255.255.0计算为24(11111111.11111111.11111111.0)二进制有24个1,代码如下:
netmask = '255.255.255.0'
result = ""
for num in netmask.split('.'):
temp = str(bin(int(num)))[2:]
result = result + temp
print (len("".join(str(result).split('0')[0:1])))
所以ubuntu的ip地址表现形式:
192.168.1.112/24
把地址和掩码一起表示了
ubuntu用的是netplan(不同版本有所不用),所以改/etc/netplan/01-network-manager-all.yaml这个文件即可,改完执行netplan apply命令。
报错Permission denied:
由于该文件是只读的,所以要想通过代码修改,还要修改一下文件的权限chmod 557 /etc/netplan/01-network-manager-all.yaml。也可以干脆点chmod 777.
该文件的格式是yml,所以要安装yaml install
完整代码如下:
# netmask = '255.255.255.0'
# result = ""
# for num in netmask.split('.'):
# temp = str(bin(int(num)))[2:]
# result = result + temp
# print (len("".join(str(result).split('0')[0:1])))
import yaml,os
path = "/etc/netplan/01-network-manager-all.yaml"
def sudoCMD(command,password):
str = os.system('echo %s | sudo -S %s' % (password,command))
print(str)
sudoCMD('chmod 557 '+ path,'1234')
with open(path, mode='w', encoding='utf-8') as f:
f.truncate()
def add_dict():
data = {'network':{}}
data['network']['version'] = 2
data['network']['renderer'] = "networkd"
data['network']['ethernets'] = {}
data['network']['ethernets']['eno1'] = {'addresses':['192.168.1.112/24'],'dhcp4':'no','optional':"true",
'gateway4':"192.168.1.254",'nameservers':{'addresses':['8.8.8.8','114.114.114.114']}}
# data['network']['ethernets']['ens22'] = {'addresses':['192.168.31.215/24'],'dhcp4':'no','optional':"true",
# 'gateway4':"192.168.31.1",'nameservers':{'addresses':['192.168.31.1,114.114.114.114']}}
file = open(path, 'a', encoding='utf-8')
yaml.dump(data, file)
file.close()
add_dict()
with open(path, "r",encoding='utf-8') as yaml_file:
yaml_obj = yaml.load(yaml_file.read(), Loader=yaml.FullLoader)
print(yaml_obj)
# main_yaml = open(path, 'w')
# yaml.dump(yaml_obj, main_yaml)
# main_yaml.close()
sudoCMD('sudo netplan apply','1234')
网络参数都在代码中,封装以下即可。
|