惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyberwarzone
Cyberwarzone
G
GRAHAM CLULEY
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Latest
Security Latest
P
Privacy & Cybersecurity Law Blog
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
Spread Privacy
Spread Privacy
Know Your Adversary
Know Your Adversary
K
Kaspersky official blog
T
Tor Project blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
Simon Willison's Weblog
Simon Willison's Weblog
雷峰网
雷峰网
I
Intezer
C
Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Latest news
Latest news
C
CERT Recently Published Vulnerability Notes
P
Privacy International News Feed
P
Proofpoint News Feed
F
Fortinet All Blogs
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
宝玉的分享
宝玉的分享
量子位
博客园 - 叶小钗
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Announcements
Recent Announcements
D
Darknet – Hacking Tools, Hacker News & Cyber Security
aimingoo的专栏
aimingoo的专栏
A
Arctic Wolf
Martin Fowler
Martin Fowler
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
IT之家
IT之家
小众软件
小众软件
T
The Blog of Author Tim Ferriss
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
D
DataBreaches.Net
Webroot Blog
Webroot Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog

博客园 - 萝卜L

TIA 轨迹 Trace USB Device Tree Viewer & 设备管理器 - 通用串行总线控制器 树莓派 DT 西门子 PLC 1500 过程时间性能 树莓派5 GPIO 输出 PWM PD 协议 E-Marker芯片、私有协议,联想 ThinkPad 135W 电源 Slim方口 ThinkPlus电源 树莓派 RaspberryPi 5 硬件 设备(dev) 芯片(SoC) BCM 线路编号(line) GPIO 针脚 gpioinfo pinout Solid Edge 仿真 Dynamic Designer Motion (DDM) Solid Edge PMI 智能尺寸 尺寸平面 Solid_Edge,尺寸、测量,从动、驱动,同步、顺序建模,变量表 变量类型 Dim Var SolidWorks & Solid Edge 装配体 零件 部件 移动 通过批处理快捷方式参数化调用 Lua 脚本:完整方案与备选方式 Win10 隐藏的 占用空间的 大文件 组态王 7.5 西门子 驱动 各版本 严重 异常 PLC、上位(HMI)接口约定 Modbus RTU TCP 网关 拓扑 TIA SIM 授权 iup "creation only"的时刻 lua 5.3 glue srlua/wsrlua console/windows CMake Luarocks OCX(ActiveX COM) 控件测试容器(tstcon32) 失败 问题 解决 Lua IUP Plot 柱状图 示例 GitHub Desktop 连接 Gitee 失败 EPLAN P8 学习笔记 配图 20250114 TIA Portal V19 STEP 7 Professional WinCC - Setup 安装过程中出错 失败 笔记 配图 20250110 windows zeroBrane Studio(zbstudio/zbs)配置 iuplua V3 Lua 找不到指定模块 找不到指定的程序 V2 网络 主机名 地址 解析 记戴尔/Dell U2913WM 显示器故障
powershell 作服务端 响应网络(socket tcp)连接 提供文件夹大小查询服务 V1.1
萝卜L · 2023-12-21 · via 博客园 - 萝卜L

包含:

  • 端口占用检测
  • 心跳包网络断线检测
  • 传入的数据是否为合法有效的目录路径检测
  • 读取计算文件夹大小(不含软链接|symlink)
  • 传回查询到的文件夹大小

Powershell Service

# Service.ps1
[cmdletbinding()] Param($Port = 8888)

$VerbosePreference = "Continue"
# 值或取`SilentlyContinue`,此时需调用脚本时传入`-Verbose`才等效`Continue`。
# `Continue`输出`Write-Verbose`的内容。

Write-Verbose("Check port {0} busy/available" -f $Port)
$Connection = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
if($Connection){
    if($Connection.OwningProcess.GetType().Name -eq "UInt32"){
        $Process_ID = $Connection.OwningProcess
    }
    else{
        $Process_ID = $Connection.OwningProcess[1]
        # `$Connection.OwningProcess`为数组对象(System.Object)
    }
    if($Process_ID){
        Write-Error("Port {0} is busy, using by process ID {1}." -f $Port, $Process_ID)
        Exit
    }
    else{
        Write-Verbose("Port {0} is available" -f $Port)
    }
}
else{
    Write-Verbose("Port {0} is available" -f $Port)
}
$Connection = $Null

$Listener = New-Object System.Net.Sockets.TcpListener -ArgumentList $Port
try{
    $Listener.Start()
    # 可能的异常:
    # # "通常每个套接字地址(协议/网络地址/端口)只允许使用一次。"
    # # CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    # # FullyQualifiedErrorId : SocketException
    Write-Verbose("Start linsten.")
}
catch {
    Write-Error("Linsten failed.")
    throw
}

Write-Verbose "Server started."

While ($True) {
    Write-Host("Waiting connection from port {0}" -f $Port)

    $Socket_TCP_Client = $Listener.AcceptTcpClient()
    # incoming socket tcp client endpoint.
    
    $Client_Address = $Socket_TCP_Client.client.RemoteEndPoint.ToString()
	Write-Verbose ("New connection from {0}" -f $Client_Address)

	# Start-Sleep -Milliseconds 1000

	$Stream = $Socket_TCP_Client.GetStream()
    $Stream.ReadTimeout = 1000 # ms
    # [NetworkStream.ReadTimeout Property](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.readtimeout?view=net-8.0)
    $Stream_Reader = [System.IO.StreamReader]::new($Stream)
    $Stream_Writer = New-Object System.IO.StreamWriter($Stream)

    $Previous_Communication_Time = Get-Date -UFormat %s

    $string = $Null
	While ($Socket_TCP_Client.Connected) {
        Write-Verbose "Try to read line."
        try{
            $string = $Stream_Reader.ReadLine()
        }
        catch{
            # 可能的异常:
            # # 使用“0”个参数调用“ReadLine”时发生异常:“无法从传输连接中读取数据: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。。”
            # # 使用“0”个参数调用“ReadLine”时发生异常:“无法从传输连接中读取数据: 你的主机中的软件中止了一个已建立的连接。。”
            Write-Verbose "Timeout, waiting data."
        }

        if($string -eq "exit"){
            Write-Verbose "Exit."

            $Stream_Reader.Dispose()
            Write-Verbose "Stream_Reader.Dispose done."
            $Stream_Reader.Close()
            Write-Verbose "Stream_Reader.Close done."

            $Stream_Writer.Dispose()
            Write-Verbose "Stream_Writer.Dispose done."
            $Stream_Writer.Close()
            Write-Verbose "Stream_Writer.Close done."

            $Stream.Dispose()
            Write-Verbose "Stream.Dispose done."
            $Stream.Close()
            Write-Verbose "Stream.Close done."
            
            $Socket_TCP_Client.Dispose()
            Write-Verbose "Socket_TCP_Client.Dispose done."
            $Socket_TCP_Client.Close()
            Write-Verbose "Socket_TCP_Client.Close done."

            break
        }
        if ($string) {
            Write-Verbose "Data available, line read."
            Write-Host("Message received from {0}:`n {1}" -f $Client_Address, $string)

            $Previous_Communication_Time = Get-Date -UFormat %s
            
            $Path = $string
            $string = $Null

            $Is_Path_Exist_Folder = $Null
            try{
                $Is_Path_Exist_Folder = Test-Path -Path $Path -PathType Container
                # 可能的异常:
                # # "Test-Path : 路径中具有非法字符。"
            }catch{}
            if($Is_Path_Exist_Folder){
                Write-Verbose "Path valid - Path is a folder."
            }
            else{
                Write-Verbose "Path invalid - Path is not a folder, skip."
            }

            if($Is_Path_Exist_Folder){
                Write-Verbose "Measure size (length) of folder.."
                $Command = 'Get-ChildItem -Path "'+ $Path + '" -Recurse | Measure-Object -Property Length -Sum'
                $GenericMeasureInfo = Invoke-Expression $Command
                $Size = $GenericMeasureInfo.Sum
                Write-Verbose("Folder size (length) is {0}." -f $Size)
			    
                Write-Verbose "Send size to client."
                $Stream_Writer.WriteLine($Size)
                $Stream_Writer.Flush()
            }
            else{
                Write-Verbose "Send error code to client."
			    $Stream_Writer.WriteLine("")
                $Stream_Writer.Flush()
            }
		}
        ElseIf((($Current_Time = (Get-Date -UFormat %s)) - $Previous_Communication_Time) -gt 3){ #等待数据超时,检查断线
            $bytes = 0
            try{ #heart-beat
                Write-Verbose "Heart-beat test."
                # 参见:[(16)Powershell中的转义字符 - yang-leo - 博客园](https://www.cnblogs.com/leoyang63/articles/12060596.html)
                $Stream_Writer.WriteLine("")
                $Stream_Writer.Flush()
                $Previous_Communication_Time = $Current_Time
                Write-Verbose("Connection {0} alive." -f $Client_Address)
            }catch{
                Write-Verbose("Connection {0} failed." -f $Client_Address)
                break
            }
        }
	}
    if($string -eq "exit"){
        break
    }else{
        Write-Host "Client disconnect."
    }
}

$Listener.Stop()
Write-Verbose "Listener.Stop done."
Write-Verbose "Server stopped."

Write-Host "Exit."
Exit

Lua Client

-- Client.lua
local Socket = require("socket")

local function Query_Size(self,Path)
	local Client = self._Client
	Client:send(Path..'\n')
	local result,response = ''
	repeat
		response = Client:receive"*l"
		result = result .. (response or '')
	until not response or result~=''
	return result
end
local function Close(self)
	local Client = self._Client
--	Client:shutdown()
	Client:close()
end
local Metatable = {__gc = Close,}

local Master = {
	Connect = function(Host_Name_or_IP,Port)
		local Client = assert(Socket.connect(Host_Name_or_IP or "localhost", Port or 8888))
		--	"connection refused"
		local Client_Agent = setmetatable(
			{
				Query_Size = Query_Size,
				Query = Query_Size,
				Close_Client = Close,
				Close = Close,
				_Client = Client,
				Close_Service = function()
					Client:send"Exit\n"
					Client:close()
				end,
			},Metatable
		)
		return Client_Agent
	end,
}

if not ... then --test
	local Client = Master.Connect()
	print(Client:Query_Size[[H:\Ghost]])
	print(Client:Query[[H:\土豆]])
	Client.Close_Service()
	Client:Close()
end

return Master