Python IP Switching

Source: Internet
Author: User

Recently in the notebook reinstall the virtual machine, because at home in the company often need to switch IP, modify the IP configuration file, feel quite cumbersome, so simply write a script to automatically switch IP, mainly read the configuration file modification, details as follows:

1. Create the configuration file:

# cat Ip.conf[home]ip = 192.168.7.150gateway = 192.168.7.1[work]ip = 10.7.93.150gateway = 10.7.93.1

2. Script instance

#!/usr/bin/env  python# conding = utf-8# finame swtch_ip.py# this  is swtch ip python fileimport socket,os,sysimport ConfigParserimport  Timefrom optparse import optionparserdef init ():     global ips     global GATEWAYS    config =  Configparser.configparser (    dir = os.path.dirname) (Os.path.abspath (__file__))     conf = dir +  "/conf"     filepath =  " %s/ip.conf " % (conf)     if not os.path.exists (filepath):         raise  "error: ip.conf is not it!"     config.read (filepath)     ips = config.get (Options.type, " IP ")     gateways = config.get (optionS.type, "gateway")     print  "======[%s] start get new options, please wait... ====== " % (options.type)     print "%s config  file ip is %s,gateway is %s " % (options.type,ips,gateways) def getopts ():     msg_usage= ' Python %s -t home '  % sys.argv[0]     optparser=optionparser (msg_usage)     optparser.add_option ('-t ', action= ' store ', Type= ' string ', dest= ' type ', default= ' work ', Help=u ' Type:work,home ')      (Options,args) = Optparser.parse_args ()     return optionsdef ipconfig ():     Ipconfigfile = open ('/etc/sysconfig/network-scripts/ifcfg-eth0 ', ' R ')     while  true:        ipconfiglines = ipconfigfile.readlines ()         if not ipconfiglines:    break    # Ipconfigfile.close () if  "ipaddr"  in ipconfiglines[4] and  "GATEWAY"  in  ipconfiglines[3]:    print  "====== change ip and gateway,  please wait... ====== "            temp  = ipconfiglines[4].split (' \ "')              a = temp[1]            temp1  = ipconfiglines[3].split (' \ "')             b  = temp1[1]            print  " ifcfg-et0 config old ip is %s and old gateway is %s " % ( b)             edit_file = os.system (' sed -i  ' s/' +a+ '/' +IPS+ '/g;s/' +b + '/' +gateways+ '/g '  /etc/sysconfig/network-scripts/ifcfg-eth0 ')              if edit_file == 0:                 print  ' edit ifcfg-eth0 ip and  Gateway is ok,restart network restart '                  restart_network = os.system ('/etc/init.d/network  restart ') if restart_network == 0:    print  "Network restart  succ! "                 else:             print  "network restart fail!"     else:                 print  ' Edit ifcfg-eth0 ip is error ' else:    print  "no  Ip address and gateway!!! " if __name__ ==  ' __main__ ':     if len (SYS.ARGV) <1 and  sys.argv[1] !=  '-h '  and sys.argv[1] !=  '--help ':         print  ' usage:  python %s -t work         python %s -h|--help '  %  (sys.argv[0],sys.argv[0])          sys.exit (1)     options = getopts ()      init ()     ipconfig ()

3. View Help

# python swich_ip.py--helpusage:python swich_ip.py-t homeoptions:-H,--help show this help message and Exit-t TYPE Type:work,home

4. Run the test

# python swich_ip.py -t home======[home] start get new options,please  wait... ======home config file ip is 192.168.7.250,gateway is  192.168.7.1====== change ip and gateway, please wait... ======ifcfg-et0  config old IP is 192.168.7.250 and old GATEWAY is  192.168.7.1edit ifcfg-eth0 ip and gateway is ok,restart network  Restart is shutting down the interface  eth0:                                          [OK] Close Loopback interface:                                                [OK] eject loopback interface:                                                [OK] Popup interface  eth0:                                              [Determine]network  restart succ!

5. Results

# cat/etc/sysconfig/network-scripts/ifcfg-eth0device= "eth0" onboot= "yes" bootproto= "static" gateway= "192.168.7.1" Ipaddr= "192.168.7.250"



This article is from the "& Think Far Dawn" blog, make sure to keep this source http://kling.blog.51cto.com/3320545/1606396

Python IP Switching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.