ubuntu18.04初始化script(python3+shell)

#!/bin/bash
# ubuntu18.04初始化配置


#判断用户执行
if [ $UID != "0" ];then
	echo "请使用root用户运行"
	exit 1
fi

hostnamectl set-hostname myname


# 配置apt源
mv /etc/apt/sources.list /etc/apt/sources.list.bak
touch /etc/apt/sources.list
cat>>/etc/apt/sources.list<<EOF
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
EOF
apt update # 这条命令只检查可更新的组件包,不会进行更新
apt upgrade -y


# ssh优化配置
apt install openssh-server -y
sed -i "s|^#UseDNS no|UseDNS no|g" /etc/ssh/sshd_config
sed -i "s|^#GSSAPIAuthentication no|GSSAPIAuthentication no|g" /etc/ssh/sshd_config
sed -i "s|^#PermitRootLogin prohibit-password|PermitRootLogin yes|g" /etc/ssh/sshd_config
sed -i "s|^#Port 22|Port 2021|g" /etc/ssh/sshd_config

systemctl restart sshd


# 添加常用命令别名和变量
cat>>/root/.bashrc<<EOF
alias rnet='/etc/init.d/networking restart'
alias res='systemctl restart'
alias start='systemctl start'
alias status='systemctl status'
NET='/etc/sysconfig/network-scripts'
EOF
source /root/.bashrc





pip3 install pyyaml netifaces

# 编写python脚本,配置网络
touch config_net.py
cat>>config_net.py<<EOF
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re


def get_interfaces() -> 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'\t\tconfigure 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("\033[1;32m interface configure succeed\033[0m")
    else:
        print("\033[1;31m interface configure failed\033[0m")

EOF

python3 config_net.py
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值