代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import os
import sys
import time
import pymysql
import queue
import json
import wmi
import win32api
import re
import ctypes


def loadtext(path):
try:
f = open(path,"r")
txt = f.read()
f.close()
return txt
except Exception as e:
print("load file error! {}".format(path))
return None
return None


def writefile(path, text):
try:
f = open(path,"w")
text = f.write(text)
f.close()
return True
except Exception as e:
print("write file error! {}".format(path))
return False
return False

# to json
def txt2json(text):
try:
jsondict=json.loads(text)
return jsondict
except Exception as e:
print('json error!')
return None
return None

# to txt
def json2txt(jsondict):
try:
text=json.dumps(jsondict)
return text
except Exception as e:
print('json error!')
return None
return None


# wmi修改IP
def modserverip(mdict):
intReboot=0
wmiService = wmi.WMI()
colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
if len(colNicConfigs)<1:
print("not find network adapter")
return False
objNicConfig = colNicConfigs[0]
arrIPAddresses =[mdict['serverAddress']]
arrSubnetMasks =[mdict['netmask']]
arrDefaultGateways =[mdict['gateway']]
arrGatewayCostMetrics =[1]
#arrDNSServers =['172.16.151.10']
intReboot =0
returnValue = objNicConfig.EnableStatic(IPAddress= arrIPAddresses,SubnetMask= arrSubnetMasks)
if returnValue[0]==0:
print ('设置IP成功')
elif returnValue[0]==1:
print ('设置IP成功')
intReboot +=1
else:
print ('修改IP失败: IP设置发生错误')
return False
returnValue = objNicConfig.SetGateways(DefaultIPGateway= arrDefaultGateways,GatewayCostMetric= arrGatewayCostMetrics)
if returnValue[0]==0:
print ('设置网关成功')
elif returnValue[0]==1:
print ('设置网关成功')
intReboot +=1
else:
print ('修改IP失败: 网关设置发生错误')
return False
#returnValue = objNicConfig.SetDNSServerSearchOrder(DNSServerSearchOrder= arrDNSServers)
#if returnValue[0]==0:
# print ('设置DNS成功')
#elif returnValue[0]==1:
# print ('设置DNS成功')
# intReboot +=1
#else:
# print ('修改IP失败: DNS设置发生错误')
# return False
if intReboot >0:
print ('need reboot computer')
else:
print ('修改IP结束')
return True

# run
def run(cmd, model=0):
if not is_admin():
print("runas admin")
state = runasadmin(cmd)
print('state {}'.format(state))
return state
jsontext=cmd.replace('\'','\"')
state=0
mdict={}
mdict=txt2json(jsontext)
if mdict:
if 0 == model:
if not modserverip(mdict):
state = 1
else:
if not modserverip2(mdict):
state = 1
print('state {}'.format(state))
return state

# 匹配中文网卡名,取第一块网卡名
def FindFirstNetworkName():
result = os.popen("ipconfig")
if not result:
print("cmd ipconfig error!")
return ""
s = result.read()
if not s:
print("ipconfig result error!")
return ""
# print(s)
pattern = re.compile("以太网适配器 (.*):") # 查找数字
finds = re.findall(pattern, s)
resname = ""
for name in finds:
# 路过虚拟网卡
if -1 != name.find("VMnet"):
continue
resname = name
break
return resname

# netsh修改IP
def modserverip2(mdict):
ip = mdict['serverAddress']
mask = mdict['netmask']
way = mdict['gateway']
name = FindFirstNetworkName()
if not name:
return False
cmd = " netsh interface ip set address \"{}\" static {} {} {} 1".format(name, ip , mask, way)
print(cmd)
result = os.popen(cmd)
if not result:
print(cmd+" -> error!")
return False
s = result.read()
if "" != s:
print(s)
return False
return True

# win10下UAC调到最低,提权时不会弹出UAC框。
def run_runas(name, calls):
state = 1
try :
callsstr= json2txt(calls)
print("run_runas:{},args:{}".format(name, calls))
# 参数
# 父进程句柄 要进行的操作 文件名 参数 文件夹名 显示模式
# 具体解释msdn搜索ShellExecute
# res = win32api.ShellExecute(0, 'runas', name, callsstr, '', 0)
res = ctypes.windll.shell32.ShellExecuteW(0, "runas", name, callsstr, '', 0)
print(res)
# 调用成功返回42
if 42 == res:
state = 0
except BaseException as e:
return state, str(e)
return state


def runasadmin(jsontext):
run = sys.argv[0]
state = run_runas(run, jsontext)
return state



def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False


def test():
is1 = is_admin()
return


if __name__ == "__main__":
cmd1=""
model = 0
args = len(sys.argv)
if args > 2:
cmd1 = sys.argv[1]
model = 1
elif args > 1:
cmd1 = sys.argv[1]
model=0
else:
print('this is test code!')
#cmd1='{"serverAddress":"192.168.2.151","ipEnd":"ipEnd","ipStart":"ipStart","netmask":"netmask","gateway":"gateway","id":"1"}'
cmd1="{'serverAddress':'192.168.2.151','netmask':'netmask','gateway':'gateway','id':'1'}"
#os._exit(1)
print('cmd: {}'.format(cmd1))
ex = run(cmd1, model)
os._exit(ex)