• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

 

posted on 2022-04-14 11:17  yxchun  阅读(378)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3