python 调用dos修改IP 、网关 、子网掩码
想要修改成功,必须用管理员才行;
有2种方法:1)python要调用管理员窗口 ; 2)写好后的py文件用管理员执行;
方法1
import ctypes, sys, os, time import datetime cmd1 = "netsh interface ip set address \"VMware Network Adapter VMnet8\" static " cmd2 = " 255.255.255.0 192.168.109.1" def is_admin(): try: print("admin-",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) return ctypes.windll.shell32.IsUserAnAdmin() except: time.sleep(2) print("no admin-",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) return False def admin_exe(cmd) : print('先进入EXE ',datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) if is_admin(): print("admin_exe函数内,以管理员权限运行 " ,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) time.sleep(10) os.system(cmd) print("执行了更改IP语句 ",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) time.sleep(30) print("时间结束,弹窗消失 ",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) time.sleep(2) else: if sys.version_info[0] == 3: print('admin_exe函数内,还没有管理员权限 ',datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) print("执行了管理员身份语句",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) def getIP(ip): return ip if __name__ == '__main__': print("admin_exe前",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) global deviceIP
# 输入要修改的IP str = input("tipmsg:") deviceIP = str cmd = cmd1+deviceIP+cmd2 print(cmd) admin_exe(cmd) print("admin_exe后",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
解析:
1) 通过main进入,输入IP,先判断是否为管理员,如果不是执行升级为管理员身份语句 :ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1);此时就打开了管理员窗口。
2)程序自动再次进入main方法(此时是管理员窗口);输入IP,执行修改IP命令;
代码解析:
dos修改IP语句解释 ,请参考:
https://www.cnblogs.com/ychun/p/16143627.html
文章参考:https://blog.csdn.net/qq_43909184/article/details/107424740
以管理员执行操作,请参考如下:
https://blog.csdn.net/xuhui_liu/article/details/73832743
https://blog.csdn.net/qq_42028065/article/details/102958208
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)