Image

Image

Search This Blog

Monday, July 15, 2024

ESP32-CAM serve video to multiple http clients

 // Multicam v.2.19

// ESP32 has two cores, APPlication and PROcess

#define APP_CPU 1
#define PRO_CPU 0

#include "src/OV2640.h"
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiClient.h>
// we should disable bt
//#include <esp_bt.h>
#include <esp_wifi.h>
#include <esp_sleep.h>
#include <driver/rtc_io.h>
//disable brownout problems
#include "soc/soc.h"           
#include "soc/rtc_cntl_reg.h"

#define CAMERA_MODEL_AI_THINKER
//those are the GPIO pins for AI_THINKER - find yours if you have a different SOC
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
// wifi, because I'm too lazy to put it in a different file
#define SSID1 "my_WiFi"
#define PWD1 "myp455w0rd"

//init camera
OV2640 cam;

//init webserver
WebServer server(80);


// ===== rtos task handles =====
// Streaming is implemented with 3 tasks:
// handle client connections to the webserver
TaskHandle_t tMjpeg;
// handle getting picture frames from the camera and storing them locally
TaskHandle_t tCam;
// actually streaming frames to all connected clients
TaskHandle_t tStream;

// frameSync semaphore is used to prevent streaming buffer while is replaced with the next frame
SemaphoreHandle_t frameSync = NULL;

// Queue stores currently connected clients to whom we are streaming
QueueHandle_t streamingClients;

// We will try to achieve 15 FPS frame rate - for surveilllance, it is ok-ish...
const int FPS = 15;

// We will handle web client requests every 100 ms (10 Hz) - web can wait a bit
const int WSINTERVAL = 100;


// ======== Server Connection Handler Task ==========
void mjpegCB(void* pvParameters) {
  TickType_t xLastWakeTime;
  const TickType_t xFrequency = pdMS_TO_TICKS(WSINTERVAL);

  // Creating frame synchronization semaphore and initializing it
  frameSync = xSemaphoreCreateBinary();
  xSemaphoreGive(frameSync);

  // Creating a queue to track all connected clients
  streamingClients = xQueueCreate(10, sizeof(WiFiClient*));

  //=== Setup section  ===

  //  Creating RTOS task for grabbing frames from the camera
  xTaskCreatePinnedToCore(
    camCB,     // callback
    "cam",     // name
    4096,      // stacj size
    NULL,      // parameters
    2,         // priority
    &tCam,     // RTOS task handle
    APP_CPU);  // core

  //  Creating task to push the stream to all connected clients
  xTaskCreatePinnedToCore(
    streamCB,
    "strmCB",
    4 * 1024,
    NULL,  //(void*) handler,
    2,
    &tStream,
    APP_CPU);

  //  Registering webserver handling routines
  server.on("/mjpeg", HTTP_GET, handleJPGSstream);
  server.on("/jpeg", HTTP_GET, handleJPG);
  server.onNotFound(handleNotFound);

  //  Starting webserver
  server.begin();

  //=== loop() section  ====
  xLastWakeTime = xTaskGetTickCount();
  for (;;) {
    server.handleClient();

   // After every server client handling request, we let other tasks run and then pause
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);
  }
}


// Commonly used variables:
volatile size_t camSize;  // size of the current frame, byte
volatile char* camBuf;    // pointer to the current frame


// ==== RTOS task to grab frames from the camera ====
void camCB(void* pvParameters) {

  TickType_t xLastWakeTime;

  //  A running interval associated with currently desired frame rate
  const TickType_t xFrequency = pdMS_TO_TICKS(1000 / FPS);

  // Mutex for the critical section of swithing the active frames around
  portMUX_TYPE xSemaphore = portMUX_INITIALIZER_UNLOCKED;

  //  Pointers to the 2 frames, their respective sizes and index of the current frame
  char* fbs[2] = { NULL, NULL };
  size_t fSize[2] = { 0, 0 };
  int ifb = 0;

  //=== loop() section  ===
  xLastWakeTime = xTaskGetTickCount();

  for (;;) {

    //  Grab a frame from the camera and query its size
    cam.run();
    size_t s = cam.getSize();

    //  If frame size is more that we have previously allocated - request  125% of the current frame space
    if (s > fSize[ifb]) {
      fSize[ifb] = s * 4 / 3;
      fbs[ifb] = allocateMemory(fbs[ifb], fSize[ifb]);
    }

    //  Copy current frame into local buffer
    char* b = (char*)cam.getfb();
    memcpy(fbs[ifb], b, s);

    //  Let other tasks run and wait until the end of the current frame rate interval (if any time left)
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);

    //  Only switch frames around if no frame is currently being streamed to a client
    //  Wait on a semaphore until client operation completes
    xSemaphoreTake(frameSync, portMAX_DELAY);

    //  Do not allow interrupts while switching the current frame
    portENTER_CRITICAL(&xSemaphore);
    camBuf = fbs[ifb];
    camSize = s;
    ifb++;
    ifb &= 1;  // this should produce a 1, 0, 1, 0, 1 ... sequence
    portEXIT_CRITICAL(&xSemaphore);

    //  Let anyone waiting for a frame know that the frame is ready
    xSemaphoreGive(frameSync);

    //  Technically only needed once: let the streaming task know that we have at least one frame
    //  and it could start sending frames to the clients, if any
    xTaskNotifyGive(tStream);

    //  Immediately let other (streaming) tasks run
    taskYIELD();

    //  If streaming task has suspended itself (no active clients to stream to) there is no need to grab frames from the camera. We can save some power by suspending the tasks
    if (eTaskGetState(tStream) == eSuspended) {
      vTaskSuspend(NULL);  //NULL means "suspend yourself"
    }
  }
}


// ==== Memory allocator uses of PSRAM if present ====
char* allocateMemory(char* aPtr, size_t aSize) {

  //  Since current buffer is too small, free it
  if (aPtr != NULL) free(aPtr);

  size_t freeHeap = ESP.getFreeHeap();
  char* ptr = NULL;

  // If memory requested is more than 2/3 of the currently free heap, try PSRAM immediately
  if (aSize > freeHeap * 2 / 3) {
    if (psramFound() && ESP.getFreePsram() > aSize) {
      ptr = (char*)ps_malloc(aSize);
    }
  } else {
    //  Enough free heap - let's try allocating fast RAM as a buffer
    ptr = (char*)malloc(aSize);

    //  If allocation on the heap failed, let's give PSRAM one more chance:
    if (ptr == NULL && psramFound() && ESP.getFreePsram() > aSize) {
      ptr = (char*)ps_malloc(aSize);
    }
  }

  // Well, if the memory pointer is NULL, we were not able to allocate any memory, and that is the end. RESTART.
  if (ptr == NULL) {
    ESP.restart();
  }
  return ptr;
}


// ==== STREAMING ======
const char HEADER[] = "HTTP/1.1 200 OK\r\n"
                      "Access-Control-Allow-Origin: *\r\n"
                      "Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n";
const char BOUNDARY[] = "\r\n--123456789000000000000987654321\r\n";
const char CTNTTYPE[] = "Content-Type: image/jpeg\r\nContent-Length: ";
const int hdrLen = strlen(HEADER);
const int bdrLen = strlen(BOUNDARY);
const int cntLen = strlen(CTNTTYPE);


// ==== Handle connection request from clients ======
void handleJPGSstream(void) {
  //  Can only acommodate 10 clients. The limit is a default for WiFi connections
  if (!uxQueueSpacesAvailable(streamingClients)) return;


  //  Create a new WiFi Client object to keep track of this one
  WiFiClient* client = new WiFiClient();
  *client = server.client();

  //  Immediately send this client a header
  client->write(HEADER, hdrLen);
  client->write(BOUNDARY, bdrLen);

  // Push the client to the streaming queue
  xQueueSend(streamingClients, (void*)&client, 0);

  // Wake up streaming tasks if they were previously suspended:
  if (eTaskGetState(tCam) == eSuspended) vTaskResume(tCam);
  if (eTaskGetState(tStream) == eSuspended) vTaskResume(tStream);
}


// ==== Actually stream content to all connected clients ====
void streamCB(void* pvParameters) {
  char buf[16];
  TickType_t xLastWakeTime;
  TickType_t xFrequency;

  //  Wait until the first frame is captured - only after we have something to send
  ulTaskNotifyTake(pdTRUE,         /* Clear the notification value before exiting. */
                   portMAX_DELAY); /* Block indefinitely. */

  xLastWakeTime = xTaskGetTickCount();
  for (;;) {
    // Default assumption: we are running according to the FPS
    xFrequency = pdMS_TO_TICKS(1000 / FPS);

    //  Only send anything if there is someone watching
    UBaseType_t activeClients = uxQueueMessagesWaiting(streamingClients);
    if (activeClients) {
      // Adjust the period to the number of connected clients
      xFrequency /= activeClients;

      //  Since we are sending the same frame to everyone,
      //  pop a client from the the front of the queue
      WiFiClient* client;
      xQueueReceive(streamingClients, (void*)&client, 0);

      //  Check if this client is still connected.

      if (!client->connected()) {
        //  delete this client reference if it has disconnected
        //  and don't put it back on the queue anymore.
        delete client;
      } else {

        //  OK, this is an actively connected client.
        //  Let's grab a semaphore to prevent frame changes while we are serving the current
        xSemaphoreTake(frameSync, portMAX_DELAY);

        client->write(CTNTTYPE, cntLen);
        sprintf(buf, "%d\r\n\r\n", camSize);
        client->write(buf, strlen(buf));
        client->write((char*)camBuf, (size_t)camSize);
        client->write(BOUNDARY, bdrLen);

        // Since this client is still connected, push it to the end
        // of the queue for further processing
        xQueueSend(streamingClients, (void*)&client, 0);

        //  The frame has been served. Release the semaphore and let other tasks run.
        //  If there is a frame switch ready, it will happen now in between frames
        xSemaphoreGive(frameSync);
        taskYIELD();
      }
    } else {
      //  Since there are no connected clients, there is no reason to waste power running
      vTaskSuspend(NULL);
    }
    //  Let other tasks run after serving every client
    taskYIELD();
    vTaskDelayUntil(&xLastWakeTime, xFrequency);
  }
}


const char JHEADER[] = "HTTP/1.1 200 OK\r\n"
                       "Content-disposition: inline; filename=capture.jpg\r\n"
                       "Content-type: image/jpeg\r\n\r\n";
const int jhdLen = strlen(JHEADER);


// ==== Serve up one JPEG frame =========
void handleJPG(void) {
  WiFiClient client = server.client();

  if (!client.connected()) return;
  cam.run();
  client.write(JHEADER, jhdLen);
  client.write((char*)cam.getfb(), cam.getSize());
}


// ==== Handle invalid URL requests =====
void handleNotFound() {
  String message = "This camera runs fine, you are asking the wrong question!\n

you should only ask for /mjpeg or /jpeg here\n\n";
  message += "URL: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  server.send(200, "text / plain", message);
}


// we're at the classic setup function


void setup() {
  //disable brownout detector
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);  

  // Configure the camera
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  // Frame parameters: UXGA is ok if we only want a decent framerate of 15fps
    config.frame_size = FRAMESIZE_UXGA;
  //  config.frame_size = FRAMESIZE_SVGA;
  //  config.frame_size = FRAMESIZE_VGA;
  //  config.frame_size = FRAMESIZE_QVGA;
  config.jpeg_quality = 12;
  config.fb_count = 2;

  if (cam.init(config) != ESP_OK) {
    delay(10000);
    ESP.restart();
  }


  //  Configure and connect to WiFi
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID1, PWD1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  // Start main streaming RTOS task
  xTaskCreatePinnedToCore(
    mjpegCB,
    "mjpeg",
    4 * 1024,
    NULL,
    2,
    &tMjpeg,
    APP_CPU);
}


// variables for wifi reconnect
unsigned long previousMillis = 0;
unsigned long interval = 30000;

void loop() {
  vTaskDelay(1000);
  //Check Wifi status
  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting every interval mseconds
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >= interval)) {
    WiFi.disconnect();
    vTaskDelay(1000);
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
}

Saturday, March 23, 2024

Create a task that removes "shutdown task if running longer than" from other tasks

$batchfileToAdd = @'
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set srvlist=UDP_SERVER_CHAN0,UDP_CANBUS_SERVER,UDP_UART_SERVER_CHAN0
for %%i in (%srvlist%) do (
powershell "$task = get-ScheduledTask -taskname %%i ; $Task.Settings.ExecutionTimeLimit = 'PT0H' ; set-ScheduledTask $task"
)
ENDLOCAL
exit /B
'@
Add-Content "C:\CAB\chgtskshtdn.bat" $batchfileToAdd

$xmlfileToAdd = @'
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-02-20T09:21:14.0904858</Date>
    <Author>myself</Author>
    <Description>Uncheck "shutdown task is running longer than" for the tasks UDP_SERVER_CHAN0,UDP_CANBUS_SERVER,UDP_UART_SERVER_CHAN0</Description>
    <URI>\Keep Tasks running</URI>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT60M</Interval>
        <Duration>P1D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2024-02-20T09:15:39</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>false</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\CAB\chgtskshtdn.bat</Command>
    </Exec>
  </Actions>
</Task>
'@
Add-Content "C:\CAB\KeepTasksRunning.xml" $xmlfileToAdd

$complstfileToAdd = @'

cmp1
cmp2
cmp3
cmp4

'@
Add-Content "C:\tmp\complst.txt" $complstfileToAdd

$cred = Get-Credential;
foreach($line in Get-Content C:\tmp\complst.txt) {
Write-Host "Running on $line"
$comp = New-PSSession -Credential $cred $line
Write-Host "Session to $comp established"
Copy-Item -ToSession $comp C:\CAB\chgtskshtdn.bat -Destination C:\CAB\chgtskshtdn.bat
Write-Host "bat file copied"
Copy-Item -ToSession $comp "C:\CAB\KeepTasksRunning.xml" -Destination "C:\CAB\KeepTasksRunning.xml"
Write-Host "xml file copied"
Invoke-Command -ComputerName $line -Credential $cred { $Task = Get-Content "C:\CAB\KeepTasksRunning.xml" -raw ; Register-ScheduledTask -Xml $Task -TaskName 'Keep Tasks Running' -User adminuser -Password "som3p455wrd" -Force }
Write-Host "task created"
}

Remove-Item "C:\tmp\complst.txt"
Remove-Item "C:\CAB\KeepTasksRunning.xml"
Remove-Item "C:\CAB\chgtskshtdn.bat"

exit

Saturday, February 03, 2024

backup cmd

:: *** SYNC DATA - Copy one way v3.6 ***
@echo off
title BACKUP in progress
SETLOCAL ENABLEDELAYEDEXPANSION
if not defined is_min set is_min=1 && start "" /min "%~dpnx0" %* && goto end
echo.
if not "%~1" == "" (set source=%~1)
if not "%~2" == "" (set destination=%~2)
if not "%~3" == "" (set rcptto=%~3) else (echo USAGE: %~0 "source" "destination" "mail@dom.tld; mail2@dom.tld" "mail.server(optional)" && goto end)
if not "%~4" == "" (set smtpsrv=%~4) else (set smtpsrv="smtp.dom.tld")
set mailfrom="%COMPUTERNAME%@%USERDNSDOMAIN%"
set emailer=%temp%\email_%random%.vbs
set logfile=%temp%\copy_report_%random%.log

:: *** Copy ***
echo > %logfile% %date% %time% *** STARTING COPY ***

robocopy %source% %destination% /E /FP /TS /XO /FFT /COPY:D /R:3 /W:5 /IPG:25 /X /V /NP /LOG:%logfile%
set erlvl=%ERRORLEVEL%
if %erlvl% EQU 16 echo >> %logfile% %date% %time% *** !!! FATAL ERROR - NOTHING COPIED !!! *** && set err=yes
if %erlvl% EQU 15 echo >> %logfile% %date% %time% * FAIL + MISMATCHES + XTRA + OKCOPY * && set err=yes
if %erlvl% EQU 14 echo >> %logfile% %date% %time% * FAIL + MISMATCHES + XTRA * && set err=yes
if %erlvl% EQU 13 echo >> %logfile% %date% %time% * FAIL + MISMATCHES + OKCOPY * && set err=yes
if %erlvl% EQU 12 echo >> %logfile% %date% %time% * FAIL + MISMATCHES * && set err=yes
if %erlvl% EQU 11 echo >> %logfile% %date% %time% * FAIL + XTRA + OKCOPY * && set err=yes
if %erlvl% EQU 10 echo >> %logfile% %date% %time% * FAIL + XTRA * && set err=yes
if %erlvl% EQU 9 echo >> %logfile% %date% %time% * FAIL + OKCOPY * && set err=yes
if %erlvl% EQU 8 echo >> %logfile% %date% %time% * FAIL * && set err=yes
if %erlvl% EQU 7 echo >> %logfile% %date% %time% * MISMATCHES + OKCOPY + XTRA *
if %erlvl% EQU 6 echo >> %logfile% %date% %time% * MISMATCHES + XTRA *
if %erlvl% EQU 5 echo >> %logfile% %date% %time% * MISMATCHES + OKCOPY *
if %erlvl% EQU 4 echo >> %logfile% %date% %time% * MISMATCHES *
if %erlvl% EQU 3 echo >> %logfile% %date% %time% * OKCOPY + XTRA *
if %erlvl% EQU 2 echo >> %logfile% %date% %time% * XTRA *
if %erlvl% EQU 1 echo >> %logfile% %date% %time% * OKCOPY *
if %erlvl% EQU 0 echo >> %logfile% %date% %time% * NO CHANGES / NOCOPY *

:: *** Delete files & folder older than 365 days ****
::forfiles /p %destination% /s /m *.* /c "cmd /c del @path" /d -365
::for /f "tokens=*" %d in ('dir %destination% /ad/b/s ^| sort /R') do rd "%d"
::echo Files older than 365 days deleted

:: *** Send Email ***
echo Set objNet = CreateObject("WScript.Network") >%emailer%
echo strHostName = objNet.ComputerName >>%emailer%
echo Set email = CreateObject("CDO.Message") >>%emailer%
if "%err%"=="" echo email.Subject = strHostName ^& " - Backup Report" >>%emailer%
if "%err%"=="yes" echo email.Subject = strHostName ^& " - FAILED Backup Report" >>%emailer%
echo email.From = %mailfrom% >>%emailer%
echo email.To = "%rcptto%" >>%emailer%
if "%err%"=="" echo email.TextBody = "Copy completed as %username% on " ^& strHostName ^& ".  Please check the attached report" >>%emailer%
if "%err%"=="yes" echo email.TextBody = "Copy as %username% has FAILED on " ^& strHostName ^& ".  Please check the attached report" >>%emailer%
echo email.AddAttachment "%logfile%" >>%emailer%
echo email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername")="UserName" >>%emailer%
echo email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword")="PassWord" >>%emailer%
echo email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2 >>%emailer%
echo email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")=%smtpsrv% >>%emailer%
echo email.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 >>%emailer%
echo email.Configuration.Fields.Update >>%emailer%
echo email.Send >>%emailer%
echo set email = Nothing >>%emailer%

start %emailer%
timeout 1 >nul /nobreak && del /q %emailer%
timeout 1 >nul /nobreak && del /q %logfile%

:end
ENDLOCAL
title
exit /B
 

Saturday, January 06, 2024

Powershell backup

 #Backup folder
$dateStr = (Get-Date -Format "yyy-MM-dd-HH-mm")
$Source = "C:\source"
$Staging = "U:\BKPTemp"
$Destination = "U:\Backup\destination_$dateStr.zip"
Get-ChildItem "U:\Backup\" -Recurse -File | Where CreationTime -lt  (Get-Date).AddDays(-90)  | Remove-Item -Force
Add-Type -AssemblyName System.IO.Compression.Filesystem
Copy-Item -Path $Source -Destination $Staging -Recurse
[System.IO.Compression.ZipFile]::CreateFromDirectory($Staging, $Destination)
Remove-Item -Path $Staging -Force -Recurse
exit

Monday, December 04, 2023

List Members of AD groups

To get the members of a group, we need to login into a server with an admin account.

The admin account is member of another domain in the same forest, but the groups are in a different domain. In order to perform the inquiry, an AD controller server for the target domain must be specified.

Get-ADGroup -Filter { Name -like "*the searched_group*" } -Server DC.TARGET.TLD | Get-ADGroupMember -Server DC.TARGET.TLD | Select-Object name, objectClass | Out-GridView

Thursday, November 02, 2023

MULTIPLE SAMBA INSTANCES

 

In order to allow clients with different encryption levels access to the same network share, multiple instances of SAMBA must be configured on the same machine. We are benefiting from a feature of SAMBA called “bind_interface” that allow a certain instance to only run on a specific network interface. If only one interface is available, “Virtual interfaces” might be defined.


Optional step – Define virtual interfaces:

cd /etc/sysconfig/network-scripts

vi ifcfg-eth0:1

DEVICE=eth0:1

BOOTPROTO=static

IPADDR=192.168.127.1

NETMASK=255.255.0.0

NETWORK=192.168.0.0

BROADCAST=192.168.100.255

ONBOOT=yes

TYPE=Ethernet


vi ifcfg-eth0:2

DEVICE=eth0:2

BOOTPROTO=static

IPADDR=192.168.127.2

NETMASK=255.255.0.0

NETWORK=192.168.0.0

BROADCAST=192.168.100.255

ONBOOT=yes

TYPE=Ethernet


vi /etc/hosts

192.168.127.1 SMB1.domain.tld SMB1

192.168.127.2 SMB2.domain.tld SMB2



Step 1 – Prepare directories for instances:

mkdir -p /var/run/samba/SMB1 /var/run/samba/SMB2

mkdir -p /var/cache/samba/SMB1 /var/cache/samba/SMB2

mkdir -p /var/log/samba/SMB1 /var/log/samba/SMB2



Step 2 – Modify logrotate to care for the new log directories:

vi /etc/logrotate.d/samba

/var/log/samba/SMB*/log.* {

[…]

/bin/kill -HUP \`cat /var/run/samba/SMB1/smbd.pid /var/run/samba/SMB1/nmbd.pid /var/run/samba/SMB1/winbindd.pid 2> /dev/null\` 2> /dev/null || true

/bin/kill -HUP \`cat /var/run/samba/SMB2/smbd.pid /var/run/samba/SMB2/nmbd.pid /var/run/samba/SMB2/winbindd.pid 2> /dev/null\` 2> /dev/null || true

}


Step 3 – Create two configuration files:


vi /etc/samba/samba.conf.SMB1

[global]

workgroup = WORKGROUP

client min protocol = NT1

server min protocol = NT1

client ipc min protocol = NT1

client ipc signing = desired

client plaintext auth = yes

ntlm auth = ntlmv1-permitted

null passwords = yes

netbios name = SMB1

pid directory = /var/run/samba/SMB1

lock directory = /var/cache/samba/SMB1

private dir = /var/cache/samba/SMB1

server role = standalone

security = user

passdb backend = tdbsam

guest account = nobody

map to guest = Bad User

bind interfaces only = yes

interfaces = lo;eth0:1

log file = /var/log/samba/SMB1/log.%m

logging = file

log level = 2

load printers = no

printing = bsd

printcap name = /dev/null

disable spoolss = yes

[test]

Comment = Test Share

path = /tmp/test

browsable = yes

read only = no

guest ok = yes


vi /etc/samba/samba.conf.SMB2

[global]

workgroup = WORKGROUP

null passwords = yes

netbios name = SMB2

pid directory = /var/run/samba/SMB2

lock directory = /var/cache/samba/SMB2

private dir = /var/cache/samba/SMB2

server role = standalone

security = user

passdb backend = tdbsam

bind interfaces only = yes

interfaces = eth0:2

log file = /var/log/samba/SMB2/log.%m

logging = file

log level = 2

load printers = no

printing = bsd

printcap name = /dev/null

disable spoolss = yes

[test]

Comment = Test Share

path = /tmp/test

browsable = yes

read only = no

guest ok = yes


Step 4 – Edit/create sysconfig configuration files:


vi /etc/sysconfig/samba.SMB1

SMBDOPTIONS="-D -s /etc/samba/smb.conf.SMB1 -l /var/log/samba/SMB1"

NMBDOPTIONS="-D -s /etc/samba/smb.conf.SMB1 -l /var/log/samba/SMB1"


vi /etc/sysconfig/samba.SMB2

SMBDOPTIONS="-D -s /etc/samba/smb.conf.SMB2 -l /var/log/samba/SMB2"

NMBDOPTIONS="-D -s /etc/samba/smb.conf.SMB2 -l /var/log/samba/SMB2"


Step 4 – Edit/create systemctl startup files:


vi /usr/lib/systemd/system/smb1.service

[Unit]

Description=Samba SMB1 Daemon

Documentation=man:smbd(8) man:samba(7) man:smb.conf(5)

Wants=network-online.target

After=network.target network-online.target nmb1.service winbind.service

[Service]

Type=notify

PIDFile=/var/run/SMB1/smbd.pid

LimitNOFILE=16384

EnvironmentFile=-/etc/sysconfig/samba.SMB1

ExecStart=/usr/sbin/smbd --foreground --no-process-group $SMBDOPTIONS

ExecReload=/bin/kill -HUP $MAINPID

LimitCORE=infinity

Environment=KRB5CCNAME=FILE:/var/run/samba/SMB1/krb5cc_samba

[Install]

WantedBy=multi-user.target


vi /usr/lib/systemd/system/smb2.service

[Unit]

Description=Samba SMB2 Daemon

Documentation=man:smbd(8) man:samba(7) man:smb.conf(5)

Wants=network-online.target

After=network.target network-online.target nmb2.service winbind.service

[Service]

Type=notify

PIDFile=/var/run/SMB2/smbd.pid

LimitNOFILE=16384

EnvironmentFile=-/etc/sysconfig/samba.SMB2

ExecStart=/usr/sbin/smbd --foreground --no-process-group $SMBDOPTIONS

ExecReload=/bin/kill -HUP $MAINPID

LimitCORE=infinity

Environment=KRB5CCNAME=FILE:/var/run/samba/SMB2/krb5cc_samba

[Install]

WantedBy=multi-user.target


vi /usr/lib/systemd/system/nmb1.service

[Unit]

Description=Samba NMB1 Daemon

Documentation=man:nmbd(8) man:samba(7) man:smb.conf(5)

Wants=network-online.target

After=network.target network-online.target

[Service]

Type=notify

PIDFile=/var/run/SMB1/nmbd.pid

EnvironmentFile=-/etc/sysconfig/samba.SMB1

ExecStart=/usr/sbin/nmbd --foreground --no-process-group $NMBDOPTIONS

ExecReload=/bin/kill -HUP $MAINPID

LimitCORE=infinity

Environment=KRB5CCNAME=FILE:/var/run/samba/SMB1/krb5cc_samba

[Install]

WantedBy=multi-user.target


vi /usr/lib/systemd/system/nmb2.service

[Unit]

Description=Samba NMB2 Daemon

Documentation=man:nmbd(8) man:samba(7) man:smb.conf(5)

Wants=network-online.target

After=network.target network-online.target

[Service]

Type=notify

PIDFile=/var/run/SMB2/nmbd.pid

EnvironmentFile=-/etc/sysconfig/samba.SMB2

ExecStart=/usr/sbin/nmbd --foreground --no-process-group $NMBDOPTIONS

ExecReload=/bin/kill -HUP $MAINPID

LimitCORE=infinity

Environment=KRB5CCNAME=FILE:/var/run/samba/SMB2/krb5cc_samba

[Install]

WantedBy=multi-user.target


Step 5 – Create local users:


useradd -d /tmp/test test

smbpasswd -c /etc/samba/smb.conf.SMB1 -a test

smbpasswd -c /etc/samba/smb.conf.SMB2 -a test



Step 6 – Enable & Start the new services:


systemctl daemon-reload

systemctl enable nmb2

systemctl enable smb2

systemctl enable smb1

systemctl enable nmb1

systemctl start nmb1

systemctl start nmb2

systemctl start smb1

systemctl start smb2



Step 6 – Test the share:


Ideally from a different Linux machine,

mkdir /tmp/1

mount-t cifs //SMB1.domain.tld/test /tmp/1 -o username=test,password=p455w0rd,vers=1.0

umount /tmp/1

mount-t cifs //SMB2.domain.tld/test /tmp/1 -o username=test,password=p455w0rd,vers=2.0



Monday, October 16, 2023

18

Not the best year.

Friday, August 04, 2023

Generate pseudo-random, incremental serial numbers for motherboards

 

@echo off

    setlocal enableextensions disabledelayedexpansion

 

for /f "tokens=1,* delims=:" %%a in ('

        findstr /l /b /c:":::persist:::" "%~f0"

') do set "%%~b"

if not defined savedValue (

        set "savedValue=%random%" && ( call :persist.write savedValue )

)

    set /a savedValue=%savedValue%+1  && ( call :persist.write savedValue )

    ;;echo DEBUG: Recorded data %savedValue%

    set ss=DW173878110%savedValue%

    set bs=BTDN8389450%savedValue%

    set su=00020003000400050006000700080i%savedValue%

AMIDEWINx64.EXE /CM "My Corporation" /BM "My Corporation" /BV J83500-205 /BP NUC7i7DNB  /SM "My Corporation" /SV J85489-205 /SP NUC7i7DNHE /SS %ss% /BS %bs% /SU %su%

    timeout 10 /nobreak >nul

goto :eof

 

:persist.write varName

    if "%~1"=="" goto :eof

    for %%a in ("%temp%\%~nx0.%random%%random%%random%.tmp") do (

        findstr /l /v /b /c:":::persist::: %~1=" "%~f0" > "%%~fa"

        >"%~f0" (

            type "%%~fa"

            setlocal enabledelayedexpansion

            echo(:::persist::: %~1=!%~1!

            endlocal

        )

        del /q "%%~fa"

    )

    goto :eof

 

Friday, May 05, 2023

Pingresults

Ping a host once every X seconds and save the result in a csv:

 

 

@echo off
SETLOCAL

if [%1]==[/?] goto :help

::Set the address to ping
set address=%1
if [%1]==[] goto :fatal

::Set the destination filename
set filename=%2
if [%2]==[] set filename=pingres.csv

::Set delay between pings (seconds)
set delay=%3
if [%3]==[] set delay=30

:: some info
echo.
echo Running %0 %address% %filename% %delay% - press "Q" for at least %delay%s to quit.
echo.

:: Prepare csv header
echo Time, Target, Lag > %filename%

:loop
::Ping
for /F "tokens=7 delims== " %%l in ('ping -n 1 %address%^|findstr /i "time="') do set lag=%%l

::echo Current ping for %address%: %ping%
<nul set /p =.

::Set Timestamp
set curTime= %date:~0,4%/%DATE:~5,2%/%DATE:~8,3%-%time:~0,2%:%time:~3,2%:%time:~6,2%

::Write in .csv
echo %curTime%, %address%, %lag% >> %filename%

::delay
timeout /T %delay% /nobreak >nul

::keypress
choice /c QWERTY /d Y /t 1 /n >nul
if %errorlevel%==1 ( exit /B 0)

goto :loop

:help
echo.
echo Usage: %0 target resultfile delay
echo if not specified, resultfile is "pingres.csv" and delay is 30s

:fatal
echo.
echo You need to provide at least the hostname/IP of the target
echo type %0 /? for help
exit /B 1

ENDLOCAL

Sunday, April 09, 2023

Stop a service and wait for it to stop

 

@echo off
:: echo without NewLine
 <nul set /p =Please wait. Stopping Service...
 :: request stop service
sc stop "service we need to stop" >nul
:: wait up to 30 seconds for the service to stop
set a=1
set tmout=30
:retry
:: is it stopped ?
sc query "service we need to stop" | find "STOPPED"
if errorlevel 1 (
:: echo dots on the same line
 <nul set /p =.
 timeout 1 /nobreak >nul
 set /a a += 1
if %%a%% lss %%tmout%%  goto retry
)
:: allow one second to see the messages
timeout 1 /nobreak >nul

Friday, March 31, 2023

Reset ILO password without OS

If you have an OS installed is simple, just use hponcfg and you can change the password as explained in https://blog.toma.guru/2015/04/hp-ilo-linux-reset-password.html but if no OS is available, then hope is not lost, you can use the iLO Physical Presence Button.

On RX2800 Itanium iLO Physical Presence Button is hidden behind the small red hole

 

As stated on https://support.hpe.com/hpesc/public/docDisplay?docId=c02728748

The iLO 3 physical presence button enables to reset iLO 3 and reset the user-specific values to factory default values. A momentary press causes a soft reset of iLO 3 when the button is released. The iLO 3 Physical Presence button enables to reset iLO, enter TPM physical presence mode, and enter security override mode.

  • A momentary press of the button resets iLO and clears any security override or TPM physical presence mode that were initiated by this button.

  • A greater than 4 seconds less than 8 seconds, press of the button places the system in physical presence mode for up to 15 minutes.

  • A greater than 8 seconds less than 12 seconds, press of this button places iLO into security override mode for up to 15 minutes. Security override mode enables to enter iLO without being challenged for a password enabling to set up users.

    The UID LED blinks once after holding the button for 4 seconds and once after holding the button for 8 seconds to help gauge how long the button press has been held.

 

 

Blog Archive