简体   繁体   English

如何在python中设置“ ip地址”,“ DNS”,“主机名”,“ MAC地址”?

[英]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. 我想编写用于网络安全IP扫描的脚本,这样的工具可能需要欺骗其主机NIC状态以进行测试,例如,设置NIC的IP地址,设置DNS地址,同时设置主机名,MAC地址和启用/禁用NIC适配器。

I googled and found most soultion is using "popen" invoking system existing tools such as 我在Google上搜索后发现,大多数灵魂是使用“ popen”调用系统现有的工具,例如

>>> 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. 另外,还有一些模块可以读取NIC的状态,例如netifaces,但似乎所有模块都是“只读”的,但不能直接写入。

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. 由于我发现没有模块可以直接设置NIC状态,因此我在这里寻求帮助,以查看是否有人可以帮忙或提供更好的方法。

Any hints will be appricated. 任何提示将被应用。 Thanks! 谢谢!

Rgs KC 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. 之前我曾经做过,没有像这样的低级特定于OS的东西的显式Python os接口。 You just have to write an (OS-specific) wrapper to UNIX(/Windows/Mac) commands. 您只需要为UNIX(/ Windows / Mac)命令编写一个(特定于操作系统的)包装器即可。 It's not hard, just tedious. 这并不难,只是乏味。

os.popen*() is very deprecated (since 2.4), use subprocess module . os.popen *()从2.4开始非常不推荐使用,请使用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. subprocess.Popen()接口确实令人讨厌 ,您几乎肯定会为自己的理智编写一个包装器,以提供合理的默认arg值并整理您的代码。 Obviously pay close attention to command exit statuses, path prefixes etc. Not sure how much you care about portability. 显然,请密切注意命令退出状态,路径前缀等。不确定您是否在乎可移植性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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