标签:字符 exit please 指定 work write == 网卡 %s
python实例#!/usr/bin/env python
import re
import sys
import subprocess
#定义配置ip地址函数
def configip(fname,ip_addr,if_ind):
content = ‘‘‘TYPE=Ethernet
BOOTPROTO=none
NAME=eth%s
DEVICE=eth%s
ONBOOT=yes
IPADDR=%s
PREFIX=24
‘‘‘ % (if_ind,if_ind,ip_addr)
with open(fname,‘w‘) as fobj:
fobj.write(content)
#定义检测ip地址是否合法函数
def check_ip(ip_addr):
m = re.match(r‘(\d{1,3}\.){3}\d{1,3}$‘,ip_addr)
if not m:
return False
return True
#定义配置主机名函数
def config_hostname():
fhostname = ‘/etc/hostname‘
hostname = raw_input(‘Input You Hostname: ‘)
with open(fhostname,‘w‘) as fobj:
fobj.write(hostname)
subprocess.Popen(‘hostname %s ‘ % hostname,shell=True)
#定义显示菜单函数
def show_menu():
prompt = ‘‘‘Configure IP Address:
(0)eth0
(1)eth1
(2)eth2
(3)eth3
Your choice(0/1/2/3):‘‘‘
try:
if_ind = raw_input(prompt).strip()[0]
except:
print ‘Invalid raw_input.‘
sys.exit(1)
if if_ind not in ‘0123‘:
print ‘Wrong Selection. Use 0/1/2/3/‘
sys.exit(2)
fname = ‘/etc/sysconfig/network-scripts/ifcfg-eth%s‘ % if_ind
ip_addr = raw_input(‘ip address: ‘).strip()
result = check_ip(ip_addr)
if not result:
print ‘Invalid ip address!‘
sys.exit(3)
configip(fname,ip_addr,if_ind)
subprocess.Popen(‘systemctl restart network‘,shell=True)
print ‘\033[32;1mConfigure ip address done. Please execute "systemctl restart NetworkManager"\033[0m‘
if __name__ == ‘__main__‘:
main_menu = ‘‘‘(0)config_hostname
(1)config_ipaddr
Your choice(0/1)‘‘‘
try:
ind = raw_input(main_menu).strip()[0]
except:
print ‘Invalid raw_input.‘
sys.exit(4)
if ind not in ‘01‘:
print ‘Wrong Selection. Use 0/1‘
sys.exit(5)
if ind == ‘0‘:
config_hostname()
show_menu()
备注:
1. 通过指定方式的办法来获取地址,如果未指定的化可能会出现问题,有三种模式:static 静态ip;dhcp 动态ip;none 无(不指定)
2. m = re.match(r‘(\d{1,3}\.){3}\d{1,3}$‘,ip_addr) # r 表示 raw string(原始字符串常量),用于规避反斜杠的转义
标签:字符 exit please 指定 work write == 网卡 %s
原文地址:http://blog.51cto.com/11389430/2167950