简体   繁体   中英

how to setup “ip address”,“DNS”, “hostname”,“MAC address” in python?

I want to write a script for network security IP scan porpose, such a tool may need spoofing it's host NIC status for testing purpose, for example, to setup NIC's ip address, to setup DNS address, while to setup hostname, MAC address and enable/disable the NICs adapter.

I googled and found most soultion is using "popen" invoking system existing tools such as

>>> import os
>>> p=os.popen("/sbin/ifconfig eth0")
>>> t=p.read()
>>> p.close() 

to get return from system. Also there's modules can reading the status of the NIC, such as netifaces, but seems all of them are "READ ONLY" but can not wirte directly.

Since I found no modules can setup the NIC status directly, then I asks help here to see if someone can give a hand or show a more better way.

Any hints will be appricated. Thanks!

Rgs KC

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 
# Copyright 2014 by mimvp.com


def get_valid_ip(cls, ip_str):
    ip_str_new = ''
    ip_re = re.compile(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b')
    ipList = ip_re.findall(ip_str)
    if len(ipList) >= 1:
        ip_str_new = ipList[0]
        ip_str_new = ip_str_new.lstrip("0")     # '05.9.87.163'  ==>  '5.9.87.163'
    return ip_str_new


if __name__ == '__main__':
    result = os.popen("/sbin/ifconfig en0 | grep broadcast")
    ip_inet = result.read()
    for ip_str in ip_inet.split(" "):
        if self.get_valid_ip(ip_str) : 
            print ip_str

I did this previously, there's no explicit Python os interface to low-level OS-specific stuff like that. You just have to write an (OS-specific) wrapper to UNIX(/Windows/Mac) commands. It's not hard, just tedious.

os.popen*() is very deprecated (since 2.4), use subprocess module .

The interface to subprocess.Popen() is admittedly irritating , you'll almost surely end up writing a wrapper for your own sanity to supply sane default arg values and unclutter your code. Obviously pay close attention to command exit statuses, path prefixes etc. Not sure how much you care about portability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM