#!/bin/bash
# ubuntu18.04初始化配置
#判断用户执行
if [ $UID != "0" ];then
echo "请使用root用户运行"
exit 1
fi
hostnamectl set-hostname 041840636zwt
# 配置apt源
mv /etc/apt/source.list /etc/apt/source.list.bak
touch /etc/apt/source.list
cat>>/etc/apt/source.list<>/root/.bashrc<>config_net.py< list:
interface_list = []
with open('/proc/net/dev') as f:
net_file = f.readlines()
for line in net_file[2:]:
interface = line[0:line.index(':')].strip()
if interface != 'lo':
interface_list.append(interface)
return interface_list
def netmask_2_int(netmask: str) -> int:
str_list = netmask.split('.')
one_count = 0
for str in str_list:
bin_str = bin(int(str))[2:]
one_count += bin_str.count('1')
return one_count
if __name__ == '__main__':
net_file = open('/etc/netplan/01-network-manager-all.yaml', mode='a')
net_file.write('n ethernets:n')
for interface in get_interfaces():
print('=' * 50)
print(f'ttconfigure interface {interface}')
print('=' * 50)
ip_reg = r'[0-9]+.[0-9]+.[0-9]+.[0-9]+'
ip_group_reg = r'([0-9]+).([0-9]+).([0-9]+).([0-9]+)'
reg = re.compile(ip_group_reg)
while True:
address = input('please enter your ip address:n')
if re.match(ip_reg, address):
matcher = reg.match(address)
for i in range(1, 5):
if int(matcher.group(i)) >= 255:
print('ERROR:please enter the right address')
continue
break
while True:
netmask = input(f'please enter your netmask(255.255.255.0):n')
if netmask == '':
netmask = '255.255.255.0'
break
bin_mask = ''
if re.match(ip_reg, netmask):
matcher = reg.match(netmask)
for i in range(1, 5):
if int(matcher.group(i)) > 255:
print('ERROR:please enter the right netmask')
continue
bin_num = bin(int(matcher.group(i)))[2:]
bin_mask += bin_num
if not re.match('1+0+', bin_mask):
print('ERROR:the netmask is not recommended')
break
while True:
gateway = input(f'please enter your gateway:n')
if re.match(ip_reg, gateway):
matcher = reg.match(gateway)
for i in range(1, 5):
if int(matcher.group(i)) >= 255:
print('ERROR:please enter the right gateway')
continue
break
while True:
dns = input(f'please enter your DNS({gateway}):n')
if dns == '':
dns = gateway
break
if re.match(ip_reg, dns):
matcher = reg.match(dns)
for i in range(1, 5):
if int(matcher.group(i)) >= 255:
print('ERROR:please enter the right DNS')
continue
break
content = f'''
{interface}:
dhcp4: no
dhcp6: no
addresses: [{address}/{netmask_2_int(netmask)}]
gateway4: {gateway}
nameservers:
addresses: [{dns}]n
'''
net_file.write(content)
net_file.close()
if os.system('netplan apply') == 0:
print(" 33[1;32m interface configure succeed 33[0m")
else:
print(" 33[1;31m interface configure failed 33[0m")
EOF
python3 config_net.py