PY gets the IP address of the specified network card for this machine

Source: Internet
Author: User

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:
  
 
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By Sandler
  4. import socket
  5. import fcntl
  6. import struct
  7. def get_ip_addr(ifname): #ifname传入参数(网卡)
  8. ‘‘‘
  9. 获取本机指定网卡的ip地址
  10. :param ifname: 指定网卡
  11. :return: 默认None
  12. ‘‘‘
  13. s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  14. return socket.inet_ntoa(fcntl.ioctl(
  15. s.fileno(),
  16. 0x8915,
  17. struct.pack(‘256s‘,ifname[:15])
  18. )[20:24])
  19. ip = get_ip_addr(‘eth0‘)
  20. print(ip)
Modify the configuration file to add content with Python:
  
 
  1. #!/user/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By Sandler
  4. res_file = ‘/etc/resolv.conf‘ # 定义配置文件变量
  5. f = open(res_file,‘a‘) # 以追加模式打开配置文件
  6. f.write(‘\nservername1.1.1.1‘) # 把dns配置追加到最后一行
  7. f.close() # 关闭文件
  8. # ————————————————————————————————————————————————
  9. fs_file = ‘/etc/fstab‘
  10. f = open(fs_file,‘a‘)
  11. f.write(‘\nxx xx xx %s xx xx‘ % ip) #追加一条新的挂载项,把ip写入其中。
  12. 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

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.