-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript2.ps1
More file actions
1265 lines (1084 loc) · 45.4 KB
/
Copy pathscript2.ps1
File metadata and controls
1265 lines (1084 loc) · 45.4 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# UTF-8 without BOM
Set-StrictMode -Version Latest
# 检测参数(兼容 irm | iex 执行方式)
$DirectToAutoLogin = $env:PS_DIRECT_TO_AUTOLOGIN -eq "1"
$ElevatedSession = $env:PS_ELEVATED_SESSION -eq "1"
# 全局变量
$script:scriptDir = "$env:USERPROFILE\LoginScript"
$script:logFile = "$script:scriptDir\login_script.log"
$script:taskName = "NetworkLoginScript"
$script:asciiArtCache = @{}
$script:scriptContent = $null
# 如果通过 irm | iex 运行,保存脚本内容
if (-not $PSCommandPath) {
$script:scriptContent = $MyInvocation.MyCommand.ScriptBlock.ToString()
}
# 检测参数(通过环境变量)
$DirectToAutoLogin = $env:PS_DIRECT_TO_AUTOLOGIN -eq "1"
$ElevatedSession = $env:PS_ELEVATED_SESSION -eq "1"
# ASCII艺术相关函数
function Convert-BBCodeToAnsi {
param(
[Parameter(Mandatory=$true)]
[string]$InputString
)
$colorTagRegex = '(\[color=(?<hex>#[a-fA-F0-9]{6})\]|<span style="color:(?<hex>#[a-fA-F0-9]{6})">)'
$matchEvaluator = {
param($match)
$hex = $match.Groups['hex'].Value.TrimStart('#')
$r = [System.Convert]::ToInt32($hex.Substring(0, 2), 16)
$g = [System.Convert]::ToInt32($hex.Substring(2, 2), 16)
$b = [System.Convert]::ToInt32($hex.Substring(4, 2), 16)
return "$([char]27)[38;2;${r};${g};${b}m"
}
$processedString = [regex]::Replace($InputString, $colorTagRegex, $matchEvaluator)
$processedString = $processedString -replace '(\[/color\]|</span>)', "$([char]27)[0m"
$processedString = $processedString -replace '\[/?(size|font)[^\]]*\]', ''
return $processedString
}
function Get-AsciiArtDimensions {
param(
[Parameter(Mandatory=$true)]
[string]$AsciiContent,
[Parameter(Mandatory=$false)]
[switch]$Detailed # 返回详细信息,包括每行的起始位置
)
$plainText = $AsciiContent -replace '\[/?[^\]]+\]', ''
$plainText = $plainText -replace '<[^>]+>', ''
$lines = $plainText -split "`n"
$nonEmptyLines = $lines | Where-Object { $_.Trim() -ne '' }
$height = $nonEmptyLines.Count
$width = 0
$minLeftPadding = [int]::MaxValue
$lineDetails = @()
foreach ($line in $nonEmptyLines) {
$trimmedLine = $line.TrimEnd()
# 计算左侧空白
$leftPadding = 0
if ($trimmedLine.Length -gt 0) {
$leftPadding = $line.Length - $line.TrimStart().Length
if ($leftPadding -lt $minLeftPadding -and $trimmedLine.Length -gt 0) {
$minLeftPadding = $leftPadding
}
}
# 计算实际内容宽度
$contentWidth = $trimmedLine.Length
if ($contentWidth -gt $width) {
$width = $contentWidth
}
if ($Detailed) {
$lineDetails += @{
Content = $trimmedLine
LeftPadding = $leftPadding
Width = $contentWidth
}
}
}
# 如果所有行都是空的,重置最小左边距
if ($minLeftPadding -eq [int]::MaxValue) {
$minLeftPadding = 0
}
$result = @{
Width = $width
Height = $height
MinLeftPadding = $minLeftPadding
EffectiveWidth = $width - $minLeftPadding # 去除最小左边距后的实际宽度
}
if ($Detailed) {
$result.LineDetails = $lineDetails
}
return $result
}
function Load-AsciiArt {
param(
[Parameter(Mandatory=$true)]
[string]$FileName
)
$content = $null
$cacheDir = Join-Path $script:scriptDir "ascii_cache"
# 检查是否是URL
if ($FileName -match "^https?://") {
# 从URL获取文件名作为缓存文件名
$cacheFileName = [System.IO.Path]::GetFileName($FileName)
$cacheFilePath = Join-Path $cacheDir $cacheFileName
# 检查缓存是否存在
if (Test-Path $cacheFilePath) {
$content = Get-Content $cacheFilePath -Raw -Encoding UTF8
} else {
Write-LogMessage "从URL下载ASCII艺术: $FileName" -Level "INFO" -Silent
try {
$webClient = New-Object System.Net.WebClient
$content = $webClient.DownloadString($FileName)
# 创建缓存目录
if (-not (Test-Path $cacheDir)) {
New-Item -ItemType Directory -Path $cacheDir -Force | Out-Null
}
# 写入缓存
$content | Out-File -FilePath $cacheFilePath -Encoding UTF8
Write-LogMessage "ASCII艺术已缓存到: $cacheFilePath" -Level "SUCCESS" -Silent
} catch {
Write-LogMessage "从URL下载ASCII艺术失败: $($_.Exception.Message)" -Level "ERROR"
$content = $null
}
}
}
# 如果内容仍为空,尝试从本地文件加载
if (-not $content) {
$asciiPath = Join-Path $PSScriptRoot "ascii\$FileName"
if (-not (Test-Path $asciiPath)) {
Write-LogMessage "本地ASCII艺术文件不存在: $asciiPath" -Level "ERROR"
return $null
}
Write-LogMessage "尝试从本地文件加载ASCII艺术: $asciiPath" -Level "INFO"
$content = Get-Content $asciiPath -Raw -Encoding UTF8
Write-LogMessage "从本地文件加载ASCII艺术成功。" -Level "SUCCESS"
}
if (-not $content) {
return $null
}
$ansiContent = Convert-BBCodeToAnsi -InputString $content
$dimensions = Get-AsciiArtDimensions -AsciiContent $content -Detailed
return @{
Content = $ansiContent
Lines = $ansiContent -split "`n"
Width = $dimensions.Width
Height = $dimensions.Height
MinLeftPadding = $dimensions.MinLeftPadding
EffectiveWidth = $dimensions.EffectiveWidth
LineDetails = $dimensions.LineDetails
}
}
# 计算字符串的显示宽度(考虑中文字符)
function Get-StringDisplayWidth {
param(
[string]$Text
)
$width = 0
foreach ($char in $Text.ToCharArray()) {
$charCode = [int]$char
# 中文字符范围和全角字符
if (($charCode -ge 0x4E00 -and $charCode -le 0x9FFF) -or
($charCode -ge 0x3000 -and $charCode -le 0x303F) -or
($charCode -ge 0xFF00 -and $charCode -le 0xFFEF)) {
$width += 2
} else {
$width += 1
}
}
return $width
}
function Show-Menu {
param(
[string]$Title = "操作菜单",
[string]$MenuLevel = "main", # "main", "power", "company", "autologin"
[string]$AsciiArtFile = "https://raw.githubusercontent.com/mengchunm/mengchunm.github.io/main/ascii/isekai.bbcode" # 默认使用isekai ASCII画
)
Clear-Host
# 在所有菜单中加载ASCII艺术 (使用内存和文件缓存)
$asciiArt = $null
if ($AsciiArtFile) {
if ($script:asciiArtCache.ContainsKey($AsciiArtFile)) {
$asciiArt = $script:asciiArtCache[$AsciiArtFile]
} else {
$asciiArt = Load-AsciiArt -FileName $AsciiArtFile
if ($asciiArt) {
$script:asciiArtCache[$AsciiArtFile] = $asciiArt
}
}
}
# 准备菜单内容
$menuLines = @()
$menuLines += "=================================================="
$menuLines += " $Title"
$menuLines += "=================================================="
switch ($MenuLevel) {
"main" {
$menuLines += "[1] 电源模式"
$menuLines += "[2] 公司特殊配置"
$menuLines += "--------------------------------------------------"
$menuLines += "[Q] 退出"
}
"power" {
$menuLines += "[1] 卓越性能"
$menuLines += "[2] 高性能"
$menuLines += "[3] 节能"
$menuLines += "[4] 平衡"
$menuLines += "--------------------------------------------------"
$menuLines += "[B] 返回主菜单"
}
"company" {
$menuLines += "[1] 自动登录配置"
$menuLines += "[2] 代理设置"
$menuLines += "--------------------------------------------------"
$menuLines += "[B] 返回主菜单"
}
"autologin" {
$menuLines += "[1] 安装/更新自动登录脚本"
$menuLines += "[2] 查看自动登录状态"
$menuLines += "[3] 卸载自动登录"
$menuLines += "[4] 查看日志"
$menuLines += "--------------------------------------------------"
$menuLines += "[B] 返回公司配置菜单"
}
}
$menuLines += "=================================================="
# 显示逻辑
if ($asciiArt) {
# 菜单在左,ASCII在右
$menuWidth = 0
foreach ($line in $menuLines) {
$lineWidth = Get-StringDisplayWidth -Text $line
if ($lineWidth -gt $menuWidth) {
$menuWidth = $lineWidth
}
}
$menuHeight = $menuLines.Count
$asciiHeight = $asciiArt.Height
$maxHeight = [Math]::Max($menuHeight, $asciiHeight)
$gap = " "
for ($i = 0; $i -lt $maxHeight; $i++) {
# 计算菜单行 (底部对齐)
$menuLine = ""
$menuIndex = $i - ($maxHeight - $menuHeight)
if ($menuIndex -ge 0) {
$menuLine = $menuLines[$menuIndex]
}
# 计算ASCII行 (底部对齐)
$asciiLine = ""
$asciiIndex = $i - ($maxHeight - $asciiHeight)
if ($asciiIndex -ge 0 -and $asciiIndex -lt $asciiArt.Lines.Count) {
$asciiLine = $asciiArt.Lines[$asciiIndex]
}
# 组合并输出 (处理中文字符对齐)
$currentMenuLineWidth = Get-StringDisplayWidth -Text $menuLine
$paddingSpaces = " " * ($menuWidth - $currentMenuLineWidth)
$paddedMenuLine = $menuLine + $paddingSpaces
Write-Host "$paddedMenuLine$gap$asciiLine"
}
} else {
# 如果没有ASCII艺术,仅显示菜单
foreach ($line in $menuLines) {
Write-Host $line
}
}
# 确保颜色重置
Write-Host "$([char]27)[0m" -NoNewline
# 添加ASCII尺寸信息(调试用)
if ($asciiArt -and $env:DEBUG_ASCII) {
Write-Host "`n[ASCII Info: Width=$($asciiArt.Width), Height=$($asciiArt.Height)]" -ForegroundColor DarkGray
}
}
function Write-LogMessage {
param(
[string]$Message,
[string]$Level = "INFO",
[switch]$Silent
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp] [$Level] $Message"
# 创建日志目录如果不存在
if (-not (Test-Path (Split-Path $script:logFile))) {
New-Item -ItemType Directory -Path (Split-Path $script:logFile) -Force | Out-Null
}
# 写入日志文件
Add-Content -Path $script:logFile -Value $logMessage -ErrorAction SilentlyContinue
# 根据级别显示不同颜色
if (-not $Silent) {
switch ($Level) {
"ERROR" { Write-Host $Message -ForegroundColor Red }
"WARNING" { Write-Host $Message -ForegroundColor Yellow }
"SUCCESS" { Write-Host $Message -ForegroundColor Green }
default { Write-Host $Message }
}
}
}
function Test-AdminRights {
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
return $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Set-PowerScheme {
param(
[int]$Choice
)
$sourceGuid = ""
$schemeName = ""
switch ($Choice) {
1 {
$sourceGuid = "e9a42b02-d5df-448d-aa00-03f14749eb61" # 卓越性能
$schemeName = "卓越性能"
}
2 {
$sourceGuid = "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c" # 高性能
$schemeName = "高性能"
}
3 {
$sourceGuid = "a1841308-3541-4fab-bc81-f71556f20b4a" # 节能
$schemeName = "节能"
}
4 {
$sourceGuid = "381b4222-f694-41f0-9685-ff5bb260df2e" # 平衡
$schemeName = "平衡"
}
default {
Write-LogMessage "无效的电源模式选择。" -Level "ERROR"
return
}
}
Write-LogMessage "正在设置 $schemeName..."
# 尝试查找现有方案
$currentSchemes = powercfg /list
$existingSchemeLine = $currentSchemes | Select-String -Pattern "$schemeName" -ErrorAction SilentlyContinue
if ($existingSchemeLine) {
# 如果找到同名方案,提取其 GUID 并激活
$existingGuid = ([regex]::Match($existingSchemeLine, "[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}")).Value
Write-LogMessage "找到现有电源方案 '$schemeName',GUID 为:$existingGuid"
$setActiveResult = powercfg -setactive $existingGuid 2>&1
if ($LASTEXITCODE -eq 0) {
Write-LogMessage "'$schemeName' 已激活。" -Level "SUCCESS"
} else {
Write-LogMessage "激活 '$schemeName' 失败:$setActiveResult" -Level "ERROR"
}
} else {
# 如果未找到,则复制源方案并激活新方案
Write-LogMessage "未找到电源方案 '$schemeName',正在创建..."
$newSchemeOutput = powercfg -duplicatescheme $sourceGuid 2>&1
if ($LASTEXITCODE -eq 0) {
$newSchemeGuid = ([regex]::Match($newSchemeOutput, "[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}")).Value
if (-not [string]::IsNullOrEmpty($newSchemeGuid)) {
Write-LogMessage "新方案 '$schemeName' 已创建,GUID 为:$newSchemeGuid"
$setActiveResult = powercfg -setactive $newSchemeGuid 2>&1
if ($LASTEXITCODE -eq 0) {
Write-LogMessage "'$schemeName' ($newSchemeGuid) 已激活。" -Level "SUCCESS"
} else {
Write-LogMessage "激活新方案 '$schemeName' ($newSchemeGuid) 失败:$setActiveResult" -Level "ERROR"
}
} else {
Write-LogMessage "未能从输出中提取 GUID。原始输出:$newSchemeOutput" -Level "ERROR"
}
} else {
Write-LogMessage "创建新方案 '$schemeName' 失败:$newSchemeOutput" -Level "ERROR"
}
}
Read-Host "按任意键返回..." | Out-Null
}
function Set-ProxySettings {
try {
Write-LogMessage "正在配置代理设置..."
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyEnable -Value 1
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -Value "127.0.0.1:7897"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyOverride -Value "localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;airchina.com.*;10.10.101.*;*.airchina.com.cn"
Write-LogMessage "代理设置已完成。" -Level "SUCCESS"
} catch {
Write-LogMessage "代理设置失败:$($_.Exception.Message)" -Level "ERROR"
}
Read-Host "按任意键返回..." | Out-Null
}
function Install-AutoLogin {
# 检查是否需要管理员权限
if (-not (Test-AdminRights)) {
Write-Host "`n========================================" -ForegroundColor Yellow
Write-Host "安装自动登录需要管理员权限" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Yellow
$response = Read-Host "是否以管理员权限重新启动并继续安装?(Y/N)"
if ($response -ne 'Y' -and $response -ne 'y') {
Write-LogMessage "用户取消管理员权限提升" -Level "WARNING"
Read-Host "按任意键返回..." | Out-Null
return
}
try {
# 保存当前脚本到临时文件
$tempScriptPath = "$env:TEMP\install_autologin_$(Get-Random).ps1"
if ($script:scriptContent) {
# 如果是通过 irm | iex 运行的,使用保存的内容
$script:scriptContent | Out-File -FilePath $tempScriptPath -Encoding UTF8
} elseif ($PSCommandPath) {
# 如果是本地文件运行,复制文件
Copy-Item -Path $PSCommandPath -Destination $tempScriptPath -Force
} else {
Write-LogMessage "无法确定脚本来源,权限提升失败" -Level "ERROR"
Read-Host "按任意键返回..." | Out-Null
return
}
Write-Host "正在以管理员权限重新启动..." -ForegroundColor Cyan
# 使用环境变量传递参数,而不是命令行参数
$startScript = @"
`$env:PS_DIRECT_TO_AUTOLOGIN = "1"
`$env:PS_ELEVATED_SESSION = "1"
& "$tempScriptPath"
Remove-Item "$tempScriptPath" -Force -ErrorAction SilentlyContinue
"@
$startScriptPath = "$env:TEMP\start_elevated_$(Get-Random).ps1"
$startScript | Out-File -FilePath $startScriptPath -Encoding UTF8
# 启动新的管理员进程
$arguments = "-ExecutionPolicy Bypass -NoExit -File `"$startScriptPath`""
Start-Process powershell.exe -ArgumentList $arguments -Verb RunAs
Write-Host "请在新窗口中完成操作..." -ForegroundColor Green
Write-Host "原窗口可以关闭" -ForegroundColor Gray
Read-Host "按任意键关闭当前窗口..." | Out-Null
exit
} catch {
Write-LogMessage "权限提升失败:$($_.Exception.Message)" -Level "ERROR"
Read-Host "按任意键返回..." | Out-Null
return
}
}
# 以下是原有的安装逻辑
Write-LogMessage "开始安装自动登录脚本..."
# 验证用户输入
$username = ""
$password = ""
while ([string]::IsNullOrWhiteSpace($username)) {
$username = Read-Host "请输入用户名"
if ([string]::IsNullOrWhiteSpace($username)) {
Write-LogMessage "用户名不能为空!" -Level "WARNING"
}
}
$securePassword = Read-Host "请输入密码" -AsSecureString
$passwordPlainText = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword))
if ([string]::IsNullOrWhiteSpace($passwordPlainText)) {
Write-LogMessage "密码不能为空!" -Level "ERROR"
Read-Host "按任意键返回..." | Out-Null
return
}
# Python脚本内容 - 基于您的工作版本
$pythonScript = @'
import requests, time
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
# 配置
LOGIN_BASE_URL = "http://114.114.114.114:90"
LOGIN_PATH = "/login"
USERNAME = "PLACEHOLDER_USERNAME"
PASSWORD = "PLACEHOLDER_PASSWORD"
# --- md6 加密 ---
def mc(a):
if a == 32: return "+"
if (a < 48 and a not in (45, 46)) or (57 < a < 65) or (90 < a < 97 and a != 95) or a > 122:
return "%" + "0123456789ABCDEF"[a >> 4] + "0123456789ABCDEF"[a & 15]
return chr(a)
def m(a):
return (((a&1)<<7)|((a&2)<<5)|((a&4)<<3)|((a&8)<<1)|((a&16)>>1)|((a&32)>>3)|((a&64)>>5)|((a&128)>>7))
def md6(s):
return "".join(mc(m(ord(c)) ^ (0x35 ^ i)) for i,c in enumerate(s))
session = requests.Session()
import re
def _extract_uri_from_response(response):
"""
从响应中提取URI,优先从HTML中的input字段,其次从URL查询字符串。
"""
soup = BeautifulSoup(response.text, 'html.parser')
# 尝试从HTML中的隐藏input字段获取URI
uri_input = soup.find('input', {'id': 'uri', 'name': 'uri'})
if uri_input and 'value' in uri_input.attrs:
return uri_input['value']
# 尝试从URL的查询字符串中提取URI
parsed_url = urlparse(response.url)
uri_from_query = parsed_url.query
if uri_from_query:
return uri_from_query
return None
def get_uri_from_login_page():
try:
# 访问基础URL
initial_response = session.get(LOGIN_BASE_URL, allow_redirects=True)
initial_response.raise_for_status()
# 定义URI获取策略
strategies = [
# 策略1: 从当前响应中直接提取
lambda resp: _extract_uri_from_response(resp),
# 策略2: 从iframe中提取
lambda resp: _get_uri_from_iframe(resp),
# 策略3: 从JavaScript重定向中提取
lambda resp: _get_uri_from_js_redirect(resp)
]
for strategy in strategies:
uri = strategy(initial_response)
if uri:
return uri
print(f"未能在任何地方找到URI参数。最终URL: {initial_response.url}")
return None
except requests.exceptions.RequestException as e:
print(f"获取登录页面失败: {e}")
return None
def _get_uri_from_iframe(response):
soup = BeautifulSoup(response.text, 'html.parser')
iframe = soup.find('iframe')
if iframe and 'src' in iframe.attrs:
iframe_src = iframe['src']
full_iframe_url = urljoin(response.url, iframe_src)
iframe_response = session.get(full_iframe_url, allow_redirects=True)
iframe_response.raise_for_status()
return _extract_uri_from_response(iframe_response)
return None
def _get_uri_from_js_redirect(response):
soup = BeautifulSoup(response.text, 'html.parser')
scripts = soup.find_all('script')
for script in scripts:
if script.string:
match = re.search(r'(?:window\.location\.href|document\.location)\s*=\s*["\']([^"\']+)["\']', script.string)
if match:
redirect_url_relative = match.group(1)
full_redirect_url = urljoin(response.url, redirect_url_relative)
redirect_response = session.get(full_redirect_url, allow_redirects=True)
redirect_response.raise_for_status()
return _extract_uri_from_response(redirect_response)
return None
def login():
uri = get_uri_from_login_page()
if not uri:
print("无法获取URI,登录失败。")
return False
data = {
"uri": uri,
"terminal": "pc", "login_type": "login", "check_passwd": "1",
"username": USERNAME, "password": md6(PASSWORD), "password1": ""
}
try:
r = session.post(f"{LOGIN_BASE_URL}{LOGIN_PATH}", data=data)
if "您已经成功登录!" in r.text:
print("登录成功")
return True
print("登录失败")
return False
except Exception as e:
print("登录请求失败:", e)
return False
def logged_in():
try:
r = session.get(f"{LOGIN_BASE_URL}{LOGIN_PATH}")
return "您已经成功登录!" in r.text
except:
return False
def main():
print("开始检测,每5秒循环")
while True:
if not logged_in():
print("未登录,尝试登录...")
login()
time.sleep(5)
if __name__ == "__main__":
main()
'@
# 替换占位符
$pythonScript = $pythonScript.Replace("PLACEHOLDER_USERNAME", $username)
$pythonScript = $pythonScript.Replace("PLACEHOLDER_PASSWORD", $passwordPlainText)
# 停止现有进程
Write-LogMessage "停止现有Python进程..."
Stop-AutoLoginProcess
# 等待进程完全终止
Start-Sleep -Seconds 2
# 创建脚本目录
if (-not (Test-Path $script:scriptDir)) {
New-Item -ItemType Directory -Path $script:scriptDir -Force | Out-Null
Write-LogMessage "创建脚本目录:$script:scriptDir"
}
# 保存Python脚本
$scriptPath = "$script:scriptDir\login_script.py"
$pythonScript | Out-File -FilePath $scriptPath -Encoding UTF8
Write-LogMessage "Python脚本已保存到:$scriptPath"
# 设置Python环境
if (-not (Install-PythonEnvironment)) {
Write-LogMessage "Python环境设置失败!" -Level "ERROR"
Read-Host "按任意键返回..." | Out-Null
return
}
# 创建批处理文件
$batContent = @"
@echo off
cd /d "$script:scriptDir"
if exist "python\pythonw.exe" (
python\pythonw.exe login_script.py
) else if exist "python\python.exe" (
python\python.exe login_script.py
) else (
pythonw.exe login_script.py
)
"@
$batPath = "$script:scriptDir\run_login.bat"
$batContent | Out-File -FilePath $batPath -Encoding ASCII
# 创建VBS文件
$vbsContent = @"
CreateObject("Wscript.Shell").Run """$batPath""", 0, False
"@
$vbsPath = "$script:scriptDir\run_login_silent.vbs"
$vbsContent | Out-File -FilePath $vbsPath -Encoding ASCII
# 创建计划任务
if (Create-ScheduledTask) {
Write-LogMessage "自动登录脚本安装完成!" -Level "SUCCESS"
Write-LogMessage "脚本位置:$scriptPath"
# 清理敏感信息
$passwordPlainText = $null
$securePassword = $null
# 自动启动
Write-Host ""
$startNow = Read-Host "是否立即启动自动登录?(Y/N)"
if ($startNow -eq 'Y' -or $startNow -eq 'y') {
Start-AutoLoginDirect
}
Write-Host "`n安装完成!" -ForegroundColor Green
} else {
Write-LogMessage "计划任务创建失败,但脚本已安装。" -Level "WARNING"
}
# 不再直接退出,而是返回菜单
Read-Host "按任意键返回..." | Out-Null
}
function Install-PythonEnvironment {
$pythonDir = "$script:scriptDir\python"
# 检查是否已安装Python
if (Test-Path "$pythonDir\python.exe") {
Write-LogMessage "Python环境已存在,正在验证..."
# 验证pip和依赖包
$pipPath = "$pythonDir\Scripts\pip.exe"
if (Test-Path $pipPath) {
Write-LogMessage "正在检查并安装依赖包..."
& $pipPath install --upgrade requests beautifulsoup4 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-LogMessage "Python环境验证完成" -Level "SUCCESS"
return $true
}
}
}
Write-LogMessage "正在下载并安装Python环境..."
$pythonUrl = "https://www.python.org/ftp/python/3.11.0/python-3.11.0-embed-amd64.zip"
$pythonZip = "$script:scriptDir\python.zip"
try {
# 下载Python
Write-LogMessage "下载Python (约15MB)..."
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile($pythonUrl, $pythonZip)
# 解压Python - 使用更安全的方法
Write-LogMessage "解压Python..."
# 确保目标目录存在
if (-not (Test-Path $pythonDir)) {
New-Item -ItemType Directory -Path $pythonDir -Force | Out-Null
}
# 使用 .NET 方法解压,避免 PowerShell 的 Expand-Archive 问题
Add-Type -AssemblyName System.IO.Compression.FileSystem
try {
[System.IO.Compression.ZipFile]::ExtractToDirectory($pythonZip, $pythonDir)
} catch {
# 如果目录已存在文件,先清理再解压
if (Test-Path $pythonDir) {
Remove-Item "$pythonDir\*" -Recurse -Force -ErrorAction SilentlyContinue
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($pythonZip, $pythonDir)
}
Remove-Item $pythonZip -ErrorAction SilentlyContinue
# 修复python._pth文件
$pthFile = "$pythonDir\python311._pth"
if (Test-Path $pthFile) {
$pthContent = Get-Content $pthFile
$pthContent = $pthContent -replace '^#import site', 'import site'
$pthContent | Set-Content $pthFile
}
# 安装pip
Write-LogMessage "安装pip..."
$getpipUrl = "https://bootstrap.pypa.io/get-pip.py"
$getpipPath = "$script:scriptDir\get-pip.py"
$webClient.DownloadFile($getpipUrl, $getpipPath)
& "$pythonDir\python.exe" "$getpipPath" 2>&1 | Out-Null
# 安装依赖包
Write-LogMessage "安装依赖包..."
$pipPath = "$pythonDir\Scripts\pip.exe"
if (Test-Path $pipPath) {
& $pipPath install requests beautifulsoup4 2>&1 | Out-Null
} else {
& "$pythonDir\python.exe" -m pip install requests beautifulsoup4 2>&1 | Out-Null
}
# 清理
Remove-Item "$getpipPath" -ErrorAction SilentlyContinue
Write-LogMessage "Python环境设置完成" -Level "SUCCESS"
return $true
} catch {
Write-LogMessage "Python环境设置失败:$($_.Exception.Message)" -Level "ERROR"
# 尝试使用系统Python
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
if ($pythonCmd) {
Write-LogMessage "将使用系统Python..." -Level "WARNING"
return $true
}
return $false
}
}
function Create-ScheduledTask {
if (-not (Test-AdminRights)) {
Write-LogMessage "需要管理员权限来创建计划任务" -Level "WARNING"
Write-LogMessage "尝试使用当前用户权限创建任务..."
}
$vbsPath = "$script:scriptDir\run_login_silent.vbs"
# 创建任务XML - 修改为Windows 10兼容
$taskXml = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>$(Get-Date -Format 'yyyy-MM-ddTHH:mm:ss')</Date>
<Author>$env:USERNAME</Author>
<Description>NetworkLoginScript自动启动任务</Description>
</RegistrationInfo>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>false</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
<Compatibility>Win8</Compatibility>
</Settings>
<Triggers>
<BootTrigger>
<Enabled>true</Enabled>
</BootTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>$env:USERDOMAIN\$env:USERNAME</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Actions Context="Author">
<Exec>
<Command>wscript.exe</Command>
<Arguments>"$vbsPath"</Arguments>
</Exec>
</Actions>
</Task>
"@
try {
# 保存XML到临时文件
$tempXmlPath = "$env:TEMP\task_temp_$(Get-Random).xml"
$taskXml | Out-File -FilePath $tempXmlPath -Encoding Unicode
# 删除现有任务
$deleteResult = & schtasks /delete /tn "$script:taskName" /f 2>&1
# 使用XML创建任务
if (Test-AdminRights) {
# 如果有管理员权限,使用SYSTEM账户
$createResult = & schtasks /create /tn "$script:taskName" /xml "$tempXmlPath" /ru "SYSTEM" /f 2>&1
} else {
# 普通用户权限
$createResult = & schtasks /create /tn "$script:taskName" /xml "$tempXmlPath" /f 2>&1
}
# 删除临时文件
Remove-Item -Path $tempXmlPath -Force -ErrorAction SilentlyContinue
if ($LASTEXITCODE -eq 0) {
Write-LogMessage "计划任务创建成功(Windows 10 兼容模式)" -Level "SUCCESS"
# 验证设置是否正确应用
$task = Get-ScheduledTask -TaskName $script:taskName -ErrorAction SilentlyContinue
if ($task) {
Write-LogMessage "任务设置验证:电池模式运行 = $(-not $task.Settings.DisallowStartIfOnBatteries)" -Level "INFO"
Write-LogMessage "任务设置验证:无执行时限 = $($task.Settings.ExecutionTimeLimit -eq 'PT0S')" -Level "INFO"
Write-LogMessage "任务兼容性设置:$($task.Settings.Compatibility)" -Level "INFO"
}
return $true
} else {
Write-LogMessage "计划任务创建失败: $createResult" -Level "ERROR"
return $false
}
} catch {
Write-LogMessage "计划任务创建失败:$($_.Exception.Message)" -Level "ERROR"
return $false
}
}
function Get-AutoLoginStatus {
Write-LogMessage "检查自动登录状态..."
# 检查脚本文件
$scriptPath = "$script:scriptDir\login_script.py"
if (Test-Path $scriptPath) {
Write-Host "✓ 自动登录脚本已安装" -ForegroundColor Green
} else {
Write-Host "✗ 自动登录脚本未安装" -ForegroundColor Red
Read-Host "按任意键返回..." | Out-Null
return
}
# 检查Python环境
$pythonDir = "$script:scriptDir\python"
if (Test-Path "$pythonDir\python.exe") {
Write-Host "✓ Python环境已配置" -ForegroundColor Green
} else {
$systemPython = Get-Command python -ErrorAction SilentlyContinue
if ($systemPython) {
Write-Host "✓ 使用系统Python" -ForegroundColor Yellow
} else {
Write-Host "✗ Python环境未配置" -ForegroundColor Red
}
}
# 检查进程状态
$pythonProcess = Get-Process | Where-Object {
$_.ProcessName -match "python" -and $_.Path -like "*$script:scriptDir*"
} -ErrorAction SilentlyContinue
if ($pythonProcess) {
Write-Host "✓ 自动登录正在运行 (PID: $($pythonProcess.Id))" -ForegroundColor Green
} else {
Write-Host "✗ 自动登录未运行" -ForegroundColor Yellow
}
# 检查状态文件
$statusFile = "$script:scriptDir\login_status.json"
if (Test-Path $statusFile) {
try {
$status = Get-Content $statusFile | ConvertFrom-Json
Write-Host ""
Write-Host "状态信息:" -ForegroundColor Cyan
Write-Host " 当前状态:$($status.status)"
Write-Host " 最后检查:$($status.last_check)"
if ($status.last_login) {
Write-Host " 最后登录:$($status.last_login)" -ForegroundColor Green
}
if ($status.error_count -gt 0) {
Write-Host " 错误次数:$($status.error_count)" -ForegroundColor Yellow
}
} catch {
Write-LogMessage "无法读取状态文件" -Level "WARNING"
}
}
# 检查计划任务
Write-Host ""
$taskInfo = schtasks /query /tn "$script:taskName" /fo LIST /v 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "✓ 计划任务已配置" -ForegroundColor Green
# 解析任务状态
$taskInfoString = $taskInfo | Out-String
if ($taskInfoString -match "状态:\s*(.+?)\r?\n") {
$status = $Matches[1].Trim()
Write-Host " 任务状态:$status"
}