Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

linux - How to assign IP address to interface in python?

I have python script that set the IP4 address for my wireless and wired interfaces. So far, I use subprocess command like :

subprocess.call(["ip addr add local 192.168.1.2/24 broadcast 192.168.1.255 dev wlan0"])

How can I set the IP4 address of an interface using python libraries? and if there is any way to get an already existing IP configurations using python libraries ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With pyroute2.IPRoute:

from pyroute2 import IPRoute
ip = IPRoute()
index = ip.link_lookup(ifname='em1')[0]
ip.addr('add', index, address='192.168.0.1', mask=24)
ip.close()

With pyroute2.IPDB:

from pyroute2 import IPDB
ip = IPDB()
with ip.interfaces.em1 as em1:
    em1.add_ip('192.168.0.1/24')
ip.release()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...