How to Get an ip Address Using python3 in linux

  • 2021-07-18 08:19:57
  • OfStack

Preface

This article mainly introduces how to use python3 to get ip address in linux, the article through the example code introduction is very detailed, for everyone's study or work with a reference to learning value, the need for friends can refer to the following.

1. No parameters


#!/usr/bin/python
 
# -*- coding: UTF-8 -*-
 
import os
 
 
def get_ip():
  # Note that double quotation marks are used instead of single quotation marks , And assume that the default is the 1 Network card , Please modify the code appropriately in special environment  
  out = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()
  ip=out.split('\n')[0]
  return ip
res = get_ip()
print(res)

2. With parameters

If the server is an centos6/centos7 machine, the above method can not be obtained correctly for centos7, and sometimes it is not the first network card to be obtained

The following method can be used in both windows and linux operating systems. windows does not need parameters, and linux parameters are network card names


# -*- coding: UTF-8 -*-
 
import socket
import os
import platform
import re
 
 
def get_ip(*args):
  if platform.system() == 'Windows':
    my_name = socket.getfqdn(socket.gethostbyname('localhost'))
    my_addr = socket.gethostbyname(my_name)
    ip = my_addr.split('\n')[0]
    return ip
  else:
 
    my_addr = os.popen(
      "ifconfig | grep -A 1 %s|tail -1| awk '{print $2}'" % args[0]).read()
    ip = re.search(r'(?<![\.\d])(?:25[0-5]\.|2[0-4]\d\.|[01]?\d\d?\.)'
                r'{3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![\.\d])',my_addr).group()
    return ip
 
 
if __name__ == '__main__':
  f = get_ip('eno16777736')
  print(f)

Related articles: