Powershell - Windows主机信息自动推送

0x01  可能很多同学都会遇到这么一个运维场景---

1、有些服务/程序表面活着,实际已经死了;

2、有些服务/程序是非法者入侵后第一时间就要处理的;

所以我们需要定期上传服务/程序进程状态,同时比对机器的日志信息以此来判断上述信息,这里推荐一个关于powershell发送TCP请求的小技巧,来实现这些需求

0x02  找个加密方式来处理我的TCP请求

不知道怎么说,反正安全挺重要的就对了,那么我们在传输TCP请求时也要考虑到安全因素,比如找个合适的加密方式加密一下数据,下面会简单介绍一个在powershell下如何使用RC4,后面会继续更新Powershell下如何使用AES,DES,3DES进行加密。

 1 #先定义一个函数处理RC4
 2 function rc4 {
 3     param(
 4         [Byte[]]$data,
 5         [Byte[]]$key
 6       )
 7 
 8     [Byte[]]$buffer = New-Object Byte[] $data.Length;
 9     $data.CopyTo($buffer, 0);
10     
11     [Byte[]]$s = New-Object Byte[] 256;
12     [Byte[]]$k = New-Object Byte[] 256;
13 
14     for ($i = 0; $i -lt 256; $i++)
15     {
16         $s[$i] = [Byte]$i;
17         $k[$i] = $key[$i % $key.Length];
18     }
19 
20     $j = 0;
21     for ($i = 0; $i -lt 256; $i++)
22     {
23         $j = ($j + $s[$i] + $k[$i]) % 256;
24         $temp = $s[$i];
25         $s[$i] = $s[$j];
26         $s[$j] = $temp;
27     }
28 
29     $i = $j = 0;
30     for ($x = 0; $x -lt $buffer.Length; $x++)
31     {
32         $i = ($i + 1) % 256;
33         $j = ($j + $s[$i]) % 256;
34         $temp = $s[$i];
35         $s[$i] = $s[$j];
36         $s[$j] = $temp;
37         [int]$t = ($s[$i] + $s[$j]) % 256;
38         $buffer[$x] = $buffer[$x] -bxor $s[$t];
39     }
40 
41     return $buffer;
42 }

如何使用RC4,

1 $msg = "test"
2 $enc = [System.Text.Encoding]::UTF8;
3 [Byte[]]$data = $enc.GetBytes($msg);
4 [Byte[]]$key = $enc.GetBytes("xxxxxxxxxxxxxxxxxx");
5 $encryptedBytes = rc4 $data $key;

$encryptedBytes这个变量中的内容就是经过RC4加密后的内容了。

0x03  Powershell下创建TCP请求

 1 #这里是接收端信息,我这里使用的是Flask
 2 $ip = 'xxx.xxx.xxx.xxx'
 3 $port = 'xxxx'
 4 $socket = new-object System.Net.Sockets.TcpClient($ip, $port)
 5 $stream = $socket.GetStream()
 6 $encoding = new-object System.Text.AsciiEncoding
 7 
 8 #举个例子,随便收集一些机器信息
 9 $localHost = hostname
10 $workstation = wmic path win32_computersystem get domain
11 $osVer =  wmic os get "caption,Version,buildnumber,osarchitecture,CSDVersion" /format:csv
12 $localIp = ipconfig /all
13 $Task = tasklist | findstr wuauserv
14 $msg = $localHost + '|' + $workstation + '|' + $osVer + '|' + $localIp + '|' + $Task
15 
16 #进行加密
17 $enc = [System.Text.Encoding]::UTF8
18 [Byte[]]$data = $enc.GetBytes($msg)
19 [Byte[]]$key = $enc.GetBytes("xxxxxxxxxx")
20 $encryptedBytes = rc4 $data $key
21 $b64Encrypted = [Convert]::ToBase64String($encryptedBytes)
22 $sendBuf  = $encoding.GetBytes(b64Encrypted)
23 #处理TCP请求
24 $stream.Write($sendBuf, 0, $sendBuf.Length)
25 $stream.Close()
26 $socket.Close()

0x04  后端接口收到信息后,结合$Key进行信息解密就可以成功拿到机器传递过来的信息,以此来综合判断我们想要保持运行的程序/服务是否健康。

猜你喜欢

转载自www.cnblogs.com/zhr1217/p/12897931.html