In the previous period of time need to batch modify the server configuration file, which contains the IP address of the machine,because the server has multiple network cards and configures multiple IP addresses,initially wanted to write Shell script batch modification, but since now is learning python, why not study the use of Python to write, search on the web related articles, according to their actual situation, there are the following script:Use Python to get the IP address of the specified network card:
#!/usr/bin/env python
# -.- coding: utf-8 -.-
# By Sandler
import socket
import fcntl
import struct
def get_ip_addr(ifname): #ifname传入参数(网卡)
‘‘‘
获取本机指定网卡的ip地址
:param ifname: 指定网卡
:return: 默认None
‘‘‘
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack(‘256s‘,ifname[:15])
)[20:24])
ip = get_ip_addr(‘eth0‘)
print(ip)
Modify the configuration file to add content with Python:
#!/user/bin/env python
# -.- coding: utf-8 -.-
# By Sandler
res_file = ‘/etc/resolv.conf‘ # 定义配置文件变量
f = open(res_file,‘a‘) # 以追加模式打开配置文件
f.write(‘\nservername1.1.1.1‘) # 把dns配置追加到最后一行
f.close() # 关闭文件
# ————————————————————————————————————————————————
fs_file = ‘/etc/fstab‘
f = open(fs_file,‘a‘)
f.write(‘\nxx xx xx %s xx xx‘ % ip) #追加一条新的挂载项,把ip写入其中。
f.close()
After the script is written, use PSCP to send it to the server in bulk, Pssh execute it.
From for notes (Wiz)
PY gets the IP address of the specified network card for this machine