1 2 /** 3 * @name CeL function for WMI 4 * @fileoverview 5 * 本檔案包含了 Windows Management Instrumentation 的 functions。 6 * @since 7 */ 8 9 10 if (typeof CeL === 'function') 11 CeL.setup_module('application.OS.Windows.WMI', 12 function(library_namespace, load_arguments) { 13 14 // nothing required 15 16 17 18 /** 19 * null module constructor 20 * @class WMI 的 functions 21 */ 22 CeL.application.OS.Windows.WMI 23 = function() { 24 // null module constructor 25 }; 26 27 /** 28 * for JSDT: 有 prototype 才會將之當作 Class 29 */ 30 CeL.application.OS.Windows.WMI 31 .prototype = { 32 }; 33 34 35 36 37 38 39 40 // WMI set ================== 41 42 /* 2007/5/22 23:34:43 43 WMI: Windows Management Instrumentation 44 http://www.codecomments.com/archive298-2004-5-203306.html 45 http://msdn2.microsoft.com/en-us/library/Aa394616 46 http://msdn2.microsoft.com/en-us/library/aa389290.aspx 47 http://msdn2.microsoft.com/en-us/library/aa389763.aspx 48 http://msdn2.microsoft.com/en-us/library/aa393854.aspx SWbemServices 49 http://msdn2.microsoft.com/en-us/library/ms525320.aspx 50 http://www.serverwatch.com/tutorials/article.php/1476831 51 http://www.serverwatch.com/tutorials/article.php/1476861 52 http://www.serverwatch.com/tutorials/article.php/1476871 53 http://www.serverwatch.com/tutorials/article.php/1476941 54 55 string moniker: 56 [[/root/]cimv2:][from[.v]] [/|\\]root[/|\\] 57 58 object moniker: 59 { 60 prefix:'WinMgmts:', // moniker prefix 61 security:'{impersonationLevel=impersonate}!', 62 computer:'.', // Computer string(localhost '.') 63 p:'cimv2', // '/root/' will auto added 64 path:'/root/cimv2', // Namespace e.g., \root\default 65 66 from:, // select from ~ 67 where:, // select from where ~ ** You MUST check the string yourself!! This function won't do it! 68 v:, // value to get 69 value:, // value used in moniker 70 71 flag:48, // flag to call SWbemServices.ExecQuery Method 72 } 73 74 prefix+security+computer+path+':'+from+'='+value http://msdn2.microsoft.com/en-us/library/aa389292.aspx 75 76 TODO: 77 多次呼叫最佳化 78 */ 79 function WMI_data(moniker,func){ // moniker, for each do function 80 var i,oWMIS,_m={ 81 prefix:'WinMgmts:' 82 ,security:'{impersonationLevel=impersonate}!' 83 ,computer:'.' 84 ,p:'cimv2' 85 ,path:'' 86 ,from:'' 87 ,value:'' 88 ,v:'' 89 ,flag:48 // 32: wbemFlagForwardOnly + 16: wbemFlagReturnImmediately 90 }; 91 if(!moniker) 92 moniker=''; 93 94 if(typeof moniker=='string'){ 95 // parse moniker 96 _m.from=moniker; 97 // 取得path 98 if(i=_m.from.match(/^([^:]+):([^\/\\]*)$/)){ 99 if(/^[\/\\]/.test(i[1]))_m.path=i[1];else _m.p=i[1]; 100 _m.from=i[2]; 101 } 102 // 取得from[.v] 103 if(i=_m.from.match(/^([^.]+)\.(.*)$/))_m.from=i[1],_m.v=i[2]; 104 }else for(i in moniker)_m[i]=moniker[i]; 105 106 // create object 107 try{ 108 //with(_m)alert(prefix+security+'//'+computer+(path||'/root/'+p)+(value||value===0?':'+from+'='+value:'')); 109 with(_m)oWMIS=GetObject(prefix+security+'//'+computer+(path||'/root/'+p) 110 //+(func||v?'':(from?':'+from+(value||value==0?'':'='+value):'')) // 有func||_m.v時無條件捨棄,到後面再搞。 111 +(value||value===0?':'+from+'='+value:'') 112 ); 113 //oLoc=new ActiveXObject("WbemScripting.SWbemLocator");oSvc=oLoc.ConnectServer(sComputer||null,"root\\default");oReg=oSvc.Get("StdRegProv"); // http://msdn.microsoft.com/library/en-us/wmisdk/wmi/swbemobject_execmethod_.asp 114 }catch(e){ 115 return; 116 /* useless? 117 try{ 118 with(new ActiveXObject("WbemScripting.SWbemLastError")) // Error Handling 119 return {ProviderName:ProviderName,ParameterInfo:ParameterInfo,Operation:Operation,Description:Description}; 120 }catch(_e){throw e;} 121 */ 122 } 123 if(!func&&!_m.from)return oWMIS; 124 125 // do search 126 var oE; 127 try{ 128 // http://msdn2.microsoft.com/en-us/library/aa393866.aspx 129 oE=oWMIS.ExecQuery('Select * From '+_m.from+(_m['where']?' Where '+_m.where:'') 130 ,'WQL' // String that contains the query language to be used. If specified, this value must be "WQL". 131 ,_m.flag 132 ); 133 }catch(e){ 134 // 程式庫未登錄。 135 // 此時 typeof oWMIS=='object' 136 popErr(e,0,'WMI_data: error occurred!'); 137 //if(438!=(e.number&0xFFFF))return; 138 return; // return {item:function(){}}; // or return a object using wbemQueryFlagPrototype 139 } 140 oE=new Enumerator(oE); // wbemFlagForwardOnly:32+wbemFlagReturnImmediately:16 141 //if(func)for(;!oE.atEnd()&&!func(oE.item());oE.moveNext()); 142 if(func)while(!oE.atEnd()&&!func(oE.item()))oE.moveNext(); 143 else return _m.v||_m.v===0?oE.item()?oE.item()[_m.v]:null:oE; 144 }; 145 146 /* 用在將 WMI date 轉成 javascript date, old: WMIDateStringToDate 147 http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept04/hey0907.mspx 148 http://www.microsoft.com/technet/scriptcenter/resources/qanda/aug05/hey0802.mspx 149 150 TODO: 151 return ms 152 */ 153 WMI_data.DateStringToDate=function(t){ 154 if(!t)return new Date(0); 155 var m=(''+t).match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d+)?([+ \-]\d+)?$/); 156 // http://msdn2.microsoft.com/en-us/library/474de325.aspx 157 return m?new Date(m[1],m[2]-1,m[3],m[4],m[5],m[6],m[7]*1e3):t; // locale會自己調整 158 }; 159 160 /* 用在取得 WMI object 之 property 161 http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/other/wmi/ 162 http://msdn.microsoft.com/en-us/library/aa393741%28VS.85%29.aspx 163 */ 164 WMI_data.getProperties = function(o, is_VBA, is_Date) { 165 var oP = new Enumerator(o.Properties_), ph = {}, p; 166 while (!oP.atEnd()) { 167 o = p = oP.item(); 168 169 if (0 && o.Name === 'IPAddress') { 170 alert(p); 171 alert('' + p + '\n[' + (typeof p) + ']\n' 172 // +(new VBArray(p)).toArray() 173 + Object.prototype.toString.call(p)); 174 for (var i in p) 175 alert('' + Object.prototype.toString.call(p[i]) + '\n' + i + ' ' + p[i]); 176 } 177 178 // 自動別日期 179 if (typeof p == 'object' && /^\d{14}(\.\d+)?([+ \-]\d+)?$/.test('' + p)) 180 p = this.DateStringToDate(p); 181 // 自動別 VBA 182 else if (typeof p == 'unknown') 183 // from VBA_to_JSA() 184 try { 185 p = new VBArray(p).toArray(); 186 } catch (e) { 187 } 188 ; 189 ph[o.Name] = p; 190 oP.moveNext(); 191 } 192 193 // o=[];for(p in ph)o.push(p+': '+ph[p]);sl(o.join('\n')); 194 return ph; 195 }; 196 197 198 199 /* cause error! requires Windows 2003 DNS 200 http://forums.devshed.com/dns-36/dns-through-wmi-in-net-140427.html 201 http://www.activexperts.com/activmonitor/windowsmanagement/scripts/networking/dns/server/ 202 http://www.113317.com/blog/article.asp?id=543 203 http://blogs.msdn.com/mpoulson/archive/2006/05/10/594950.aspx 204 http://www.ureader.com/message/3258511.aspx 205 http://www.scriptinganswers.com/forum/forum_posts.asp?TID=516&PID=3124 206 if(0){ 207 var qHost='213.22.211.in-addr.arpa',qIP=WMI_data({p:'MicrosoftDNS',from:'MicrosoftDNS_PTRType',where:"OwnerName='"+qHost+"'"}).item(); 208 alert(qIP.RecordData); 209 } 210 */ 211 212 213 214 215 /* 216 http://msdn2.microsoft.com/en-us/library/aa394239.aspx 217 http://tech.163.com/05/0406/10/1GL8FUG200091589.html 218 219 test: 220 with(getSysInfo())alert(Caption+' '+CSDVersion+' '+OtherTypeDescription+'(SP '+ServicePackMajorVersion+'.'+ServicePackMinorVersion+') [Version '+Version+']' 221 +'\nWindowsDirectory: '+WindowsDirectory 222 +'\nSystemDirectory: '+SystemDirectory 223 +'\nFreePhysicalMemory: '+turnSI(FreePhysicalMemory)+'/'+turnSI(PhysicalMemory)+'B ('+PhysicalMemory+' bytes)' 224 +'\nOSLanguage: '+OSLanguage+' (0x'+hex(OSLanguage)+')' // http://msdn.microsoft.com/zh-tw/library/system.globalization.cultureinfo%28VS.80%29.aspx 225 +'\nCountryCode: '+CountryCode 226 +'\nCodeSet: CP'+CodeSet // http://en.wikipedia.org/wiki/Code_page http://msdn.microsoft.com/en-us/library/dd317756%28VS.85%29.aspx 227 +'\nLocale: '+Locale 228 +'\nCurrentTimeZone: '+gDate(CurrentTimeZone*60*1000) 229 +'\nMUILanguages: '+MUILanguages 230 +'\nBootUpTime: '+LastBootUpTime.toLocaleString() 231 +'\nLocalDateTime: '+LocalDateTime.toLocaleString() 232 +'\n系統運行 Uptime: '+gDate(Uptime)//+' ms' 233 +'\n系統 counter: '+Timestamp+' s' 234 +'\nCSName: '+CSName 235 +'\nRegisteredUser: '+RegisteredUser 236 );WScript.Quit(); 237 */ 238 239 getSysInfo[generateCode.dLK]='WMI_data'; 240 function getSysInfo(){ 241 var o=WMI_data('Win32_OperatingSystem').item(),r; 242 with(o)r={ 243 Caption:o.Caption.replace(/\s+$/,''), // 系統 244 Name:o.Name, 245 CSDVersion:o.CSDVersion, 246 ServicePackMajorVersion:o.ServicePackMajorVersion||(isNaN(o.ServicePackMajorVersion)?'':0), 247 ServicePackMinorVersion:o.ServicePackMinorVersion||(isNaN(o.ServicePackMinorVersion)?'':0), 248 OtherTypeDescription:o.OtherTypeDescription||'', 249 Version:o.Version, // 系統版本 250 251 WindowsDirectory:o.WindowsDirectory, 252 SystemDirectory:o.SystemDirectory, 253 254 CSName:o.CSName, 255 RegisteredUser:o.RegisteredUser, 256 257 CurrentTimeZone:o.CurrentTimeZone, 258 // 系統最後一次啟動的時間 259 // see: WMI_data('Win32_PerfRawData_PerfOS_System.SystemUpTime') 260 LastBootUpTime : WMI_data.DateStringToDate(o.LastBootUpTime), 261 LocalDateTime : WMI_data.DateStringToDate(o.LocalDateTime), 262 OSLanguage : o.OSLanguage, 263 CountryCode : o.CountryCode, 264 CodeSet : o.CodeSet, 265 Locale : o.Locale, 266 MUILanguages : VBA_to_JSA(o.MUILanguages), 267 268 FreePhysicalMemory : o.FreePhysicalMemory, 269 PhysicalMemory : WMI_data('Win32_PhysicalMemory').item().Capacity, 270 271 // ms: maybe null! 272 // http://msdn2.microsoft.com/en-us/library/aa394272.aspx 273 // http://snippets.dzone.com/posts/show/5472 274 Uptime : (WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Object') 275 - WMI_data('Win32_PerfRawData_PerfOS_System.SystemUpTime')) * 1e3 276 / WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Object'), 277 // 顯示系統當下時間之印記 (NOT Uptime!) 這個運行時間是從性能計數器中獲得的64位整型數,不會出現在49.7天後溢出的情況。 278 // http://www.dx21.com/SCRIPTING/WMI/SUBCLASS.ASP?CID=201 279 // maybe NaN 280 Timestamp : WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Sys100NS') 281 / WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Sys100NS') 282 }; 283 //alert(WMI_data('Win32_PerfRawData_PerfOS_System.Timestamp_Sys100NS')+'/'+WMI_data('Win32_PerfRawData_PerfOS_System.Frequency_Sys100NS')); 284 285 if (!r.Uptime) 286 r.Uptime = (new Date() - r.LastBootUpTime); 287 288 return r; 289 }; 290 291 292 /* http://support.microsoft.com/kb/328874/zh-tw 293 http://msdn.microsoft.com/en-us/library/aa394520(VS.85).aspx 294 http://msdn.microsoft.com/en-us/library/aa390456(VS.85).aspx http://school.21tx.com/2004/06/16/11568_4.html 295 If this method succeeds and the ActivationRequired property is 1 (one), the method returns 0 (zero). Otherwise, the method returns one of the WMI error constants. 296 297 TODO: 298 判別 OS 299 */ 300 getWinID[generateCode.dLK]='WMI_data'; 301 function getWinID(pKey){ 302 var o=WMI_data('Win32_WindowsProductActivation') 303 ,WshShell=WScript.CreateObject("WScript.Shell"); 304 if(!o){alert('getWinID: Can not get Win32_WindowsProductActivation!');return;} 305 o=o.item(); 306 if(o.ActivationRequired){ 307 // 未啟用 Windows 前, 用錯誤序號會出錯 308 alert('Activation Required.'); 309 return; 310 } 311 if(pKey)try{ 312 // SetProductKey: 修改產品金鑰CD-KEY序號, return 0:OK, else error 313 var e=o.SetProductKey(pKey.replace(/[\s\-]/g,'')); 314 if(e)throw e; 315 }catch(e){ 316 alert('Update failed for ['+pKey+']:\n'+e.description); // for old version 有可能:無效的操作, 此時需 delete OOBETimer registry value 317 // TODO: delete OOBETimer registry value for XP 2600: 針對非 Windows XP SP1 或較新版 Windows XP 使用,來停用 Windows。 318 //WshShell.RegDelete("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WPAEvents\\OOBETimer"); 319 } 320 return o.GetInstallationID(pKey);//||pKey; // 無法以此方法獲得 ID 321 } 322 323 // ksp: 324 //alert(getWinID('Q9FDY-483HM-FV6RQ-2YQQQ-FD7J8'));WScript.Quit(); 325 326 // NTSU 327 //alert(getWinID('VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ'));WScript.Quit(); 328 //alert(getWinID()); 329 330 //alert(getSysInfo().Caption) 331 //WScript.Quit(); 332 333 /* 334 http://163.19.54.70/student/SerialNumber.txt 大量授權 335 Windows XP Professional VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ 336 Windows XP Prof, x64 Ed. FG2Q3-QX4JG-FQMMB-8XXD6-34MRY 337 Office XP Applications MXCVH-R3QQG-DMQ2M-KXPVQ-VKD6W 338 Office XP Suites PCCKW-J8Y6T-P632P-9KW9P-PK88B 339 Office 2003 Applications TF6RQ-TVG9Q-FVV74-GR4CP-2C2MB 340 Office 2003 Suites WCMVH-XJGPJ-G9BKC-2KHY9-Y7V36 341 Office 2007 Applications FJXGQ-RDQRY-Q2784-D89BP-M4MYJ 342 Office 2007 Suites KX3T3-RYFP7-BMPKG-JXTQ2-9HWBJ 343 344 DBXYD-TF477-46YM4-W74MH-6YDQ8 (CD) 345 W2JJW-4KYDP-2YMKW-FX36H-QYVD8 (FILES) 346 347 'Microsoft Windows XP Professional 5.1.2600':'VWPM3-MH7H6-VDDHG-YVR4Y-W38JQ' 348 349 ksp: 350 Windows XP Professional Q9FDY-483HM-FV6RQ-2YQQQ-FD7J8 351 Windows XP Prof, x64 Ed. V3PP8-CD446-62H9J-3XHVF-K44F3 352 Windows Vista 的 KMS 認證方式,請參考 http://www.ks.edu.tw/KSnet_service.html#D 353 Office XP Suites F86BJ-8PJWY-4P8QX-89FKF-896DT 354 Office 2003 Suites F4RMR-DKBX3-2TV7F-9T8QJ-8MYQ6 355 Office 2007 Suites M3JH3-4R8XX-R37F2-8D8H8-CBVD8 356 357 高雄市? 358 Office 2007 359 W3GCD-YWK98-8F6BG-2CYBY-KVWBJ 360 361 362 以下序號皆為 VLK 大量授權序號: 363 HCQ9D-TVCWX-X9QRG-J4B2Y-GR2TT 364 MRX3F-47B9T-2487J-KWKMF-RPWBY 365 QC986-27D34-6M3TY-JJXP9-TBGMD 366 CM3HY-26VYW-6JRYC-X66GX-JVY2D 367 DP7CM-PD6MC-6BKXT-M8JJ6-RPXGJ 368 F4297-RCWJP-P482C-YY23Y-XH8W3 369 HH7VV-6P3G9-82TWK-QKJJ3-MXR96 370 371 372 373 Windows XP Home Edition 374 x: 375 BQFBV-9J43J-663WJ-T2VDY-X86HY 376 VTDBB-QVPCJ-33J2V-B9KV4-W2PBM 377 DJH7R-4CYKJ-GWYDC-7MXHJ-X9VJY 378 3GT36-XXFDW-JC676-P4FBF-2G6MJ 379 DGDGK-XVXWR-XJHYK-3688K-8HXYJ 380 CX7DD-4GX4Y-BTTR4-H88Y7-GQPWQ 381 J22CH-K4V7X-4G6H6-66JFG-737TK 382 CG3BH-RG63P-6H2MR-3DVPT-6WTXJ 383 JPDR8-7X4G9-Q226K-B7VYR-HFHMD 384 W888Y-WM6YJ-DJQ27-WRB88-7FG96 385 386 */ 387 388 389 /* 390 Win32_ComputerSystem: 391 http://msdn2.microsoft.com/en-us/library/aa394224.aspx 392 393 Win32_NetworkAdapterConfiguration: 394 http://msdn2.microsoft.com/en-us/library/aa394217.aspx 395 http://www.microsoft.com/china/technet/community/scriptcenter/topics/networking/01_atnc_intro.mspx 396 http://www.codeproject.com/vbscript/ipaddress.asp?df=100&forumid=3295&exp=0&select=123580 397 398 399 test: 400 with(get_net_info())alert(UserName+'\n'+Name+'\n'+Workgroup+'\n'+Domain+'\n'+BootupState); 401 402 with(get_net_info(2)){ 403 alert(UserName+'\n'+Name+'\n'+Domain+'\n'+BootupState+'\nAll '+netif.length+' interfaces get'); 404 for(i=0;i<netif.length;i++)with(netif[i]) 405 sl(Caption+'\n' 406 +DNSDomain+'\n' 407 +DHCPServer+'\n' 408 +DNSHostName+'\n' 409 +DNSServerSearchOrder+'\n' 410 +IPSubnet+'\n' 411 +DefaultIPGateway+'\n' 412 +IPAddress+'\n' 413 414 +IPEnabled+'\n' 415 +DHCPEnabled+'\n' 416 +SettingID+'\n' 417 418 +MACAddress 419 ); 420 } 421 WScript.Quit(); 422 423 */ 424 CeL.application.OS.Windows.WMI 425 . 426 /** 427 * 取得網卡設定的IP地址 428 * @param type default type: ip setted interfaces only, 1: all interfaces, 2: 實體 net interfaces(網路卡,無線) 429 * @returns 430 * @example 431 * IP=get_net_info().netif[0].IPAddress[0]; 432 * with(get_net_info())alert(UserName+'\n'+Name+'\n'+Workgroup+'\n'+Domain+'\n'+BootupState); 433 * @requires WMI_data,VBA_to_JSA 434 * @memberOf CeL.application.OS.Windows.WMI 435 */ 436 get_net_info = function(type) { 437 var r = WMI_data('Win32_ComputerSystem'); 438 if (!r || !r.item()) { 439 r = null; 440 throw new Error('Can not get Win32_ComputerSystem!\nIs this old system or the function is limited?'); 441 r = {}; 442 } else { 443 r = 444 // WMI_data({computer:IP||'.',from:'Win32_ComputerSystem'}).item() 445 WMI_data.getProperties(r.item()); 446 if (!r.Workgroup) 447 // Windows 2000 and Windows NT: Workgroup is not available. Domain: If the computer is not part of a domain, then the name of the workgroup is returned. 448 r.Workgroup = r.Domain; 449 } 450 451 /* waste time 452 with(WMI_data('Win32_NTDomain').item()){ 453 r.Caption=Caption,r.Description=Description; 454 if(!r.Name)r.Name=Name; 455 } 456 */ 457 458 r.netif = []; 459 WMI_data( 460 { 461 from : 'Win32_NetworkAdapterConfiguration', 462 where : type === 1 ? '' 463 // 這判別法不是很好 464 // DHCPEnabled 與 IPEnabled 可以同時為 TRUE 465 : type === 2 ? 'MACAddress!=NULL AND (DHCPEnabled=TRUE OR IPEnabled=TRUE)'// OR IPXEnabled=TRUE 466 : 'IPEnabled=TRUE' // 'NetEnabled=True': Vista only code? 467 }, function(o) { 468 // 在DHCP可能得到兩筆同IP之data. 469 // MACAddress: getmac.exe, arp -a, nbtstat -a 192.168.0.1 470 r.netif.push(WMI_data.getProperties(o)); 471 }); 472 return r; 473 }; 474 475 476 477 CeL.application.OS.Windows.WMI 478 . 479 /** 480 * get CIDR data 481 * @param {Number} CIDR CIDR mask bits, 0~32 482 * @param {String} IP IPv4, e.g., 1.2.3.4 483 * @return CIDR data 484 * @since 2010/4/21 22:56:16 485 * @memberOf CeL.application.OS.Windows.WMI 486 */ 487 CIDR_to_IP = function (CIDR, IP) { 488 if (isNaN(CIDR) || CIDR < 0 || CIDR > 32) 489 return; 490 491 if (typeof IP === 'string') 492 IP = IP.split('.'); 493 else if (!(IP instanceof Array)) 494 IP = []; 495 496 var i = 0, r = { 497 // geteway IP 498 geteway : [], 499 // subnet mask 500 mask : [], 501 // wildcard mask 502 wildcard : [], 503 // subnet start IP,the entire network 504 subnet : [], 505 // subnet end IP, broadcast address 506 broadcast : [], 507 // Maximum Addresses, range IP count 508 // .count now = Maximum Subnets 509 count : 1 << (32 - CIDR) 510 }; 511 512 for (; i < 4; i++) { 513 if (CIDR > 7) { 514 CIDR -= 8; 515 r.wildcard[i] = 0; 516 r.mask[i] = 255; 517 r.subnet[i] = r.broadcast[i] = IP[i] || 0; 518 } else if (CIDR) { 519 r.broadcast[i] = (IP[i] || 0) | (r.wildcard[i] = CIDR = (1 << (8 - CIDR)) - 1); 520 r.subnet[i] = (IP[i] || 0) & (r.mask[i] = 255 - CIDR); 521 CIDR = 0; 522 } else 523 r.broadcast[i] = r.wildcard[i] = 255, 524 r.subnet[i] = r.mask[i] = 0; 525 } 526 527 if (r.count > 2) 528 r.count -= 2; 529 r.geteway = r.broadcast.join(',').split(','); 530 // [the entire network, .., geteway, broadcast address] 531 r.geteway[3] -= 1; 532 533 //alert(r.geteway + '\n' + r.subnet + '\n' + r.broadcast + '\n' + r.wildcard + '\n' + r.subnet + '\n' + r.count); 534 return r; 535 }; 536 537 538 CeL.application.OS.Windows.WMI 539 . 540 /** 541 * 改變網卡的IP地址: change IP, set IP 542 * @param to_s IP or {IP:''||[], CIDR:24||.CIDR_notation, Subnet:''||[], DNS:''||[], Gateway:254||[], GatewayOrder:''||[]} 543 * @param from IP or netif No. 544 * @since 545 * 2009/5/7 0:24:5 加強 546 * 2010/3/3 10:41:17 a work version 547 * @see 548 * <a href="http://msdn.microsoft.com/en-us/library/aa394217%28VS.85%29.aspx" accessdate="2010/3/3 13:15">Win32_NetworkAdapterConfiguration Class (Windows)</a> 549 * <a href="http://www.yongfa365.com/item/Use-WMi-Change-IP-VBS-yongfa365.html" accessdate="2010/3/3 13:14">通过 WMI 改变网卡的IP地址 ChangeIP.vbs - 柳永法(yongfa365)'Blog</a> 550 * <a href="http://www.microsoft.com/technet/scriptcenter/topics/networking/01_atnc_intro.mspx">Automating TCP/IP Networking on Clients: Part 1: Introduction</a> 551 * <a href="http://www.dotblogs.com.tw/PowerHammer/archive/2008/03/24/2060.aspx" accessdate="2010/3/3 13:15">使用 WMI 更改IP、子網路遮罩、閘道、DNS - 強力鎯頭 VB BLOG - 點部落</a> 552 * Using NetSh.exe (no reboot required): <a href="http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/tsleft.web+WinBatch/How~To+Change~Ip~Address.txt" accessdate="2010/3/3 13:12">WWW Tech Support/WinBatch/How To\Change Ip Address.txt</a> 553 * @example 554 * set_net_info({IP:'163.16.20.212',Gateway:254}); 555 * sl(set_net_info({IP:'163.16.20.30',Gateway:254}));WScript.Quit(); 556 * @requires WMI_data,VBA_to_JSA,JSArrayToSafeArray,CIDR_to_IP 557 * @memberOf CeL.application.OS.Windows.WMI 558 */ 559 set_net_info = function (to_s, from) { 560 561 var _f = set_net_info, r, count, IPA, i = function(ip) { 562 if (!(ip instanceof Array)) 563 if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip = '' + ip)) 564 ip = [ ip ]; 565 else 566 return; 567 return JSArrayToSafeArray(ip); 568 }; 569 570 if (typeof to_s === 'string' 571 && (r = to_s 572 .match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\/(\d{1,2}))?$/))) { 573 count = r[1]; 574 to_s = { 575 IP : count 576 }; 577 578 if ((r = r[3]) > 15) { 579 r = _.CIDR_to_IP(r, count); 580 to_s.Gateway = r.geteway.join('.'); 581 to_s.Subnet = r.mask.join('.'); 582 } 583 584 }else if (typeof to_s !== 'object' || to_s instanceof Array) 585 // treat as IP 586 to_s = { 587 IP : to_s 588 }; 589 590 if (!isNaN(to_s.Gateway)) 591 to_s.Gateway = (to_s.IP instanceof Array ? to_s.IP.join('.') : to_s.IP) 592 .replace(/\d+$/, to_s.Gateway); 593 594 // SubnetMask: Subnet masks that complement the values in the IPAddress parameter. Example: 255.255.0.0. 595 if (!('Subnet' in to_s) || !isNaN(to_s.Subnet)) { 596 r = _.CIDR_to_IP(to_s.Subnet || _f.CIDR_notation, to_s.IP); 597 to_s.Subnet = r.subnet.join('.'); 598 } 599 600 //sl('set_net_info:\n[' + from + '] → [' + to_s.IP + '/' + to_s.Subnet + ']\nGateway: [' + to_s.Gateway + ']\nDNS: [' + ('DNS' in to_s ? to_s.DNS : _f.default_DNS) + ']'); 601 // return -1; 602 603 to_s.Subnet = i(to_s.Subnet); 604 to_s.IP = i(to_s.IP); 605 to_s.DNS = i('DNS' in to_s ? to_s.DNS : _f.default_DNS); 606 607 if ((to_s.Gateway = i(to_s.Gateway))) 608 if (!to_s.GatewayOrder) 609 for (i = 1, to_s.GatewayOrder = [ 0 ], r = to_s.Gateway instanceof Array ? to_s.Gateway.length 610 : 0; i < r;) 611 to_s.GatewayOrder.push(++i); 612 else if (!(to_s.GatewayOrder instanceof Array)) 613 to_s.GatewayOrder = [ to_s.GatewayOrder ]; 614 615 r = -1; 616 count = 0; 617 if (!from) 618 from = 0; 619 620 WMI_data( 621 { 622 from : 'Win32_NetworkAdapterConfiguration', 623 // 這判別法不是很好 624 // DHCPEnabled 與 IPEnabled 可以同時為 TRUE 625 where : 'MACAddress!=NULL AND (IPEnabled=TRUE OR DHCPEnabled=TRUE)'// OR IPXEnabled=TRUE 626 }, 627 function(o) { 628 // alert('Get if: ' + o.Caption + '\n' + from + ',' + count); 629 // 通常我們不會設定無線連線 630 if(/wireless/i.test(o.Caption)) 631 return; 632 633 if (isNaN(from) || from === count++) { 634 for (i = 0, IPA = from ? VBA_to_JSA(o.IPAddress) : [ 1 ]; i < IPA.length; i++) { 635 if (!from || IPA[i] === from) { 636 r = typeof to_s.IP === 'undefined' ? o.EnableDHCP() 637 : o 638 .EnableStatic( 639 to_s.IP, 640 typeof to_s.Subnet === 'undefined' ? o.IPSubnet 641 : to_s.Subnet) 642 || typeof to_s.Gateway !== 'undefined' 643 && o.SetGateways(to_s.Gateway, 644 to_s.GatewayOrder) 645 || typeof to_s.DNS !== 'undefined' 646 && o.SetDNSServerSearchOrder(to_s.DNS); 647 //alert('Set if:\n'+o.Caption+'\nto: '+to_s.IP+'\nerrno: '+r); 648 // TODO: error detection 649 return 1; 650 } 651 } 652 } 653 }); 654 655 // not found / error 656 // http://msdn.microsoft.com/en-us/library/aa390383%28VS.85%29.aspx 657 return r; 658 }; 659 660 CeL.application.OS.Windows.WMI 661 . 662 // default DNS 663 // 168.95.1.1,8.8.4.4 664 set_net_info.default_DNS = '8.8.8.8'; 665 666 CeL.application.OS.Windows.WMI 667 . 668 // http://en.wikipedia.org/wiki/CIDR_notation 669 set_net_info.CIDR_notation = 24; 670 671 672 673 674 675 /* get IP of Windows Host 676 http://www.scriptinganswers.com/forum/forum_posts.asp?TID=516&PID=3124 677 Wscript.Network 678 679 ping: 680 http://blog.blueshop.com.tw/hammerchou/archive/2006/07/08/32205.aspx 681 1. 682 GetObject("winmgmts:").Get("NetDiagnostics=@").Ping(strAddr, Ping) 683 2. 684 objCls = GetObject("winmgmts:\\" & strMachine & "\root\CIMV2").Get("NetDiagnostics") 685 objInPara = objCls.Methods_("Ping").inParameters.SpawnInstance_() 686 objInPara.Properties_("sInAddr") = "www.google.com.tw" // 設定 Ping 的位置 687 // Ping 為 方法 , ExecMethod 為 執行方法 ( 把參數送入執行 ) 688 objOutPara = objWMIsvc.ExecMethod("NetDiagnostics=@", "Ping", objInPara) 689 // 取回輸出參數 ( Ping 的結果 ): objOutPara.ReturnValue = True 則 Ping 成功 , 反之則失敗 690 objOutPara.sOutArg 691 692 693 test: 694 var h='Public',ip=getIPofHost(h);alert(ip?h+':\n'+ip:'Computer [\\'+h+'] is unreachable!'); 695 696 */ 697 //getIPofHost[generateCode.dLK]='WMI_data'; 698 function getIPofHost(h) { 699 var qIP = WMI_data( { 700 from : 'Win32_PingStatus', 701 where : "Address='" + h + "'" 702 }).item(); 703 if (!qIP.StatusCode && qIP.StatusCode != null) 704 return qIP.ProtocolAddress; 705 } 706 707 // 終止進程 http://msdn2.microsoft.com/en-us/library/aa393907.aspx 708 //killProcess[generateCode.dLK]='WMI_data'; 709 function killProcess(n, isPID) { 710 var k = 0; 711 if (typeof isPID == 'undefined') 712 isPID = !isNaN(n); 713 WMI_data('Win32_Process', function(p) { 714 with (p) 715 if (isPID) 716 if (ProcessId == n) { 717 Terminate(); 718 k = 1; 719 return 1; 720 } else if (Caption == n) 721 Terminate(), k++; 722 }); 723 return k; 724 } 725 726 727 /* 列舉進程 http://msdn2.microsoft.com/en-us/library/aa394372.aspx 728 729 test: 730 alert(get_process()['explorer.exe'].CommandLine); 731 for(i=0,p=get_process();i<p.length;i++)with(p[i]) 732 alert(i+' / '+p.length+'\n['+ProcessId+'] '+Caption+(Name==Caption?'':' ('+Name+')')+'\n'+(Description==Caption?'':Description+'\n')+CSName+'\n' 733 +'Open files: '+HandleCount+'\n' 734 //+OSName+'\n' 735 +'memory: '+MinimumWorkingSetSize+'-'+MaximumWorkingSetSize+'\n' // memory pages visible to the process in physical RAM 736 +'Time in kernel mode: '+KernelModeTime+' ms\n'+ExecutablePath+'\n'+CommandLine+'\n'+CreationDate.toLocaleString() 737 ); 738 */ 739 //get_process[generateCode.dLK]='WMI_data'; 740 function get_process() { 741 var r = []; 742 WMI_data('Win32_Process', function(p) { 743 with (p) 744 r[Caption] = r[r.push( { 745 ProcessId : ProcessId, 746 Caption : Caption, 747 ExecutablePath : ExecutablePath, 748 CommandLine : CommandLine, 749 Name : Name, // ==Caption 750 Description : Description, // ==Caption 751 CSName : CSName, 752 HandleCount : HandleCount, 753 OSName : OSName, 754 MinimumWorkingSetSize : MinimumWorkingSetSize, 755 MaximumWorkingSetSize : MaximumWorkingSetSize, 756 KernelModeTime : p.KernelModeTime / 1e5, // 100000ms 757 CreationDate : WMI_data 758 .DateStringToDate(CreationDate) 759 }) - 1]; 760 }); 761 return r; 762 } 763 764 765 766 /* 列舉服務 767 http://msdn2.microsoft.com/en-us/library/aa394418.aspx 768 http://www.microsoft.com/taiwan/technet/scriptcenter/topics/vista/indexer.mspx 769 770 test: 771 alert(get_service()['Event Log'].Description); 772 for(i=0,s=get_service();i<s.length;i++){t=i+' / '+s.length;for(j in s[i])t+='\n'+j+': '+s[i][j];alert(t);} 773 */ 774 //get_service[generateCode.dLK]='WMI_data'; 775 function get_service() { 776 var r = []; 777 WMI_data('Win32_Service', function(s) { 778 with (s) 779 r[Caption] = r[r.push( { 780 AcceptPause : AcceptPause, 781 AcceptStop : AcceptStop, 782 Caption : Caption, 783 Description : Description, 784 DisplayName : DisplayName, 785 ExitCode : ExitCode, 786 InstallDate : WMI_data.DateStringToDate(InstallDate), 787 Name : Name, 788 Pathname : Pathname, 789 ProcessId : ProcessId, 790 ServiceSpecificExitCode : ServiceSpecificExitCode, 791 Started : Started, 792 StartMode : StartMode, 793 StartName : StartName, 794 State : State, 795 Status : Status, 796 SystemName : SystemName 797 }) - 1]; 798 }); 799 return r; 800 } 801 802 803 /* http://msdn.microsoft.com/en-us/library/bb774148.aspx 804 WinShell.ShellExecute(appName, appArgs, appPath, "", 0); http://msdn.microsoft.com/en-us/library/bb774148.aspx 805 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long 806 <object runat="server" id="WinShell" scope="page" classid="clsid:13709620-C279-11CE-A49E-444553540000"></object> 807 <object runat="server" id="fso" scope="page" classid="clsid:0D43FE01-F093-11CF-8940-00A0C9054228"></object> 808 809 http://windowssdk.msdn.microsoft.com/en-us/library/ms630425.aspx 810 WinShell.ShutdownWindows(); // Open the Shutdown dialog http://www.robvanderwoude.com/index.html 811 */ 812 813 814 /* 2008/8/8 18:29:44 815 run them with administrator rights runs under administrator privileges. 816 帳戶控制 Windows Vista:使用軟體限制原則對抗未授權的軟體 http://www.microsoft.com/taiwan/technet/windowsvista/security/rstrplcy.mspx 817 http://4sysops.com/archives/vista%E2%80%99s-uac-how-to-elevate-scripts-vbscript-and-jscript/ 818 http://blogs.msdn.com/aaron_margosis/archive/2007/07/01/scripting-elevation-on-vista.aspx 819 Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA c:\windows\system32\control.exe /name Microsoft.UserAccounts http://www.dashken.net/index.php?/archives/280-VBScript-Check-if-OS-is-Vista-and-Vistas-UAC-status.html 820 http://msdn.microsoft.com/en-us/magazine/cc163486.aspx 821 HKEY_LOCAL_MACHINESOFTWARE MicrosoftWindowsCurrentVersionPoliciesSystem\ConsentPromptBehaviorAdmin http://hsu.easynow.com.tw/index.php?load=read&id=28 822 http://vistavitals.blogspot.com/2008/02/logon-scripts-token-effort.html 823 runas http://www.merawindows.com/Forums/tabid/324/forumid/82/postid/32458/scope/posts/Default.aspx 824 http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html 825 826 http://forums.techarena.in/vista-security/654643.htm 827 Set objShell = CreateObject("Shell.Application") 828 Set objFolder = objShell.Namespace("C:\") 829 Set objFolderItem = objFolder.ParseName("myhta.hta") 830 objFolderItem.InvokeVerb "runas" 831 832 var WinShell=new ActiveXObject("Shell.Application"),p=location.pathname.replace(/[^\\]+$/,''),o=WinShell.Namespace(p).ParseName(location.pathname.slice(p.length)); 833 o.InvokeVerb("runas"); 834 835 http://www.zaoxue.com/article/tech-28339_2.htm http://www.lob.cn/vbs/20071126203237.shtml 836 837 TODO: 838 對 prompt 回應不允許時的處理: 若想在受限的情況下使用? 839 不使用自訂程式 http://msdn.microsoft.com/en-us/library/bb776820(VS.85).aspx 840 */ 841 function runas(p){ 842 if(!p)p=typeof WScript=='object'?WScript.ScriptFullName:unescape(location.pathname); 843 var a={js:'wscript.exe',vbs:'wscript.exe',hta:'mshta.exe'},ext=p.match(/([^.]+)$/); 844 a=ext&&((ext=ext[1].toLowerCase()) in a)?a[ext]:''; 845 // 判斷是否有權限 846 if(!registryF.checkAccess('HKLM\\SOFTWARE\\')){ 847 // 以管理者權限另外執行新的 It will get the UAC prompt if this feature is not disabled. 848 new ActiveXObject("Shell.Application").ShellExecute(a||p,a?p:'','','runas'/*,5*/); 849 // 執行完本身則退出 850 if(typeof WScript=='object')WScript.Quit();else if(typeof window=='object')window.close(); 851 } 852 } 853 854 855 /* JScript file: check owner, .exe file 856 http://www.microsoft.com/taiwan/technet/scriptcenter/resources/qanda/nov04/hey1115.mspx 857 Exec Method (Windows Script Host) http://msdn.microsoft.com/en-us/library/ateytk4a(VS.85).aspx 858 859 usage: 860 runProg(path): use WshShell.Exec, return [StdOut, StdErr, ExitCode] 861 runProg(path, 1): use WshShell.Exec, can get output by .StdOut.ReadAll(), or .StdErr.ReadAll() 862 runProg([path, WindowStyle, WaitonReturn],2): use WshShell.Run 863 runProg(script path, remote computer): use WshRemote 864 runProg(path, remote computer): use WMI 865 866 TODO: 867 runProg([path, Verb],3): use Shell.Application InvokeVerb 868 runProg([path, arg1, arg2,..]): use Shell.Application.ShellExecute 869 870 871 example: 872 WScript.Echo(runProg('%COMSPEC% /U /c ""C:\\Program Files\\WinRAR\\Rar.exe" vt -scuc "F:\\CLAMP 01.rar""')[0]); 873 874 875 WshShell.Run(command, [WindowStyle 0-10], [WaitonReturn false: nowait & return 0, true: wait & return error code]) 876 WshShell.Exec(),objFolderItem.InvokeVerb() 877 WshShell.Run('command /k ' + ドライブ +' | cd /D '+ パス);// cd で他ドライブへ移れないので。 878 */ 879 //runProg[generateCode.dLK]='initWScriptObj'; 880 function runProg(p,r){try{ 881 var s; 882 if(!r||r===1||r===2)if(typeof (s=new ActiveXObject('WScript.Shell'))=='object'){ 883 if(typeof p=='object'&&r===2) 884 r=s.Run(p[0],p[1],p[2]); 885 else if(s=s.Exec(p),r)r=s; 886 else with(s){ 887 while(!Status)WScript.Sleep(80); 888 r=[StdOut.ReadAll(),StdErr.ReadAll(),ExitCode]; 889 } 890 return r; 891 }else return; 892 893 if(/^[^ ]+\.(j|vb)s$/i.test(p)){ 894 s=(WScript.CreateObject('WSHController')).CreateScript(p,r); 895 s.Execute(); 896 return s; 897 } 898 899 s=GetObject("winmgmts:{impersonationLevel=impersonate}//"+(r||'.')+"/root/cimv2:Win32_Process"); 900 //if(/^[^ ]+\.(j|vb)s$/i.test(p))p="wscript.exe "+p; 901 return s.Create(p/*,null,null,intProcessID*/); // Create 方法會讓這個指令碼在「遠端電腦」上執行。 902 }catch(e){ 903 //popErr(e); 904 return e; 905 }} // function runProg 906 907 908 909 /* shutdown/reboot computer 2007/5/8-9 0:8:52 910 http://www.robvanderwoude.com/index.html 911 http://www.ericphelps.com/batch/samples/reboot.txt 912 913 http://www.semcase.com/docus/iis/prog_wmi_tut_03_01.htm http://www.semcase.com/docus/iis/iis.htm 914 http://support.microsoft.com/kb/913538 當您使用會讓列舉程式物件在 Microsoft Windows Server 2003 或 Microsoft Windows XP 用戶端電腦上進行內部複製的 Windows Management Instrumentation (WMI) 功能時,列舉程式物件於用戶端電腦尚未完成使用列舉程式物件的動作時,即遭取消。此外,WMI 功能還可能傳回錯誤碼。 915 916 mode: 917 0 poweroff (if supported by the hardware) 918 null,1 reboot 919 restart 920 logoff 921 shutdown 922 suspend, sleep, hibernate 923 lock 924 // standby http://www.tutorials-xe.com/SCRIPTING/Restart-service/ 925 16 force 926 927 open the shutdown dialog 928 929 time: seconds 930 */ 931 var shutdownF; 932 setObjValue('shutdownF','poweroff,reboot,restart,logoff,shutdown,suspend,lock,force=16,dialog=32',1); 933 shutdown[generateCode.dLK]='initWScriptObj,shutdownF,Sleep'; 934 function shutdown(mode,time/*,message*/){ 935 if(isNaN(mode))mode=shutdownF.reboot; 936 937 var f,sComputer="." 938 ,_s,s=function(t){ 939 if(t)return _s; 940 if(time&&!_s)Sleep(time); 941 _s=1; 942 } 943 ,force=mode&shutdownF.force 944 ,sF=function(a){f={};for(i=0;i<a.length;i+=2)f[a[i]]=a[i+1];} 945 ,oWMIS 946 ; 947 948 if((mode-=force)==shutdownF.dialog)try{ 949 s(); 950 WinShell.ShutdownWindows(); 951 return; 952 }catch(e){} 953 954 // way 1: WMI 955 sF([0,0,shutdownF.logoff,0,shutdownF.shutdown,1,shutdownF.reboot,2,shutdownF.force,4,shutdownF.poweroff,8]); 956 if(mode in f)try{ // f.hasOwnProperty(mode) 957 f=f[mode]&f[force]; 958 oWMIS=new Enumerator( 959 GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}//"+(sComputer||'.')+"/root/cimv2") 960 .ExecQuery("Select * from Win32_OperatingSystem")//Select * from Win32_OperatingSystem Where primary=true 961 ); 962 if(!oWMIS)throw 1; 963 s(); 964 for(;!oWMIS.atEnd();oWMIS.moveNext()){ 965 //oWMIS.item().Reboot();//.Shutdown(); // force! 966 oWMIS.item().Win32Shutdown(f);//if() // http://msdn2.microsoft.com/en-us/library/aa394058.aspx 967 } 968 return; 969 }catch(e){} 970 // way 2: RUNDLL32 SHELL32.DLL, SHExitWindowsEx [n] 971 if(mode in f)try{WshShell.Run(" RUNDLL32 SHELL32.DLL,SHExitWindowsEx "+f[mode]);return;}catch(e){} 972 973 // way 3: shutdown.exe utility 974 sF([shutdownF.logoff,'l',shutdownF.poweroff,'s',shutdownF.shutdown,'s',shutdownF.reboot,'r',shutdownF.dialog,'i']); 975 if(mode in f)try{WshShell.Run('%windir%\System32\shutdown.exe -'+f+(!time||s(1)?'':' -t '+time)+(force?' -f':''));return;}catch(e){} // -s or -r 976 977 // way 4: rundll.exe 978 sF([shutdownF.logoff,'SHELL.DLL,RestartDialog',shutdownF.poweroff,'USER.EXE,ExitWindows',shutdownF.shutdown,'USER.EXE,ExitWindows'/*'USER.EXE,#7'||'USER.EXE, #7'||'USER.EXE,#7 0'*/,shutdownF.restart,'USER.EXE,ExitWindowsExec'/*'USER.EXE,#246'*/]); 979 if(mode in f)try{WshShell.Run("rundll.exe "+f[mode]);return;}catch(e){} 980 981 // way 5: rundll32.exe 982 sF([shutdownF.poweroff,'KRNL386.EXE,exitkernel',shutdownF.shutdown,'USER.EXE,ExitWindows',shutdownF.suspend,'PowrProf.dll,SetSuspendState']); 983 if(mode in f)try{WshShell.Run("rundll32.exe "+f[mode]);return;}catch(e){} 984 // way 6: RUNDLL32 USER32.DLL 985 sF([shutdownF.lock,'LockWorkStation',shutdownF.logoff,'ExitWindowsEx']); 986 if(mode in f)try{WshShell.Run("rundll32.exe user32.dll,"+f[mode]);return;}catch(e){} 987 988 // way 7: RUNONCE.EXE runonce.exe是微軟Run Once的包裝。它用於第三方應用程序的安裝程序。它允許安裝程序添加到啟動項中,用於再次啟動後,進行進一步配置。 989 if(mode==shutdownF.reboot)try{WshShell.Run("RUNONCE.EXE -q");return;}catch(e){} 990 991 return 1; 992 } 993 994 995 // ↑WMI set ================== 996 997 998 999 1000 1001 1002 1003 return ( 1004 CeL.application.OS.Windows.WMI 1005 ); 1006 } 1007 1008 1009 ); 1010 1011