Last active
November 17, 2025 14:06
-
-
Save mdpuma/a70b83978a4f3e92717a85facbdce4c3 to your computer and use it in GitHub Desktop.
Script that generate network-scripts file for required ip range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import os | |
| import sys | |
| import getopt | |
| if __name__ == "__main__": | |
| options, remaining = getopt.getopt(sys.argv[1:], 'r:i', ['range=', 'iface=']) | |
| #print('ARGV :', sys.argv[1:]) | |
| #print('OPTIONS :', options) | |
| iprange = None | |
| interface = None | |
| for opt, arg in options: | |
| if opt in ('-r', '--range'): | |
| iprange = arg | |
| elif opt in ('-i', '--iface'): | |
| interface = arg | |
| if iprange == None or interface == None: | |
| print("Usage: "+sys.argv[0]+" --range=1.1.1.1-2 --iface=eth0\n") | |
| sys.exit(1) | |
| firstip, last_octet = iprange.split('-') | |
| config_file = "/etc/sysconfig/network-scripts/ifcfg-"+interface | |
| config_range_file = "/etc/sysconfig/network-scripts/ifcfg-"+interface+"-range0" | |
| if os.path.isfile(config_file) == False: | |
| print("file "+config_file+" is not exists\n") | |
| sys.exit(1) | |
| a,b,c,d = firstip.split('.') | |
| lastip = '.'.join( [a, b, c, last_octet] ) | |
| secondip = '.'.join( [a, b, c, str(int(d)+1)] ) | |
| gatewayip = '.'.join( [a, b, c, '1'] ) | |
| count = int(last_octet) - int(d) | |
| if count>0: | |
| print("Let's generate configs for "+str(count)+" ipv4 addresses") | |
| ifcfg_file = open(config_file, "w") | |
| ifcfg_file.write("DEVICE=\""+interface+"\"\n") | |
| ifcfg_file.write("BOOTPROTO=\"none\"\n") | |
| ifcfg_file.write("ONBOOT=\"yes\"\n") | |
| ifcfg_file.write("TYPE=\"Ethernet\"\n") | |
| ifcfg_file.write("IPADDR=\""+firstip+"\"\n") | |
| ifcfg_file.write("NETMASK=\"255.255.255.0\"\n") | |
| ifcfg_file.write("GATEWAY=\""+gatewayip+"\"\n") | |
| ifcfg_file.write("DNS1=\"8.8.8.8\"\n") | |
| ifcfg_file.write("DNS2=\"8.8.4.4\"\n") | |
| if count>1: | |
| ifcfg_file.write("ARPCHECK=no\n") | |
| ifcfg_range_file = open(config_range_file, "w") | |
| ifcfg_range_file.write("IPADDR_START=\""+secondip+"\"\n") | |
| ifcfg_range_file.write("IPADDR_END=\""+lastip+"\"\n") | |
| ifcfg_range_file.close() | |
| else: | |
| if os.path.isfile(config_range_file): | |
| os.unlink(config_range_file) | |
| ifcfg_file.close() | |
| print("Check results "+config_file+"\n\n") | |
| print("After you may reload network: \nifdown "+interface+" && ifup "+interface+"\n") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment