[個人筆記] 允許針對遠端機器執行PowerShell指令 (remote)

  • 8280
  • 0
  • 2020-03-16

疑難雜症的筆記

某個部落格文章的教學

https://ithelp.ithome.com.tw/articles/10186746

https://www.faqforge.com/windows/create-powershell-session-remote-computer/

基本的設置請參考上面

 

超級重要

執行的本地端(e.g. 你自己的電腦、Jenkins機器)

是本地端需要設置  TrustedHosts 

目標端也需要設置 TrustedHosts

另外需要執行下方這段 先開啟某個設定的樣子

winrm quickconfig

 

錯誤訊息: (无法加载文件此系统上禁止运行脚本)

set-ExecutionPolicy RemoteSigned

 

檢查是否有設置 TrustedHosts

 

如果偷懶設置allow all得話 請執行 * (all)

#設置特定的域名IP (用逗號隔開)
winrm set winrm/config/client '@{TrustedHosts="104.88.88.88,104.87.87.87"}' 

#設定allow all *
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force

 Get-Item WSMan:\localhost\Client\TrustedHosts  (取得當前已設置哪些白名單)

 

檢查是否可以遠端連線

Enter-PSSession -ComputerName "192.168.1.1" 

1. 如果response很慢 代表防火牆擋住之類了

2. 若很快得到回應、有拿到 access is deny的錯誤訊息 (拒絕存取),代表成功了 (只是因為沒有指定account、password參數 所以回應錯誤

 

其他注意事項

windows防火牆是否 5985 5986 port有允許白名單IP

 

範例script,透過遠端IP、帳號、密碼 連線

$pw = convertto-securestring -AsPlainText -Force -String "123456"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "192.168.1.1\admin_user_name",$pw


$sess = New-PSSession -Credential $cred -ComputerName 192.168.1.1

#範例一,簡單的印出某個資料夾的檔案
Invoke-Command -Session $sess -ScriptBlock {Get-ChildItem “C:\Users\gameadmin\Desktop\ps_test”}



#範例二 上傳資料夾、並覆蓋之
Copy-Item -Path 'C:\Users\user\Desktop\powerShell\cmd' -Destination 'C:\Users\gameadmin\Desktop\ps_test' -Recurse -force -ToSession $sess


 

 

其他指令備註


#強制允許、重新開啟
Enable-PSRemoting –force 
Restart-Service WinRM 



 

 

 

比較參數化的寫法

$para_account = "admin"
$para_password = "123456"
$para_host = "192.168.1.1"


#取得帶進來的參數一
$para_targetFilePath = $args[0]
$powerShell_arg_account = ("{0}\{1}" -f $para_host , $para_account)

#設定連線字串
$pw = convertto-securestring -AsPlainText -Force -String $para_password
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $powerShell_arg_account,$pw

$sess = New-PSSession -Credential $cred -ComputerName $para_host
#執行指定的檔案
Invoke-Command -Session $sess -ScriptBlock { Start-Process $args[0]} -Args $para_targetFilePath

 

包含if else 以及 判斷字串關鍵字


try {
	   
	$sess = New-PSSession -Credential $cred -ComputerName $para_host
	   
	#先檢查檔案是否存在
	$is_file_exist = Invoke-Command -Session $sess -ScriptBlock { Test-Path $args[0] } -Args $para_targetFilePath
	   
    if($is_file_exist -eq $False)
	{
		echo 'Error:file_not_found'
		exit -1
	}
	   
	if($para_targetFilePath -like '*ps1*') 
	{	   	
		#執行指定的檔案(powerShell)
		Invoke-Command -Session $sess -ScriptBlock { powershell $args[0] } -Args $para_targetFilePath
		
	}
	else 
	{	   	
		#執行指定的檔案(bat)
		Invoke-Command -Session $sess -ScriptBlock { Start-Process $args[0] } -Args $para_targetFilePath
	}
}
catch 
{    
	exit -1
}