获取局域网ip
2021-11-27
python
1397
def get_local_ip(): try: socket_objs = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ip_from_ip_port = [(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in socket_objs][0][1] ip_from_host_name = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1] local_ip = [l for l in (ip_from_ip_port, ip_from_host_name) if l][0] except (Exception) as e: print("get_local_ip found exception : %s" % e) return local_ip if ("" != local_ip and None != local_ip) else socket.gethostbyname(socket.gethostname())
返回:
192.168.0.XXX
# 更新hosts dns信息 使局域网域名解析到本地 def main(last_ip): if 255 > int(last_ip) > 100: pass else: print("参数错误,请输入100~255之间") return hosts_file = r"C:\Windows\System32\drivers\etc\hosts" # 读取hosts with open(hosts_file, "r", encoding="utf-8") as f: content = f.read() # 替换内容 content = re.sub(r"192\.168.0\.\d+(.+)", "192.168.0." + str(last_ip) + r"\1", content) lst = re.findall(r"192\.168.0\.\d+.+", content) print("\n".join(lst)) # 写入hosts with open(hosts_file,"w",encoding="utf-8") as f: f.write(content) if __name__ == "__main__": main(input("请输入ip:192.168.0.")) input("按下Enter,退出")
使用参数:
from optparse import OptionParser from optparse import OptionGroup class Opt: parser = None def __init__(self, usage='Usage: %prog [options] arg1 arg2 ...', version='%prog 1.0'): self.parser = OptionParser(usage=usage, version=version) ''' parser.add_option('-v','--verbose', action='store_true',dest='verbose',default=True, help='make lots of noise [default]') ''' def addOption(self, *args, **kwargs): self.parser.add_option(*args, **kwargs) ''' group = OptionGroup(parser,'Dangerous Options', 'Caution: use these options at your own risk.' 'It is believed that some of them bite.') 添加option parser.add_option_group(group) ''' def group(self, title, description): group = OptionGroup(self.parser, title=title, description=description) self.parser.add_option_group(group) # 获取结果 def parse_args(self): return self.parser.parse_args()
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论