Created
August 8, 2025 13:50
-
-
Save Ma233/5b56e68b88d6859841f7c21910330f18 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Execute Remote Command on Multiple Devices Script | |
param( | |
[string]$IpListFile = "ip_list.txt", | |
[Parameter(Mandatory=$true)] | |
[string]$Username, | |
[Parameter(Mandatory=$true)] | |
[string]$Password, | |
[string]$PlinkPath = ".\plink.exe", | |
[Parameter(Mandatory=$true)] | |
[string]$Command | |
) | |
# Check if plink.exe exists | |
if (!(Test-Path $PlinkPath)) { | |
Write-Error "plink.exe not found at: $PlinkPath" | |
Write-Host "You can:" | |
Write-Host "1. Download plink.exe from https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html" | |
Write-Host "2. Put the downloaded plink.exe file to the same path of this script" | |
exit 1 | |
} | |
# Check if IP list file exists | |
if (!(Test-Path $IpListFile)) { | |
Write-Error "IP list file not found: $IpListFile" | |
Write-Host "Please create a text file containing IP addresses, one per line" | |
Write-Host "Example content:" | |
Write-Host "192.168.1.100" | |
Write-Host "192.168.1.101" | |
Write-Host "192.168.1.102" | |
exit 1 | |
} | |
# Read IP list from file | |
try { | |
$ip_list = Get-Content $IpListFile | Where-Object { $_.Trim() -ne "" } | |
Write-Host "Read $($ip_list.Count) IP addresses from file" -ForegroundColor Blue | |
Write-Host "Command to execute: $Command" -ForegroundColor Cyan | |
} | |
catch { | |
Write-Error "Failed to read IP list file: $_" | |
exit 1 | |
} | |
# Process each IP address | |
foreach ($ip in $ip_list) { | |
$ip = $ip.Trim() | |
if ($ip -eq "") { continue } | |
Write-Host "========== Executing on $ip ==========" -ForegroundColor Green | |
# Execute SSH command | |
try { | |
Write-Host "Executing command: $Command" -ForegroundColor Yellow | |
$command_output = & $PlinkPath -ssh $ip -l $Username -pw $Password -batch $Command 2>&1 | |
# Check if command executed successfully | |
if ($LASTEXITCODE -ne 0) { | |
$error_msg = ($command_output -join " ").Trim() | |
Write-Error "SSH connection or command execution failed for $ip : $error_msg" | |
exit 1 | |
} | |
# Display output to console | |
Write-Host "Command output:" -ForegroundColor Magenta | |
$command_output | ForEach-Object { Write-Host " $_" } | |
Write-Host "✓ Command executed successfully on $ip" -ForegroundColor Green | |
} | |
catch { | |
Write-Error "Exception occurred while processing $ip : $_" | |
exit 1 | |
} | |
Write-Host "" | |
} | |
Write-Host "Command executed successfully on all devices!" -ForegroundColor Green |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment