tengo dos scripts Administrador remoto: Cargar las librerías necesarias para trabajar…
- User
tengo dos scripts Administrador remoto:
Cargar las librerías necesarias para trabajar con Forms
Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing
Definir la función DestroyIcon de la API de Windows
Add-Type @" using System; using System.Runtime.InteropServices;
public class User32 { [DllImport("user32.dll")] public static extern bool DestroyIcon(IntPtr hIcon); } "@
#*************************************************************************************** $ImagenBytes = [Convert]::FromBase64String('cadena')
Crear un MemoryStream y cargar la imagen
ImagenBytes) ms)
Crear un Bitmap y un Icono
image) bitmap.GetHicon() iconHandle)
No liberar el icono aquí, lo haremos más tarde
Liberar recursos de la imagen y el bitmap
bitmap.Dispose()
#*************************************************************************************** #Variables $Global:puerto=4430
Función para cargar la lista de servidores desde un archivo
function Load-ServerList { serverList = @() if (Test-Path "servers.txt") { Get-Content "servers.txt" | ForEach-Object { if (_ -match "(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}) - (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}) - (.+)") { matches serverList += [PSCustomObject]@{ DateTime = matches[1] IP = matches[3] } } } } return $serverList }
Crear el formulario de selección de servidor
serverSelectionForm.Text = "Seleccionar Servidor" serverSelectionForm.StartPosition = "CenterScreen" icon serverListBox.Location = New-Object System.Drawing.Point(10, 10) serverSelectionForm.Controls.Add($serverListBox)
connectButton.Location = New-Object System.Drawing.Point(150, 220) connectButton.Text = "Conectar" connectButton)
Evento del botón Conectar
connectButton.Add_Click({ if (serverListBox.SelectedItem) { servers[serverSelectionForm.Close() [User32]::DestroyIcon($iconHandle)
# Cargar el directorio inicial (por ejemplo, el directorio de usuario) Update-FileList -remoteServer $global:selectedServer.IP -remotePort $Global:puerto -path $env:USERPROFILE # Cargar procesos y servicios iniciales Refrescar-Procesos Refrescar-Servicios # Mostrar el formulario $form.ShowDialog() # Evento Conectar $listBox.Tag = $initialPath } else { [System.Windows.Forms.MessageBox]::Show("Por favor, seleccione un servidor.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }})
Cargar la lista de servidores
server in servers) { serverListBox.Items.Add("server.DateTime) - server.IP) - server.Description)") }
Mostrar el formulario de selección de servidor
$serverSelectionForm.ShowDialog()
Crear una ventana principal
form.Text = "Administrador de Equipos Remotos - global:selectedServer.IP)" form.StartPosition = "CenterScreen" form.ControlBox = $false
#************************************************************************************* #Control de pestañas tabControl.Location = New-Object System.Drawing.Point(0, 0) $tabControl.Size = New-Object System.Drawing.Size(800, 700)
#Definir pestañas TabFiles.Text = "Archivos"
tabPageProcesos.Text = "Procesos" $tabPageProcesos.Add_Enter({ Refrescar-Procesos })
tabPageServicios.Text = "Servicios" $tabPageServicios.Add_Enter({ Refrescar-Servicios })
#Agregar las pestañas al form TabFiles) tabPageProcesos) tabPageServicios)
#Agregar el control al form tabControl)
Pestaña de Procesos
txtBusquedaProcesos.Location = New-Object System.Drawing.Point(10, 10) tabPageProcesos.Controls.Add($txtBusquedaProcesos)
btnBuscarProcesos.Location = New-Object System.Drawing.Point(220, 10) btnBuscarProcesos.Text = "Buscar" btnBuscarProcesos)
btnMatarProcesos.Location = New-Object System.Drawing.Point(10, 530) btnMatarProcesos.Text = "Terminar proceso" btnMatarProcesos) $btnMatarProcesos.Add_Click({ terminar-proceso })
dataGridProcesos.Location = New-Object System.Drawing.Point(10, 40) dataGridProcesos.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill true false tabPageProcesos.Controls.Add($dataGridProcesos)
Pestaña de Servicios
txtBusquedaServicios.Location = New-Object System.Drawing.Point(10, 10) tabPageServicios.Controls.Add($txtBusquedaServicios)
btnBuscarServicios.Location = New-Object System.Drawing.Point(220, 10) btnBuscarServicios.Text = "Buscar" btnBuscarServicios)
btnExcluirMicrosoft.Location = New-Object System.Drawing.Point(310, 10) btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" btnExcluirMicrosoft)
dataGridServicios.Location = New-Object System.Drawing.Point(10, 40) dataGridServicios.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill true false tabPageServicios.Controls.Add($dataGridServicios)
btnRefrescarServicios.Location = New-Object System.Drawing.Point(10, 530) btnRefrescarServicios.Text = "Refrescar Servicios" btnRefrescarServicios)
btnIniciarServicio.Location = New-Object System.Drawing.Point(140, 530) btnIniciarServicio.Text = "Iniciar" btnIniciarServicio) $btnIniciarServicio.Add_Click({ Iniciar-Servicios })
btnDetenerServicio.Location = New-Object System.Drawing.Point(230, 530) btnDetenerServicio.Text = "Detener" btnDetenerServicio) $btnDetenerServicio.Add_Click({ Detener-Servicios })
btnReiniciarServicio.Location = New-Object System.Drawing.Point(320, 530) btnReiniciarServicio.Text = "Reiniciar" btnReiniciarServicio) $btnReiniciarServicio.Add_Click({ reiniciar-Servicios })
Función para refrescar la lista de procesos
function Refrescar-Procesos { param ( [string]command = "GET_PROCESSES|procesos = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($procesos) { $dataGridProcesos.DataSource = [System.Collections.ArrayList]@($procesos) $dataGridProcesos.Refresh() }}
Función para refrescar la lista de servicios
function Refrescar-Servicios { param ( [string]command = "GET_SERVICES|global:excluirMicrosoft" global:selectedServer.IP -remotePort command
if ($servicios) { $dataGridServicios.DataSource = [System.Collections.ArrayList]@($servicios) $dataGridServicios.Refresh() }}
Función para detener un servicio
function Detener-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "STOP_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para iniciar servicio
function Iniciar-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "START_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio iniciado exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al iniciar el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para iniciar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para matar proceso
function terminar-proceso { dataGridProcesos.SelectedRows[0].Cells["id"].Value if (procesoseleccionado) { command = "TERMINATE_PROCESS|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Proceso detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Procesos } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el proceso: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un proceso para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para iniciar servicio
function reiniciar-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "RESTART_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Eventos
btnRefrescarServicios.Add_Click({ global:excluirMicrosoft = btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" Refrescar-Servicios })
btnBuscarProcesos.Add_Click({ Refrescar-Procesos -filtro txtBusquedaProcesos.Text }) btnBuscarServicios.Add_Click({ Refrescar-Servicios -filtro txtBusquedaServicios.Text })
btnExcluirMicrosoft.Add_Click({ global:excluirMicrosoft = -not global:excluirMicrosoft) { btnExcluirMicrosoft.Text = "Mostrar todos los servicios" } else { btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" } Refrescar-Servicios })
#*************************************************************************************
Crear un control de lista para mostrar los archivos y carpetas
listBox.Size = New-Object System.Drawing.Size(750, 240) TabFiles.Controls.Add($listBox)
txtComando.Location = New-Object System.Drawing.Point(20, 320) txtComando.Font = New-Object System.Drawing.Font("Consolas", 10) txtComando)
txtSalida.Location = New-Object System.Drawing.Point(20, 350) txtSalida.Multiline = txtSalida.ScrollBars = "Vertical" #txtSalida.BackColor = [System.Drawing.Color]::Blue # Fondo azul txtSalida.ForeColor = [System.Drawing.Color]::White # Texto blanco txtSalida.Rtf = "{\rtf1\ansi\deff0{\fonttbl{\f0 Consolas;}}{\f0\fs20\sl240\slmult1}}" true txtSalida)
Función para ejecutar comandos PowerShell remotos
function Execute-RemoteCommand { param ( [string]command ) try { commandToSend = "EXECUTE_COMMAND|response = Send-RemoteCommand -remoteServer Global:puerto -command $commandToSend
if ($response.success) { $txtSalida.Clear() $txtSalida.AppendText(">> $command`r`n") $txtSalida.AppendText($response.output + "`r`n`r`n") } else { $txtSalida.AppendText("Error: $($response.message)`r`n`r`n") } } catch { $txtSalida.AppendText("Error de ejecución: $($_.Exception.Message)`r`n`r`n") }}
Evento del botón Enviar
#$btnEnviarComando.Add_Click({
if ($txtComando.Text.Trim()) {
Execute-RemoteCommand -command $txtComando.Text.Trim()
$txtComando.Clear()
}
#})
Evento para manejar la tecla Enter en el TextBox de comandos
txtComando.Add_KeyDown({ param(sender, e.KeyCode -eq [System.Windows.Forms.Keys]::Enter) { if (txtComando.Text.Trim()) { Execute-RemoteCommand -command txtComando.Text.Trim() txtComando.Clear() } e.SuppressKeyPress = $true } })
Crear botones para las diferentes acciones
#btnEnviarComando = New-Object System.Windows.Forms.Button #btnEnviarComando.Location = New-Object System.Drawing.Point(680, 320) #btnEnviarComando.Size = New-Object System.Drawing.Size(90, 23) #btnEnviarComando.Text = "Enviar" #btnEnviarComando)
buttonDownload.Text = "Descargar" buttonDownload.Location = New-Object System.Drawing.Point(10, 270) buttonDownload)
buttonDelete.Text = "Eliminar" buttonDelete.Location = New-Object System.Drawing.Point(120, 270) buttonDelete)
buttonCopy.Text = "Copiar" buttonCopy.Location = New-Object System.Drawing.Point(230, 270) buttonCopy)
buttonMove.Text = "Mover" buttonMove.Location = New-Object System.Drawing.Point(340, 270) buttonMove)
buttonUpload.Text = "Subir" buttonUpload.Location = New-Object System.Drawing.Point(450, 270) buttonUpload)
buttonSalir.Text = "Salir" buttonSalir.Location = New-Object System.Drawing.Point(560, 270) buttonSalir)
buttonSalir.Add_Click({ form.Hide() # Ocultar el formulario principal en lugar de cerrarlo
$serverSelectionForm.Show() # Mostrar el formulario de selección de servidor
})
buttonRDP.Text = "Escritorio Remoto" buttonRDP.Location = New-Object System.Drawing.Point(670, 270) buttonRDP)
$buttonRDP.Add_Click({
Start-Process "mstsc.exe" -ArgumentList "/v:$($global:selectedServer.IP) /f"})
#Controlar el cierre del formulario form.Add_FormClosing({ # Ocultar el formulario en lugar de cerrarlo form.Hide() # Oculta el formulario
$serverSelectionForm.Show() # Muestra el formulario de selección de servidor
# Cancelar el cierre del formulario principal $_.Cancel = $true # Esto cancela el cierre del formulario})
Funcion para subir archivos
buttonUpload.Add_Click({ openFileDialog = New-Object System.Windows.Forms.OpenFileDialog openFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { openFileDialog.FileName listBox.SelectedItem if (-not remoteFilePath = Join-Path -Path localPath) localPath) fileContent) remoteFilePath|response = Send-RemoteCommand -remoteServer Global:puerto -command response.success) { [System.Windows.Forms.MessageBox]::Show("Archivo subido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Update-FileList -remoteServer Global:puerto -path remotePath } else { [System.Windows.Forms.MessageBox]::Show("Error al subir el archivo: ($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } })
Función para enviar comandos al servidor remoto
function Send-RemoteCommand { param ( [string]remotePort, [string]command ) try { client = New-Object System.Net.Sockets.TcpClient(remotePort) client.GetStream() stream) stream)
Write-Host "Enviando comando: $($command.Substring(0, [Math]::Min(100, $command.Length)))..." $writer.WriteLine($command) $writer.Flush() $response = $reader.ReadToEnd() Write-Host "Respuesta recibida: $response" $reader.Close() $writer.Close() $stream.Close() $client.Close() return $response | ConvertFrom-Json } catch { Write-Host "Error de conexión: $($_.Exception.Message)" -ForegroundColor Red [System.Windows.Forms.MessageBox]::Show("Error de conexión: $($_.Exception.Message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) return $null }}
Función para actualizar la lista de archivos
function Update-FileList { param ( [string]remotePort, [string]command = "LIST_FILES|response = Send-RemoteCommand -remoteServer remotePort -command response -and response.files) { $listBox.Items.Clear()
# Agregar '..' al inicio de la lista si no estamos en la raíz if ($path -ne [System.IO.Path]::GetPathRoot($path)) { $listBox.Items.Add('..') } foreach ($file in $response.files) { $listBox.Items.Add($file) } } else { [System.Windows.Forms.MessageBox]::Show("No se pudieron obtener los archivos.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para descargar un archivo
buttonDownload.Add_Click({ selectedFile = selectedFile) { saveFileDialog.FileName = [System.IO.Path]::GetFileName($selectedFile)
if ($saveFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $localPath = $saveFileDialog.FileName $command = "DOWNLOAD_FILE|$selectedFile" $response = Send-RemoteCommand -remoteServer $global:selectedServer.IP -remotePort $Global:puerto -command $command if ($response.success) { $fileContentBase64 = $response.fileContent $fileContent = [System.Convert]::FromBase64String($fileContentBase64) [System.IO.File]::WriteAllBytes($localPath, $fileContent) [System.Windows.Forms.MessageBox]::Show("Archivo descargado exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } else { [System.Windows.Forms.MessageBox]::Show("Error al descargar el archivo: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para descargar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }})
Función para eliminar un archivo
buttonDelete.Add_Click({ selectedFile = selectedFile) { selectedFile" global:selectedServer.IP -remotePort command if (response.success) { [System.Windows.Forms.MessageBox]::Show(response.message, "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Update-FileList -remoteServer Global:puerto -path (Split-Path -Parent selectedFile) } else { [System.Windows.Forms.MessageBox]::Show(response.message, "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para eliminar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Función para copiar un archivo
buttonCopy.Add_Click({ selectedFile = selectedFile) { folderBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { folderBrowser.SelectedPath -ChildPath (Split-Path -Leaf command = "COPY_FILE|destination" global:selectedServer.IP -remotePort command [System.Windows.Forms.MessageBox]::Show($response.message, "Resultado", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para copiar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Función para mover un archivo
buttonMove.Add_Click({ selectedFile = selectedFile) { folderBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { folderBrowser.SelectedPath -ChildPath (Split-Path -Leaf command = "MOVE_FILE|destination" global:selectedServer.IP -remotePort command [System.Windows.Forms.MessageBox]::Show(global:selectedServer.IP -remotePort selectedFile) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para mover.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Evento para manejar el doble clic en el ListBox
listBox.Add_DoubleClick({ selectedItem = selectedItem) { if (selectedItem -eq '..') { # Subir un nivel de directorio currentPath = listBox.Tag # Asumimos que guardamos la ruta actual en la propiedad Tag del ListBox parentPath = [System.IO.Path]::GetDirectoryName(global:selectedServer.IP -remotePort parentPath parentPath } elseif (Test-Path selectedItem -PathType Container) { # Si es un directorio, actualizar la lista de archivos Update-FileList -remoteServer global:selectedServer.IP -remotePort selectedItem selectedItem } else { # Si es un archivo, mostrar un mensaje [System.Windows.Forms.MessageBox]::Show("Seleccionaste el archivo: $selectedItem", "Información", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } } })
$serverSelectionForm.ShowDialog()
y el aente:
Importar los ensamblados necesarios para System.Net
Add-Type -AssemblyName System.Net
endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, listener = New-Object System.Net.Sockets.TcpListener listener.Start()
Write-Host "Escuchando en el puerto $port..."
while (true) { client = stream = reader = New-Object System.IO.StreamReader(writer = New-Object System.IO.StreamWriter($stream)
$command = $reader.ReadLine() Write-Host "Comando recibido: $($command.Substring(0, [Math]::Min(100, $command.Length)))..." $parts = $command -split '\|' $action = $parts[0] switch ($action) { "EXECUTE_COMMAND" { $commandToExecute = $parts[1] try { $output = Invoke-Expression $commandToExecute | Out-String $response = @{ success = $true output = $output } | ConvertTo-Json } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "UPLOAD_FILE" { $remoteFilePath = $parts[1] $fileContentBase64 = $parts[2] try { $fileContent = [System.Convert]::FromBase64String($fileContentBase64) [System.IO.File]::WriteAllBytes($remoteFilePath, $fileContent) $response = @{ success = $true message = "Archivo subido exitosamente." } | ConvertTo-Json -Compress } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) $writer.Flush() } "LIST_FILES" { $directoryPath = $parts[1] try { if (Test-Path $directoryPath) { $files = Get-ChildItem -Path $directoryPath | Select-Object -ExpandProperty FullName $response = @{ success = $true files = @($files) currentPath = $directoryPath } | ConvertTo-Json -Compress } else { $response = @{ success = $false message = 'Directorio no encontrado' } | ConvertTo-Json -Compress } } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) $writer.Flush() } "DELETE_FILE" { $filePath = $parts[1] try { Remove-Item -Path $filePath -Force $response = @{success=$true; message='Archivo eliminado.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "COPY_FILE" { $sourcePath = $parts[1] $destinationPath = $parts[2] try { Copy-Item -Path $sourcePath -Destination $destinationPath $response = @{success=$true; message='Archivo copiado.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "MOVE_FILE" { $sourcePath = $parts[1] $destinationPath = $parts[2] try { Move-Item -Path $sourcePath -Destination $destinationPath $response = @{success=$true; message='Archivo movido.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "DOWNLOAD_FILE" { $remoteFilePath = $parts[1] try { if (Test-Path $remoteFilePath) { $fileContent = [System.IO.File]::ReadAllBytes($remoteFilePath) $fileContentBase64 = [System.Convert]::ToBase64String($fileContent) $response = @{ success = $true fileContent = $fileContentBase64 fileName = [System.IO.Path]::GetFileName($remoteFilePath) } | ConvertTo-Json -Compress } else { $response = @{ success = $false message = "El archivo no existe." } | ConvertTo-Json -Compress } $writer.WriteLine($response) $writer.Flush() } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress $writer.WriteLine($response) $writer.Flush() } }"GET_PROCESSES" { $filtro = $parts[1] $procesos = Get-Process | ForEach-Object { [PSCustomObject]@{ Id = $_.Id Name = $_.Name CPU = $_.CPU "Memory (MB)" = [math]::Round($_.WorkingSet64 / 1MB, 2) } } | Sort-Object Name if ($filtro) { $procesos = $procesos | Where-Object { $_.Name -like "*$filtro*" -or $_.Id -like "*$filtro*" } } $writer.WriteLine(($procesos | ConvertTo-Json)) } "GET_SERVICES" { $filtro = $parts[1] $excluirMicrosoft = [System.Convert]::ToBoolean($parts[2]) $servicios = Get-CimInstance -ClassName Win32_Service | Select-Object Name, DisplayName, State, StartMode, @{Name="CompanyName";Expression={ $_.PathName | ForEach-Object { (Get-ItemProperty $_).VersionInfo.CompanyName }}} | Sort-Object DisplayName if ($filtro) { $servicios = $servicios | Where-Object { $_.Name -like "*$filtro*" -or $_.DisplayName -like "*$filtro*" } } if ($excluirMicrosoft) { $servicios = $servicios | Where-Object { $_.CompanyName -notlike "*Microsoft*" } } $writer.WriteLine(($servicios | ConvertTo-Json)) } "TERMINATE_PROCESS" { $processId = $parts[1] try { Stop-Process -Id $processId -Force $response = @{ success = $true message = "Proceso terminado" } | ConvertTo-Json } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json } # Enviar siempre la respuesta en formato JSON $writer.WriteLine($response) $writer.Flush() } "START_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop if ($service.Status -eq 'Stopped') { Start-Service -Name $serviceName -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' iniciado exitosamente." } | ConvertTo-Json } else { $response = @{ success = $false message = "El servicio '$serviceName' está en ejecución." } | ConvertTo-Json } } catch { $response = @{ success = $false message = "Error al iniciar el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "STOP_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop if ($service.Status -eq 'Running') { Stop-Service -Name $serviceName -Force -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' detenido exitosamente." } | ConvertTo-Json } else { $response = @{ success = $false message = "El servicio '$serviceName' no está en ejecución." } | ConvertTo-Json } } catch { $response = @{ success = $false message = "Error al detener el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "RESTART_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop Restart-Service -Name $serviceName -Force -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' detenido exitosamente." } | ConvertTo-Json } catch { $response = @{ success = $false message = "Error al detener el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } default { $response = @{success=$false; message='Comando no reconocido'} | ConvertTo-Json -Compress Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } } $writer.Flush() $client.Close()}
$listener.Stop()
Quiero que el agente pueda registrarse en el archivo que lee el administrador remoto (servers.txt) donde colocan esta información: 10/07/2024 15:16:35 - 192.168.64.200 - AD
- Assistant
Para que el agente pueda registrarse en el archivo
servers.txtque el script del administrador remoto lee, puedes agregar una función al script del agente que escriba la información necesaria en ese archivo. Aquí tienes una posible implementación:Modificaciones en el Script del Agente
-
Función para Registrar el Agente en el Archivo de Servidores:
Añade una función en el script del agente que se encargue de registrar la IP del agente en
servers.txt.
function Register-Agent { param ( [string]$serverFilePath, [string]$description = "Descripción del servidor" ) $currentDateTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $agentIP = (Test-Connection -ComputerName (hostname) -Count 1).Address.IPAddressToString if (-not (Test-Path $serverFilePath)) { New-Item -Path $serverFilePath -ItemType File -Force } $entry = "$currentDateTime - $agentIP - $description" $entryExists = Get-Content $serverFilePath | Select-String -Pattern "$agentIP" if (-not $entryExists) { Add-Content -Path $serverFilePath -Value $entry Write-Host "Agente registrado: $entry" } else { Write-Host "Agente ya registrado." } }-
Llamada a la Función de Registro:
Llama a esta función en un momento apropiado de la ejecución del script del agente, por ejemplo, justo después de iniciar la escucha en el puerto:
$port = 4430 $endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, $port) $listener = New-Object System.Net.Sockets.TcpListener $endpoint $listener.Start() Write-Host "Escuchando en el puerto $port..." # Registrar el agente Register-Agent -serverFilePath "C:\ruta\a\servers.txt" -description "AD"Asegúrate de reemplazar
"C:\ruta\a\servers.txt"con la ruta correcta al archivoservers.txt.Consideraciones
- Ruta de Acceso: Asegúrate de que la cuenta que ejecuta el script del agente tenga permisos de escritura sobre el archivo
servers.txt. - Formato de Escritura: El formato de la fecha y hora, así como la IP, deben coincidir con el patrón esperado por el script del administrador remoto (
(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}) - (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - (.+)). - Prevención de Duplicados: El script del agente se asegura de no duplicar la información en
servers.txt, verificando si la IP ya está registrada. - Seguridad: Considera posibles implicaciones de seguridad al permitir que un agente registre información en un archivo del servidor.
-
- User
tengo dos scripts Administrador remoto:
Cargar las librerías necesarias para trabajar con Forms
Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing
Definir la función DestroyIcon de la API de Windows
Add-Type @" using System; using System.Runtime.InteropServices;
public class User32 { [DllImport("user32.dll")] public static extern bool DestroyIcon(IntPtr hIcon); } "@
#*************************************************************************************** $ImagenBytes = [Convert]::FromBase64String('cadena')
Crear un MemoryStream y cargar la imagen
ImagenBytes) ms)
Crear un Bitmap y un Icono
image) bitmap.GetHicon() iconHandle)
No liberar el icono aquí, lo haremos más tarde
Liberar recursos de la imagen y el bitmap
bitmap.Dispose()
#*************************************************************************************** #Variables $Global:puerto=4430
Función para cargar la lista de servidores desde un archivo
function Load-ServerList { serverList = @() if (Test-Path "servers.txt") { Get-Content "servers.txt" | ForEach-Object { if (_ -match "(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}) - (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}) - (.+)") { matches serverList += [PSCustomObject]@{ DateTime = matches[1] IP = matches[3] } } } } return $serverList }
Crear el formulario de selección de servidor
serverSelectionForm.Text = "Seleccionar Servidor" serverSelectionForm.StartPosition = "CenterScreen" icon serverListBox.Location = New-Object System.Drawing.Point(10, 10) serverSelectionForm.Controls.Add($serverListBox)
connectButton.Location = New-Object System.Drawing.Point(150, 220) connectButton.Text = "Conectar" connectButton)
Evento del botón Conectar
connectButton.Add_Click({ if (serverListBox.SelectedItem) { servers[serverSelectionForm.Close() [User32]::DestroyIcon($iconHandle)
# Cargar el directorio inicial (por ejemplo, el directorio de usuario) Update-FileList -remoteServer $global:selectedServer.IP -remotePort $Global:puerto -path $env:USERPROFILE # Cargar procesos y servicios iniciales Refrescar-Procesos Refrescar-Servicios # Mostrar el formulario $form.ShowDialog() # Evento Conectar $listBox.Tag = $initialPath } else { [System.Windows.Forms.MessageBox]::Show("Por favor, seleccione un servidor.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }})
Cargar la lista de servidores
server in servers) { serverListBox.Items.Add("server.DateTime) - server.IP) - server.Description)") }
Mostrar el formulario de selección de servidor
$serverSelectionForm.ShowDialog()
Crear una ventana principal
form.Text = "Administrador de Equipos Remotos - global:selectedServer.IP)" form.StartPosition = "CenterScreen" form.ControlBox = $false
#************************************************************************************* #Control de pestañas tabControl.Location = New-Object System.Drawing.Point(0, 0) $tabControl.Size = New-Object System.Drawing.Size(800, 700)
#Definir pestañas TabFiles.Text = "Archivos"
tabPageProcesos.Text = "Procesos" $tabPageProcesos.Add_Enter({ Refrescar-Procesos })
tabPageServicios.Text = "Servicios" $tabPageServicios.Add_Enter({ Refrescar-Servicios })
#Agregar las pestañas al form TabFiles) tabPageProcesos) tabPageServicios)
#Agregar el control al form tabControl)
Pestaña de Procesos
txtBusquedaProcesos.Location = New-Object System.Drawing.Point(10, 10) tabPageProcesos.Controls.Add($txtBusquedaProcesos)
btnBuscarProcesos.Location = New-Object System.Drawing.Point(220, 10) btnBuscarProcesos.Text = "Buscar" btnBuscarProcesos)
btnMatarProcesos.Location = New-Object System.Drawing.Point(10, 530) btnMatarProcesos.Text = "Terminar proceso" btnMatarProcesos) $btnMatarProcesos.Add_Click({ terminar-proceso })
dataGridProcesos.Location = New-Object System.Drawing.Point(10, 40) dataGridProcesos.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill true false tabPageProcesos.Controls.Add($dataGridProcesos)
Pestaña de Servicios
txtBusquedaServicios.Location = New-Object System.Drawing.Point(10, 10) tabPageServicios.Controls.Add($txtBusquedaServicios)
btnBuscarServicios.Location = New-Object System.Drawing.Point(220, 10) btnBuscarServicios.Text = "Buscar" btnBuscarServicios)
btnExcluirMicrosoft.Location = New-Object System.Drawing.Point(310, 10) btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" btnExcluirMicrosoft)
dataGridServicios.Location = New-Object System.Drawing.Point(10, 40) dataGridServicios.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill true false tabPageServicios.Controls.Add($dataGridServicios)
btnRefrescarServicios.Location = New-Object System.Drawing.Point(10, 530) btnRefrescarServicios.Text = "Refrescar Servicios" btnRefrescarServicios)
btnIniciarServicio.Location = New-Object System.Drawing.Point(140, 530) btnIniciarServicio.Text = "Iniciar" btnIniciarServicio) $btnIniciarServicio.Add_Click({ Iniciar-Servicios })
btnDetenerServicio.Location = New-Object System.Drawing.Point(230, 530) btnDetenerServicio.Text = "Detener" btnDetenerServicio) $btnDetenerServicio.Add_Click({ Detener-Servicios })
btnReiniciarServicio.Location = New-Object System.Drawing.Point(320, 530) btnReiniciarServicio.Text = "Reiniciar" btnReiniciarServicio) $btnReiniciarServicio.Add_Click({ reiniciar-Servicios })
Función para refrescar la lista de procesos
function Refrescar-Procesos { param ( [string]command = "GET_PROCESSES|procesos = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($procesos) { $dataGridProcesos.DataSource = [System.Collections.ArrayList]@($procesos) $dataGridProcesos.Refresh() }}
Función para refrescar la lista de servicios
function Refrescar-Servicios { param ( [string]command = "GET_SERVICES|global:excluirMicrosoft" global:selectedServer.IP -remotePort command
if ($servicios) { $dataGridServicios.DataSource = [System.Collections.ArrayList]@($servicios) $dataGridServicios.Refresh() }}
Función para detener un servicio
function Detener-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "STOP_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para iniciar servicio
function Iniciar-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "START_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio iniciado exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al iniciar el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para iniciar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para matar proceso
function terminar-proceso { dataGridProcesos.SelectedRows[0].Cells["id"].Value if (procesoseleccionado) { command = "TERMINATE_PROCESS|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Proceso detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Procesos } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el proceso: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un proceso para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para iniciar servicio
function reiniciar-Servicios { dataGridServicios.SelectedRows[0].Cells["Name"].Value if (selectedService) { command = "RESTART_SERVICE|response = Send-RemoteCommand -remoteServer Global:puerto -command $command
if ($response.success) { [System.Windows.Forms.MessageBox]::Show("Servicio detenido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Refrescar-Servicios } else { [System.Windows.Forms.MessageBox]::Show("Error al detener el servicio: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor, selecciona un servicio para detener.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Eventos
btnRefrescarServicios.Add_Click({ global:excluirMicrosoft = btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" Refrescar-Servicios })
btnBuscarProcesos.Add_Click({ Refrescar-Procesos -filtro txtBusquedaProcesos.Text }) btnBuscarServicios.Add_Click({ Refrescar-Servicios -filtro txtBusquedaServicios.Text })
btnExcluirMicrosoft.Add_Click({ global:excluirMicrosoft = -not global:excluirMicrosoft) { btnExcluirMicrosoft.Text = "Mostrar todos los servicios" } else { btnExcluirMicrosoft.Text = "Excluir servicios de Microsoft" } Refrescar-Servicios })
#*************************************************************************************
Crear un control de lista para mostrar los archivos y carpetas
listBox.Size = New-Object System.Drawing.Size(750, 240) TabFiles.Controls.Add($listBox)
txtComando.Location = New-Object System.Drawing.Point(20, 320) txtComando.Font = New-Object System.Drawing.Font("Consolas", 10) txtComando)
txtSalida.Location = New-Object System.Drawing.Point(20, 350) txtSalida.Multiline = txtSalida.ScrollBars = "Vertical" #txtSalida.BackColor = [System.Drawing.Color]::Blue # Fondo azul txtSalida.ForeColor = [System.Drawing.Color]::White # Texto blanco txtSalida.Rtf = "{\rtf1\ansi\deff0{\fonttbl{\f0 Consolas;}}{\f0\fs20\sl240\slmult1}}" true txtSalida)
Función para ejecutar comandos PowerShell remotos
function Execute-RemoteCommand { param ( [string]command ) try { commandToSend = "EXECUTE_COMMAND|response = Send-RemoteCommand -remoteServer Global:puerto -command $commandToSend
if ($response.success) { $txtSalida.Clear() $txtSalida.AppendText(">> $command`r`n") $txtSalida.AppendText($response.output + "`r`n`r`n") } else { $txtSalida.AppendText("Error: $($response.message)`r`n`r`n") } } catch { $txtSalida.AppendText("Error de ejecución: $($_.Exception.Message)`r`n`r`n") }}
Evento del botón Enviar
#$btnEnviarComando.Add_Click({
if ($txtComando.Text.Trim()) {
Execute-RemoteCommand -command $txtComando.Text.Trim()
$txtComando.Clear()
}
#})
Evento para manejar la tecla Enter en el TextBox de comandos
txtComando.Add_KeyDown({ param(sender, e.KeyCode -eq [System.Windows.Forms.Keys]::Enter) { if (txtComando.Text.Trim()) { Execute-RemoteCommand -command txtComando.Text.Trim() txtComando.Clear() } e.SuppressKeyPress = $true } })
Crear botones para las diferentes acciones
#btnEnviarComando = New-Object System.Windows.Forms.Button #btnEnviarComando.Location = New-Object System.Drawing.Point(680, 320) #btnEnviarComando.Size = New-Object System.Drawing.Size(90, 23) #btnEnviarComando.Text = "Enviar" #btnEnviarComando)
buttonDownload.Text = "Descargar" buttonDownload.Location = New-Object System.Drawing.Point(10, 270) buttonDownload)
buttonDelete.Text = "Eliminar" buttonDelete.Location = New-Object System.Drawing.Point(120, 270) buttonDelete)
buttonCopy.Text = "Copiar" buttonCopy.Location = New-Object System.Drawing.Point(230, 270) buttonCopy)
buttonMove.Text = "Mover" buttonMove.Location = New-Object System.Drawing.Point(340, 270) buttonMove)
buttonUpload.Text = "Subir" buttonUpload.Location = New-Object System.Drawing.Point(450, 270) buttonUpload)
buttonSalir.Text = "Salir" buttonSalir.Location = New-Object System.Drawing.Point(560, 270) buttonSalir)
buttonSalir.Add_Click({ form.Hide() # Ocultar el formulario principal en lugar de cerrarlo
$serverSelectionForm.Show() # Mostrar el formulario de selección de servidor
})
buttonRDP.Text = "Escritorio Remoto" buttonRDP.Location = New-Object System.Drawing.Point(670, 270) buttonRDP)
$buttonRDP.Add_Click({
Start-Process "mstsc.exe" -ArgumentList "/v:$($global:selectedServer.IP) /f"})
#Controlar el cierre del formulario form.Add_FormClosing({ # Ocultar el formulario en lugar de cerrarlo form.Hide() # Oculta el formulario
$serverSelectionForm.Show() # Muestra el formulario de selección de servidor
# Cancelar el cierre del formulario principal $_.Cancel = $true # Esto cancela el cierre del formulario})
Funcion para subir archivos
buttonUpload.Add_Click({ openFileDialog = New-Object System.Windows.Forms.OpenFileDialog openFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { openFileDialog.FileName listBox.SelectedItem if (-not remoteFilePath = Join-Path -Path localPath) localPath) fileContent) remoteFilePath|response = Send-RemoteCommand -remoteServer Global:puerto -command response.success) { [System.Windows.Forms.MessageBox]::Show("Archivo subido exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Update-FileList -remoteServer Global:puerto -path remotePath } else { [System.Windows.Forms.MessageBox]::Show("Error al subir el archivo: ($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } })
Función para enviar comandos al servidor remoto
function Send-RemoteCommand { param ( [string]remotePort, [string]command ) try { client = New-Object System.Net.Sockets.TcpClient(remotePort) client.GetStream() stream) stream)
Write-Host "Enviando comando: $($command.Substring(0, [Math]::Min(100, $command.Length)))..." $writer.WriteLine($command) $writer.Flush() $response = $reader.ReadToEnd() Write-Host "Respuesta recibida: $response" $reader.Close() $writer.Close() $stream.Close() $client.Close() return $response | ConvertFrom-Json } catch { Write-Host "Error de conexión: $($_.Exception.Message)" -ForegroundColor Red [System.Windows.Forms.MessageBox]::Show("Error de conexión: $($_.Exception.Message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) return $null }}
Función para actualizar la lista de archivos
function Update-FileList { param ( [string]remotePort, [string]command = "LIST_FILES|response = Send-RemoteCommand -remoteServer remotePort -command response -and response.files) { $listBox.Items.Clear()
# Agregar '..' al inicio de la lista si no estamos en la raíz if ($path -ne [System.IO.Path]::GetPathRoot($path)) { $listBox.Items.Add('..') } foreach ($file in $response.files) { $listBox.Items.Add($file) } } else { [System.Windows.Forms.MessageBox]::Show("No se pudieron obtener los archivos.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }}
Función para descargar un archivo
buttonDownload.Add_Click({ selectedFile = selectedFile) { saveFileDialog.FileName = [System.IO.Path]::GetFileName($selectedFile)
if ($saveFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $localPath = $saveFileDialog.FileName $command = "DOWNLOAD_FILE|$selectedFile" $response = Send-RemoteCommand -remoteServer $global:selectedServer.IP -remotePort $Global:puerto -command $command if ($response.success) { $fileContentBase64 = $response.fileContent $fileContent = [System.Convert]::FromBase64String($fileContentBase64) [System.IO.File]::WriteAllBytes($localPath, $fileContent) [System.Windows.Forms.MessageBox]::Show("Archivo descargado exitosamente.", "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } else { [System.Windows.Forms.MessageBox]::Show("Error al descargar el archivo: $($response.message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para descargar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) }})
Función para eliminar un archivo
buttonDelete.Add_Click({ selectedFile = selectedFile) { selectedFile" global:selectedServer.IP -remotePort command if (response.success) { [System.Windows.Forms.MessageBox]::Show(response.message, "Éxito", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) Update-FileList -remoteServer Global:puerto -path (Split-Path -Parent selectedFile) } else { [System.Windows.Forms.MessageBox]::Show(response.message, "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para eliminar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Función para copiar un archivo
buttonCopy.Add_Click({ selectedFile = selectedFile) { folderBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { folderBrowser.SelectedPath -ChildPath (Split-Path -Leaf command = "COPY_FILE|destination" global:selectedServer.IP -remotePort command [System.Windows.Forms.MessageBox]::Show($response.message, "Resultado", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para copiar.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Función para mover un archivo
buttonMove.Add_Click({ selectedFile = selectedFile) { folderBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { folderBrowser.SelectedPath -ChildPath (Split-Path -Leaf command = "MOVE_FILE|destination" global:selectedServer.IP -remotePort command [System.Windows.Forms.MessageBox]::Show(global:selectedServer.IP -remotePort selectedFile) } } else { [System.Windows.Forms.MessageBox]::Show("Por favor selecciona un archivo para mover.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })
Evento para manejar el doble clic en el ListBox
listBox.Add_DoubleClick({ selectedItem = selectedItem) { if (selectedItem -eq '..') { # Subir un nivel de directorio currentPath = listBox.Tag # Asumimos que guardamos la ruta actual en la propiedad Tag del ListBox parentPath = [System.IO.Path]::GetDirectoryName(global:selectedServer.IP -remotePort parentPath parentPath } elseif (Test-Path selectedItem -PathType Container) { # Si es un directorio, actualizar la lista de archivos Update-FileList -remoteServer global:selectedServer.IP -remotePort selectedItem selectedItem } else { # Si es un archivo, mostrar un mensaje [System.Windows.Forms.MessageBox]::Show("Seleccionaste el archivo: $selectedItem", "Información", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } } })
$serverSelectionForm.ShowDialog()
y el aente:
Importar los ensamblados necesarios para System.Net
Add-Type -AssemblyName System.Net
endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, listener = New-Object System.Net.Sockets.TcpListener listener.Start()
Write-Host "Escuchando en el puerto $port..."
while (true) { client = stream = reader = New-Object System.IO.StreamReader(writer = New-Object System.IO.StreamWriter($stream)
$command = $reader.ReadLine() Write-Host "Comando recibido: $($command.Substring(0, [Math]::Min(100, $command.Length)))..." $parts = $command -split '\|' $action = $parts[0] switch ($action) { "EXECUTE_COMMAND" { $commandToExecute = $parts[1] try { $output = Invoke-Expression $commandToExecute | Out-String $response = @{ success = $true output = $output } | ConvertTo-Json } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "UPLOAD_FILE" { $remoteFilePath = $parts[1] $fileContentBase64 = $parts[2] try { $fileContent = [System.Convert]::FromBase64String($fileContentBase64) [System.IO.File]::WriteAllBytes($remoteFilePath, $fileContent) $response = @{ success = $true message = "Archivo subido exitosamente." } | ConvertTo-Json -Compress } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) $writer.Flush() } "LIST_FILES" { $directoryPath = $parts[1] try { if (Test-Path $directoryPath) { $files = Get-ChildItem -Path $directoryPath | Select-Object -ExpandProperty FullName $response = @{ success = $true files = @($files) currentPath = $directoryPath } | ConvertTo-Json -Compress } else { $response = @{ success = $false message = 'Directorio no encontrado' } | ConvertTo-Json -Compress } } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) $writer.Flush() } "DELETE_FILE" { $filePath = $parts[1] try { Remove-Item -Path $filePath -Force $response = @{success=$true; message='Archivo eliminado.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "COPY_FILE" { $sourcePath = $parts[1] $destinationPath = $parts[2] try { Copy-Item -Path $sourcePath -Destination $destinationPath $response = @{success=$true; message='Archivo copiado.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "MOVE_FILE" { $sourcePath = $parts[1] $destinationPath = $parts[2] try { Move-Item -Path $sourcePath -Destination $destinationPath $response = @{success=$true; message='Archivo movido.'} | ConvertTo-Json -Compress } catch { $response = @{success=$false; message=$_.Exception.Message} | ConvertTo-Json -Compress } Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } "DOWNLOAD_FILE" { $remoteFilePath = $parts[1] try { if (Test-Path $remoteFilePath) { $fileContent = [System.IO.File]::ReadAllBytes($remoteFilePath) $fileContentBase64 = [System.Convert]::ToBase64String($fileContent) $response = @{ success = $true fileContent = $fileContentBase64 fileName = [System.IO.Path]::GetFileName($remoteFilePath) } | ConvertTo-Json -Compress } else { $response = @{ success = $false message = "El archivo no existe." } | ConvertTo-Json -Compress } $writer.WriteLine($response) $writer.Flush() } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json -Compress $writer.WriteLine($response) $writer.Flush() } }"GET_PROCESSES" { $filtro = $parts[1] $procesos = Get-Process | ForEach-Object { [PSCustomObject]@{ Id = $_.Id Name = $_.Name CPU = $_.CPU "Memory (MB)" = [math]::Round($_.WorkingSet64 / 1MB, 2) } } | Sort-Object Name if ($filtro) { $procesos = $procesos | Where-Object { $_.Name -like "*$filtro*" -or $_.Id -like "*$filtro*" } } $writer.WriteLine(($procesos | ConvertTo-Json)) } "GET_SERVICES" { $filtro = $parts[1] $excluirMicrosoft = [System.Convert]::ToBoolean($parts[2]) $servicios = Get-CimInstance -ClassName Win32_Service | Select-Object Name, DisplayName, State, StartMode, @{Name="CompanyName";Expression={ $_.PathName | ForEach-Object { (Get-ItemProperty $_).VersionInfo.CompanyName }}} | Sort-Object DisplayName if ($filtro) { $servicios = $servicios | Where-Object { $_.Name -like "*$filtro*" -or $_.DisplayName -like "*$filtro*" } } if ($excluirMicrosoft) { $servicios = $servicios | Where-Object { $_.CompanyName -notlike "*Microsoft*" } } $writer.WriteLine(($servicios | ConvertTo-Json)) } "TERMINATE_PROCESS" { $processId = $parts[1] try { Stop-Process -Id $processId -Force $response = @{ success = $true message = "Proceso terminado" } | ConvertTo-Json } catch { $response = @{ success = $false message = $_.Exception.Message } | ConvertTo-Json } # Enviar siempre la respuesta en formato JSON $writer.WriteLine($response) $writer.Flush() } "START_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop if ($service.Status -eq 'Stopped') { Start-Service -Name $serviceName -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' iniciado exitosamente." } | ConvertTo-Json } else { $response = @{ success = $false message = "El servicio '$serviceName' está en ejecución." } | ConvertTo-Json } } catch { $response = @{ success = $false message = "Error al iniciar el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "STOP_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop if ($service.Status -eq 'Running') { Stop-Service -Name $serviceName -Force -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' detenido exitosamente." } | ConvertTo-Json } else { $response = @{ success = $false message = "El servicio '$serviceName' no está en ejecución." } | ConvertTo-Json } } catch { $response = @{ success = $false message = "Error al detener el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } "RESTART_SERVICE" { $serviceName = $parts[1] try { $service = Get-Service -Name $serviceName -ErrorAction Stop Restart-Service -Name $serviceName -Force -ErrorAction Stop $response = @{ success = $true message = "Servicio '$serviceName' detenido exitosamente." } | ConvertTo-Json } catch { $response = @{ success = $false message = "Error al detener el servicio '$serviceName': $($_.Exception.Message)" } | ConvertTo-Json } $writer.WriteLine($response) $writer.Flush() } default { $response = @{success=$false; message='Comando no reconocido'} | ConvertTo-Json -Compress Write-Host "Enviando respuesta: $response" $writer.WriteLine($response) } } $writer.Flush() $client.Close()}
$listener.Stop()
Quiero que el agente pueda registrarse en el archivo que lee el administrador remoto (servers.txt) donde colocan esta información: 10/07/2024 15:16:35 - 192.168.64.200 - AD
- Assistant
Para que el agente pueda registrarse automáticamente en el archivo
servers.txtque utiliza el script del administrador remoto, puedes modificar el script del agente para que envíe su información al archivo después de iniciar el programa. Aquí tienes cómo hacerlo:Modificaciones en el Script del Agente
-
Función para Registrar el Agente:
Implementa una función en el script del agente que escriba la información necesaria en
servers.txt.
function Register-Agent { param ( [string]$serverFilePath, [string]$description = "Descripción del servidor" ) $currentDateTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $agentIP = (Test-Connection -ComputerName (hostname) -Count 1).Address.IPAddressToString if (-not (Test-Path $serverFilePath)) { New-Item -Path $serverFilePath -ItemType File -Force } $entry = "$currentDateTime - $agentIP - $description" $entryExists = Get-Content $serverFilePath | Select-String -Pattern "$agentIP" if (-not $entryExists) { Add-Content -Path $serverFilePath -Value $entry Write-Host "Agente registrado: $entry" } else { Write-Host "Agente ya registrado." } }-
Ejecuta la Función de Registro:
Ejecuta la función de registro en una ubicación apropiada dentro del script, posiblemente justo después de iniciar el escucha en el puerto:
$port = 4430 $endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, $port) $listener = New-Object System.Net.Sockets.TcpListener $endpoint $listener.Start() # Registrar el agente Register-Agent -serverFilePath "C:\ruta\a\servers.txt" -description "AD" Write-Host "Escuchando en el puerto $port..."Asegúrate de reemplazar
"C:\ruta\a\servers.txt"con la ruta correcta al archivoservers.txt.Consideraciones
- Ruta de Archivo: Verifica que la ruta del archivo
servers.txtsea accesible y que el usuario que ejecuta el script del agente tenga permisos suficientes para escribir en este archivo. - Formato Consistente: El formato de la fecha, hora e IP debe coincidir con el patrón esperado por el script de administración (
(\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}) - (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - (.+)). - Duplicados: La lógica revisa si la IP del agente ya está en el archivo
servers.txtantes de añadir una nueva entrada. - Seguridad y Acceso: Asegúrate de que el acceso a
servers.txtestá controlado adecuadamente para evitar manipulación no autorizada.
Estos cambios permitirán que el agente se registre automáticamente en el archivo
servers.txt, haciendo que esta información esté disponible para el administrador remoto. -