SMBstack — Samba Server Stack
|
Many small and medium-sized businesses need to share files on their local network. They may also need to recover deleted files, review access records, manage files through a browser and control storage usage. Dedicated NAS devices often provide these functions, but their cost can be a barrier in some environments. One alternative is to use Samba on Linux. A standard installation lets you share files and folders; additional components are needed for the other functions. SMBstack provides part of this infrastructure using Samba as its base for file sharing and permission management. It adds a recycle bin with separate channels according to the origin of the files, audit logs, a web panel for viewing and managing files and a daily disk usage report. It also incorporates mechanisms to monitor services, control folder sizes and back up the configuration. |
Muchas pequeñas y medianas empresas necesitan compartir archivos en su red local. Además, pueden necesitar recuperar archivos eliminados, consultar los accesos, gestionar archivos desde un navegador y controlar el espacio utilizado. Estas funciones suelen ofrecerse en dispositivos NAS, cuyo costo puede ser una barrera en algunos entornos. Una alternativa es usar Samba en Linux. La instalación estándar permite compartir archivos y carpetas; para añadir las demás funciones se necesitan componentes adicionales. SMBstack proporciona parte de esta infraestructura utilizando Samba como base para compartir archivos y gestionar permisos. Añade una papelera de reciclaje con canales separados según el origen de los archivos, registros de auditoría, un panel web para consultar y gestionar archivos y un informe diario de uso de disco. También incorpora mecanismos para supervisar los servicios, controlar el tamaño de las carpetas y respaldar la configuración. |
|
Only tested on Ubuntu 24.04/26.04 LTS. Other versions or distributions are not tested and are used at your own risk. |
Solo probado en Ubuntu 24.04/26.04 LTS. Otras versiones o distribuciones no están probadas y se usan bajo tu responsabilidad. |
|
Installation and update require the following:
The operation continues if the applicable requirements above are met; otherwise, it aborts. |
La instalación y actualización requieren lo siguiente:
La operación continúa si se cumplen los requisitos anteriores que correspondan; de lo contrario, aborta. |
- Apache2 and PHP (
apache2,apache2-utils,libapache2-mod-php,php) rsyslog,logrotateacl,openssl,cron,iproute2,sudo,systemd,util-linux,zip,python3,python3-yaml(checked bysmbsetup.sh)inotify-tools,procps,coreutils,findutils,cron,util-linux,sed,grep(checked bytools/smbwatch.sh)procps,samba,winbind,util-linux,coreutils,sed,systemd(checked bytools/smbload.sh)zip,coreutils,util-linux,cron(checked bytools/smbbk.sh)findutils,coreutils,util-linux,cron,php-cli(checked bytools/smbreport.sh)
apt-get install -y apache2 apache2-utils libapache2-mod-php php rsyslog logrotate \
acl openssl cron iproute2 sudo systemd util-linux sed grep inotify-tools \
procps coreutils findutils zip python3 python3-yamlThe Samba packages (samba, samba-common, samba-common-bin, smbclient, winbind, cifs-utils) are installed by smbsetup.sh itself.
Important
|
Importante
|
smbstack/
├── acl/ # deployed to: /etc/smbstack/acl [0755 root:root]
│ └── commonveto.txt # Samba veto list [0644 root:root]
│
├── conf/ # Samba, rsyslog and Apache configuration
│ ├── fullaudit.conf # deployed to: /etc/rsyslog.d/fullaudit.conf [0644 root:root]
│ ├── smb.conf # deployed to: /etc/samba/smb.conf [0644 root:root]
│ └── smbweb.conf # deployed to: /etc/apache2/sites-available/smbweb.conf [0644 root:root]
│
├── tools/ # deployed to: /etc/smbstack/tools [0755 root:root]
│ ├── smbstackenv.sh # shared Bash configuration reader [0644 root:root]
│ ├── smbbk.sh # Configuration backup for smbstack [0750 root:root]
│ ├── smbload.sh # Service watchdog (smbd + winbind + smbwatch) [0750 root:root]
│ ├── smbreport.sh # Disk usage report for the shared folder (daily cron) [0750 root:root]
│ └── smbwatch.sh # Shared folder size monitor (self-managed) [0750 root:root]
│
├── web/ # deployed to: /var/www/smbstack/web [0755 www-data:www-data]
│ ├── icon.svg # PWA / apple-touch icon [0644 www-data:www-data]
│ ├── index.php # Main page (Shared / Audit / Report tabs) [0644 www-data:www-data]
│ ├── manifest.json # PWA manifest [0644 www-data:www-data]
│ ├── smbshared.php # Shared folder dynamic browser [0644 www-data:www-data]
│ ├── smbapi.php # Audit log and disk report reader API [0644 www-data:www-data]
│ ├── smbaudit-diagnostic.php # Audit log diagnostic tool [0644 www-data:www-data]
│ ├── smbaudit.html # Audit log viewer UI [0644 www-data:www-data]
│ ├── smbreport.html # Disk report viewer UI [0644 www-data:www-data]
│ └── sw.js # PWA service worker (app-shell cache only) [0644 www-data:www-data]
│
└── smbsetup.sh # Installer: install, update, uninstall, status
/var/www/smbstack/ # panel root [0755 root:root]
├── .size_cache/ # folder size cache [0700 www-data:www-data]
└── web/
└── smbreport.json # generated disk usage report [0640 root:www-data]
/etc/smbstack/ # installed configuration root [0755 root:root]
└── smbstack.env # generated configuration [0640 root:www-data]
/etc/apache2/sites-enabled/
└── smbweb.conf # link to ../sites-available/smbweb.conf [0777 root:root]
/etc/cron.d/
├── smbstack # scheduled tasks [0644 root:root]
└── smbstack.lock # cron writer lock [0600 root:root]
/etc/logrotate.d/
├── samba # Samba log rotation [0644 root:root]
├── smbstack # SMBstack log rotation [0644 root:root]
└── smbwatch # folder monitor log rotation [0644 root:root]
/etc/bak/smbstack/ # last three configuration backups [0700 root:root]
/var/log/
├── samba/ # Samba log directory, observed [0750 root:adm]
│ ├── log.audit # Samba audit log [0660 root:adm]
│ └── log.samba # Samba log, initial permissions [0660 root:adm]
├── smbwatch.log # folder monitor log [0640 root:root]
├── smbload.log # service watchdog log, observed [0644 root:root]
└── smbstack.log # backup and report log [0640 root:adm]
smbsetup.log # installer log, reset each run
/home/$local_user/shared/ # Shared folder (independent of the installer)
├── .recycle/ # Recycle Bin (smbguest/, www-data/, smbwatch/)
└── DEMO/ # Demo folder
git clone --depth=1 https://github.com/maravento/smbstack.git
cd smbstack
# Install
sudo bash smbsetup.sh --install
# Update
sudo bash smbsetup.sh --update
# Uninstall
sudo bash smbsetup.sh --uninstall
# Status
sudo bash smbsetup.sh --status
# Interactive menu
sudo bash smbsetup.sh| SCOPE | ALCANCE |
|---|---|
|
|
| OUT OF SCOPE | FUERA DE ALCANCE |
|
|
Update checks Apache port 3092 and adds a missing Listen. It aligns the installed VirtualHost port and validates Apache before resuming services. |
La actualización comprueba el puerto 3092 de Apache y añade el Listen ausente. Ajusta el puerto del VirtualHost instalado y valida Apache antes de reanudar los servicios. |
| Step | Description | Descripción |
|---|---|---|
| Before copying | The installer checks all required source files and destinations, write access, available space, immutable attributes and relevant locks. | El instalador comprueba todos los orígenes y destinos, escritura, espacio disponible, atributos inmutables y bloqueos relevantes. |
| Backup | The installer invokes smbbk.sh. If smbbk.sh fails, the installer aborts before pausing consumers or replacing files, without writing done. |
El instalador invoca smbbk.sh. Si smbbk.sh falla, el instalador aborta antes de pausar procesos o reemplazar archivos, sin escribir done. |
| Pause | The installer pauses its cron file and stops affected services and daemons. It verifies they have stopped and waits for running jobs before replacing files. If a pause fails before any replacement, the installer attempts to resume the previous consumers and schedule. | El instalador pausa su archivo cron y detiene los servicios y demonios afectados. Comprueba su detención y espera que terminen las tareas en ejecución antes de reemplazar archivos. Si falla una pausa antes de reemplazar archivos, el instalador intenta reanudar los procesos y la programación anteriores. |
| Copy | The installer repeats the checks immediately before copying. It verifies every replacement and its file contents. If a replacement fails, it aborts without done; it does not resume the consumers or restore the backup. The paused schedule remains at /etc/cron.d/smbstack.update-disabled. |
El instalador repite las comprobaciones inmediatamente antes de copiar. Comprueba cada reemplazo y el contenido copiado. Si falla un reemplazo, aborta sin done; no reanuda los procesos ni restaura el respaldo. La programación pausada permanece en /etc/cron.d/smbstack.update-disabled. |
| Finish | The installer regenerates its complete cron file and resumes the consumers that were active. It writes done only after successful completion. |
El instalador regenera su archivo cron completo y reanuda los procesos que estaban activos. Escribe done únicamente si termina correctamente. |
Only interfaces with an UP link and global IPv4 are candidates. With none, abort; with one, select LAN automatically; with several, ask for LAN and omit the others. A caller can provide SMBSTACK_IFACE; validate it against the candidates and reuse it without asking for the interface. With several LAN IPv4 addresses, ask which to use, including when the interface was supplied by a caller. Save the selected address in SERVER_IP. Derive the network and mask from the selected address and its actual prefix. The installer does not configure network interfaces.
|
Solo son candidatas las interfaces con enlace UP e IPv4 global. Sin candidatas, aborta; con una, selecciona LAN automáticamente; con varias, pregunta LAN y omite las demás. Otro instalador puede proporcionar SMBSTACK_IFACE; se valida contra las candidatas y se reutiliza sin preguntar la interfaz. Con varias IPv4 en LAN, pregunta cuál utilizar, incluso si otro instalador proporcionó la interfaz. Guarda la dirección elegida en SERVER_IP. Calcula red y máscara desde la dirección seleccionada y su prefijo real. El instalador no configura las interfaces de red.
|
| The installer will prompt for: | El instalador preguntará por: |
| Prompt | Description | Descripción |
|---|---|---|
| Shared folder name | Name for the shared folder (created under /home/$local_user/). Same ASCII format and 1–255 character limit described for WATCH_ROOT_ALLOW |
Nombre de la carpeta compartida (creada bajo /home/$local_user/). Mismo formato ASCII y límite de 1 a 255 caracteres descritos para WATCH_ROOT_ALLOW |
| Network interface | Selected from available interfaces listed. The Samba network is derived from its address and prefix | Seleccionada de las interfaces disponibles listadas. La red de Samba se deriva de su dirección y prefijo |
| Samba password | Password for the automatically detected account | Contraseña de la cuenta detectada automáticamente |
To use a shared folder located outside
/home/$local_user/, edit/etc/samba/smb.confand/etc/apache2/sites-available/smbweb.confmanually after the installation.Para utilizar una carpeta compartida ubicada fuera de
/home/$local_user/, edita manualmente/etc/samba/smb.confy/etc/apache2/sites-available/smbweb.confdespués de la instalación.
Set SMBSTACK_IFACE to skip the interactive interface selection. For example:sudo SMBSTACK_IFACE=eth1 bash smbsetup.sh --installAnother installer deploying SMBstack can use this variable to provide the interface it already knows. $local_user is the local Linux user that the installer detects automatically.The installer looks for an account whose UID falls within the range in /etc/login.defs, whose login shell is enabled and that belongs to the sudo group. If several accounts match, it selects the one with the lowest UID.That account owns the shared folder and provides the base name for the Samba username. |
Define SMBSTACK_IFACE para omitir la selección interactiva de la interfaz. Por ejemplo:sudo SMBSTACK_IFACE=eth1 bash smbsetup.sh --installOtro instalador que despliega SMBstack puede utilizar esta variable para proporcionar la interfaz que ya conoce. $local_user es el usuario local de Linux que el instalador detecta automáticamente.El instalador busca una cuenta con UID dentro del rango de /etc/login.defs, una shell habilitada y pertenencia al grupo sudo. Si encuentra varias, elige la de UID más bajo.Usa esa cuenta como propietaria de la carpeta compartida y como base para el nombre de usuario de Samba. |
| File | --update |
--uninstall |
|---|---|---|
conf/smb.conf |
⛔ not touched (user-customized) | ✅ restored from .bak if it exists (only created when the installer overwrote a pre-existing smb.conf; on a fresh install, no .bak exists and smb.conf is left untouched) |
conf/fullaudit.conf |
⛔ not touched (user-customized) | ✅ removed |
conf/smbweb.conf |
Preserved; VirtualHost ports set to 3092 / Conservado; puertos de VirtualHost ajustados a 3092 |
✅ removed |
web/index.php |
✅ overwritten | ✅ removed |
web/smbaudit.html |
✅ overwritten | ✅ removed |
web/smbapi.php |
✅ overwritten | ✅ removed |
web/smbaudit-diagnostic.php |
✅ overwritten | ✅ removed |
web/smbshared.php |
✅ overwritten | ✅ removed |
web/manifest.json |
✅ overwritten | ✅ removed |
web/sw.js |
✅ overwritten | ✅ removed |
web/icon.svg |
✅ overwritten | ✅ removed |
tools/smbbk.sh |
✅ overwritten | ✅ removed (its cron entry is deregistered first) |
tools/smbload.sh |
✅ overwritten | ✅ removed |
tools/smbreport.sh |
✅ overwritten | ✅ removed (its cron entry is deregistered first) |
tools/smbwatch.sh |
✅ overwritten | ✅ removed |
/etc/smbstack/smbstack.env |
⛔ preserved | ✅ removed |
Logs /var/log/smbstack.log, /var/log/smbwatch.log and /var/log/smbload.log |
⛔ preserved | ✅ removed |
www-data ACL on the user's home |
⛔ preserved | ✅ removed |
Shared folder (/home/$local_user/shared/) |
⛔ never touched | ⛔ never touched |
Samba accounts of the administrator and smbguest, the smbguest system user and its ACL on the user's home |
⛔ preserved | Only accounts created by SMBStack are removed; the home ACL is removed only if SMBStack created the system user |
| APT packages (Samba, Apache, PHP and the rest of the installer list) | ✅ missing ones installed | ⛔ preserved |
The shared folder is independent of the installer. To remove it, do so manually:
rm -rf /home/$local_user/sharedLa carpeta compartida es independiente del instalador. Para eliminarla, hazlo manualmente:
rm -rf /home/$local_user/shared
--uninstallremoves the project only. It never uninstalls APT packages: other projects and the system may share them.
--uninstallelimina solo el proyecto. Nunca desinstala paquetes APT, porque otros proyectos y el sistema pueden compartirlos.
Before updating, --update runs tools/smbbk.sh to back up the installation to BACKUP_DIR, which must be /etc/bak/smbstack. It replaces the web application and tools. It preserves the installed Samba and rsyslog configuration. For Apache, it preserves smbweb.conf while setting its VirtualHost ports to 3092, and adds Listen 127.0.0.1:3092 to ports.conf if no listener for that port exists. It also regenerates project cron entries and log rotation rules. It repairs the owner and mode of /etc/smbstack/acl and commonveto.txt, without rewriting the list.
|
Antes de actualizar, --update ejecuta tools/smbbk.sh para respaldar la instalación en BACKUP_DIR, que debe ser /etc/bak/smbstack. Reemplaza la aplicación web y las herramientas. Conserva la configuración instalada de Samba y rsyslog. Para Apache, conserva smbweb.conf y ajusta sus puertos de VirtualHost a 3092; añade Listen 127.0.0.1:3092 a ports.conf si no existe una escucha para ese puerto. También regenera las entradas cron y las reglas de rotación de registros del proyecto. Repara el propietario y los permisos de /etc/smbstack/acl y commonveto.txt, sin reescribir la lista.
|
Compare the installed configuration with the repository's
conf/templates before applying template changes manually.Compare la configuración instalada con las plantillas de
conf/del repositorio antes de aplicar manualmente cambios de esas plantillas.
Shows the status of the smbd and winbind services, the status of Apache port 3092, the last five audit log entries and a testparm summary.
|
Muestra el estado de los servicios smbd y winbind, el estado del puerto 3092 de Apache, las últimas cinco entradas del registro de auditoría y un resumen de testparm.
|
sudo bash smbsetup.sh --status
Shared Bash reader installed at /etc/smbstack/tools/smbstackenv.sh. smbsetup.sh, smbbk.sh, smbreport.sh and smbwatch.sh load it with source and declare their allowed keys. It parses smbstack.env without executing it; file permissions and key validation remain with each caller. Installation and update deploy it before consumers; the backup and report tools also copy it when registering themselves. Do not run it separately or schedule it in cron.
|
Lector Bash compartido instalado en /etc/smbstack/tools/smbstackenv.sh. smbsetup.sh, smbbk.sh, smbreport.sh y smbwatch.sh lo cargan mediante source y declaran sus claves permitidas. Interpreta smbstack.env sin ejecutarlo; los permisos y la validación de claves permanecen en cada script. La instalación y la actualización despliegan el lector antes de sus consumidores; las herramientas de respaldo e informes también lo copian cuando se registran. No se ejecuta por separado ni se programa en cron.
|
| After installation, the main configuration files are: | Tras la instalación, los archivos de configuración principales son: |
| Description | File |
|---|---|
| Samba main config | /etc/samba/smb.conf |
| Audit rsyslog rule | /etc/rsyslog.d/fullaudit.conf |
| Web vhost (audit + shared) | /etc/apache2/sites-available/smbweb.conf |
| Log rotation (Samba logs) | /etc/logrotate.d/samba |
Log rotation (smbwatch.sh) |
/etc/logrotate.d/smbwatch |
Log rotation (Apache logs, set to rotate 7) |
/etc/logrotate.d/apache2 |
| Install config | /etc/smbstack/smbstack.env |
smbsetup.sh writes the keys listed below during install and never overwrites the file on update. smbwatch.sh --install adds four more of its own, WATCH_LIMIT_GB, WATCH_EXCLUDE, WATCH_ROOT_ALLOW and WATCH_ROOT_SYSTEM; see the smbwatch section.
|
smbsetup.sh escribe las claves enumeradas abajo durante install y no sobrescribe el archivo en update. smbwatch.sh --install añade cuatro propias, WATCH_LIMIT_GB, WATCH_EXCLUDE, WATCH_ROOT_ALLOW y WATCH_ROOT_SYSTEM; ver la sección de smbwatch.
|
| Variable | Read by | Description | Descripción |
|---|---|---|---|
LOCAL_USER |
smbbk.sh |
Non-root local user that owns the shared folder. The backups belong to root, so smbbk.sh only reads this account's passwd entry to record it |
Usuario local sin privilegios que posee la carpeta compartida. Las copias pertenecen a root, así que smbbk.sh solo lee la entrada passwd de esta cuenta para registrarla |
SHARED_NAME |
smbshared.php |
Share name as the SMB clients see it | Nombre del recurso tal como lo ven los clientes SMB |
SHARED_PATH |
smbwatch.sh, smbreport.sh, smbshared.php |
Absolute path of the shared folder | Ruta absoluta de la carpeta compartida |
SMB_NET |
smbsetup.sh |
LAN subnet in CIDR form allowed to reach the share | Subred LAN en formato CIDR autorizada a acceder al recurso |
SMB_IFACE |
smbsetup.sh |
Interface Samba binds to | Interfaz a la que se enlaza Samba |
SERVER_IP |
smbsetup.sh, smbshared.php |
Server's own IPv4 on that interface | IPv4 del servidor en esa interfaz |
SMBNAME |
smbsetup.sh |
Samba account used for the share | Cuenta de Samba utilizada para el recurso |
SMB_ACCOUNT_CREATED, SMBGUEST_CREATED, SMBGUEST_ACCOUNT_CREATED |
smbsetup.sh |
Boolean ownership flags for the user's Samba account, the guest system account and the guest Samba account. Uninstall preserves accounts it did not create | Indicadores booleanos de creación de la cuenta Samba del usuario, la cuenta de sistema invitada y la cuenta Samba invitada. La desinstalación conserva las cuentas que no creó |
SMBREPORT_TOP_ROWS, SMBREPORT_TOP_FILES |
smbreport.sh |
Report ranking limits. Defaults: 30 rows and 50 files, written automatically without questions. Positive integers without leading zeros. Changing these defaults is not recommended. |
Límites de los listados del informe. Valores iniciales: 30 filas y 50 archivos, escritos automáticamente sin preguntas. Enteros positivos sin ceros iniciales. No se recomienda modificarlos. |
MAX_LOG_LINES |
smbapi.php, smbaudit-diagnostic.php |
Maximum audit records returned by smbapi.php per request; default 50000. It reads the current log and then up to seven .gz rotations until the limit is reached. The CLI diagnostic uses the same value for the current log. The audit viewer's own request uses a fixed limit in its JavaScript, so raising this does not change what the UI asks for |
Máximo de registros de auditoría devueltos por smbapi.php por petición; valor predeterminado 50000. Lee el log vigente y después hasta siete rotaciones .gz hasta alcanzar el límite. El diagnóstico CLI usa el mismo valor para el log vigente. La petición del visor usa un límite fijo en su JavaScript, así que subir esta clave no cambia lo que pide la interfaz |
TRUSTED_PROXIES |
smbshared.php |
IPv4 addresses, comma-separated, whose REMOTE_ADDR is trusted to carry the real client IP in a header; default 127.0.0.1 |
Direcciones IPv4 separadas por comas cuyo REMOTE_ADDR se considera fiable para traer la IP real del cliente en un encabezado; valor predeterminado 127.0.0.1 |
smbstack.env sets TRUSTED_PROXIES="127.0.0.1" by default.This setting tells web/smbshared.php that, for requests arriving from localhost, it must use the CF-Connecting-IP or X-Forwarded-For header, when present, instead of REMOTE_ADDR. This way the loopback connection of a local tunnel is not recorded as the client address in the audit log.The setting has no effect on direct access from the LAN. |
smbstack.env establece TRUSTED_PROXIES="127.0.0.1" por defecto.Esta configuración indica a web/smbshared.php que, para las solicitudes que llegan desde localhost, utilice el encabezado CF-Connecting-IP o X-Forwarded-For, cuando esté presente, en lugar de REMOTE_ADDR. De esta forma, la conexión loopback de un túnel local no se registra como la dirección del cliente en el registro de auditoría.La configuración no tiene efecto sobre el acceso directo desde la LAN. |
# Verify Samba config | Verificar configuración de Samba
testparm
# Restart services | Reiniciar servicios
sudo systemctl restart smbd winbind
# View audit log | Ver log de auditoría
tail -f /var/log/samba/log.audit
# List Samba users | Listar usuarios de Samba
sudo pdbedit -L
SMBstack uses the Samba vfs_recycle module to redirect deleted files to a hidden recycle bin, instead of removing them permanently. The bin is stored inside the shared folder, under .recycle/.
|
SMBstack utiliza el módulo vfs_recycle de Samba para redirigir los archivos eliminados a una papelera de reciclaje oculta, en lugar de borrarlos permanentemente. Esta se almacena dentro de la carpeta compartida, en .recycle/.
|
| SMBstack uses three independent channels to write to the recycle bin, each running under a different system context: | SMBstack utiliza tres canales independientes para escribir en la papelera de reciclaje, cada uno ejecutándose bajo un contexto de sistema diferente: |
| Path | Written by | Purpose | Propósito |
|---|---|---|---|
.recycle/smbguest/ |
SMB clients on the LAN, through vfs_recycle (smbguest, set by force user in smb.conf) |
Holds files deleted by users from Windows or Linux over the network | Guarda los archivos borrados por los usuarios desde Windows o Linux por la red |
.recycle/www-data/ |
The web interface running under Apache (www-data) |
Holds files deleted from the browser panel | Guarda los archivos borrados desde el panel web |
.recycle/smbwatch/ |
tools/smbwatch.sh (root:root) |
Holds files moved out automatically when a monitored folder exceeds its size limit | Guarda los archivos retirados automáticamente cuando una carpeta monitoreada supera su límite de tamaño |
| This is why the recycle bin directory contains one subdirectory per channel: | Por eso el directorio de la papelera contiene un subdirectorio por canal: |
.recycle/
├── smbguest/ # Files deleted by Windows/Linux SMB clients on the LAN
│ └── DOCUMENTS/
│ ├── report.docx
│ └── Copy #1 of report.docx
├── www-data/ # Files deleted via the web browser interface
│ └── 20260623/
│ └── invoice.pdf
└── smbwatch/ # Files auto-moved by the size-limit watchdog
└── 20260711/
└── bigfile.iso
the recycle bin lives inside the shared folder itself, so that recycling a file is a
mvwithin the same filesystem: instantaneous and without copying data, something that would not happen if the bin were on another disk. For the details of each channel, see the Web Interface, smbwatch and Configuration reference sections.la papelera vive dentro de la propia carpeta compartida para que reciclar un archivo sea un
mvdentro del mismo sistema de archivos: instantáneo y sin copiar datos, algo que no ocurriría si la papelera estuviera en otro disco. Para conocer el detalle de cada canal, consulta las secciones Web Interface, smbwatch y Configuration reference.
|
The weekly cleanup deletes items based on their modification date. Each channel therefore updates that date when moving an item to the recycle bin. Otherwise, an old file could be deleted during the next cleanup even though it had only just been recycled. Each channel updates the item's modification date with the current date when moving it to the bin: |
La limpieza semanal elimina elementos según su fecha de modificación. Por eso, al mover un archivo a la papelera, cada canal actualiza esa fecha. Si se conservara la fecha original, un archivo antiguo podría eliminarse en la siguiente limpieza aunque acabara de reciclarse. Cada canal actualiza la fecha de modificación del elemento con la fecha actual al moverlo a la papelera: |
| Channel | Stamped by |
|---|---|
| SMB (LAN clients) | recycle:touch_mtime = yes in smb.conf |
| Web interface (Apache) | web/smbshared.php, applied recursively so a recycled folder carries its contents |
| Size-limit watchdog | touch after the move, in tools/smbwatch.sh |
A restored item therefore carries the date it was recycled, not its original one.
Por eso un elemento restaurado conserva la fecha en que fue reciclado, no la original.
When recycle:versions = yes is active, deleting a file that already exists in the recycle bin does not overwrite it. The new copy is kept alongside the original with the Copy #N of prefix:
|
Cuando recycle:versions = yes está activo, eliminar un archivo que ya existe en la papelera no lo sobrescribe. La nueva copia se conserva junto a la original con el prefijo Copy #N of:
|
.recycle/smbguest/DOCUMENTS/
├── report.docx ← first deletion
└── Copy #1 of report.docx ← second deletion of the same file
To exclude specific file types from versioning, use recycle:noversions. These types are still recycled, but repeated deletions overwrite the previous copy in the bin rather than creating a numbered duplicate:
|
Para excluir tipos de archivo del versionado, usa recycle:noversions. Estos archivos siguen yendo a la papelera, pero eliminaciones repetidas sobreescriben la copia anterior en lugar de crear una nueva numerada:
|
# All files keep multiple versions:
recycle:versions = yes
# These types are recycled but NOT versioned — second delete overwrites the first:
recycle:noversions = *.dat,*.iniUse
noversionsfor files where accumulating copies adds no value: runtime data files, config dumps, ini snapshots, and similar.Usa
noversionspara archivos donde acumular copias no aporta valor: archivos de datos en tiempo de ejecución, volcados de configuración, snapshots de ini y similares.
| Parameter | Value | Purpose | Propósito |
|---|---|---|---|
recycle:repository |
.recycle/%U |
SMB channel recycle bin, resolves to smbguest |
Papelera del canal SMB, resuelve a smbguest |
recycle:directory_mode |
0775 |
Group-writable recycle directory | Directorio escribible por el grupo |
recycle:keeptree |
yes |
Preserve original folder structure | Preservar estructura de carpetas |
recycle:versions |
yes |
Keep multiple versions of deleted files | Mantener múltiples versiones |
recycle:noversions |
*.dat,*.ini |
Exclude patterns from versioning | Excluir patrones del versionado |
recycle:touch |
yes |
Update access time when recycled | Actualizar tiempo de acceso al reciclar |
recycle:touch_mtime |
yes |
Update modification time when recycled; weekly cleanup uses this date | Actualiza la fecha de modificación al reciclar; la limpieza semanal utiliza esta fecha |
recycle:exclude |
*.tmp,*.temp,*.o,… |
Permanently delete matching files | Eliminar permanentemente archivos que coincidan |
recycle:exclude_dir |
/temp,/tmp,/cache,/.Trash-1000 |
Bypass recycle bin for directories | Omitir papelera para directorios |
recycle:maxsize |
1073741824 |
Max file size (1 GB) | Tamaño máximo (1 GB) |
hide files |
/.recycle/ |
Hide recycle directory from clients | Ocultar papelera a los clientes |
The installer registers a weekly cron job, run as root, that removes recycled files older than 7 days:
|
El instalador registra una tarea cron semanal, ejecutada como root, que elimina los archivos reciclados con más de 7 días de antigüedad:
|
@weekly root find "/home/$local_user/shared/.recycle/" -depth -mindepth 2 -mtime +6 -delete >/dev/null 2>&1| To adjust the retention period, edit the project cron file. To inspect its entries, display the file: | Para ajustar el período de retención, edita el archivo de tareas del proyecto. Para consultar sus entradas, muestra el archivo: |
# Edit project cron entries
sudo nano /etc/cron.d/smbstack
# Inspect project cron entries
sudo cat /etc/cron.d/smbstackThe cleanup runs once a week and removes items older than six days, so an item remains in the bin for 7 to almost 14 days, depending on when it was moved there.
Como la limpieza se ejecuta una vez por semana y elimina elementos con más de seis días, estos permanecen en la papelera entre 7 y casi 14 días, según cuándo se hayan movido allí.
SMBstack uses the Samba vfs_full_audit module to record file operations in /var/log/samba/log.audit through rsyslog. Only successful operations are recorded; failures are excluded to keep the log clean.
|
SMBstack utiliza el módulo vfs_full_audit de Samba para registrar las operaciones de archivos en /var/log/samba/log.audit mediante rsyslog. Solo se registran las operaciones exitosas; los fallos se excluyen para mantener el registro limpio.
|
| Parameter | Value | Description | Descripción |
|---|---|---|---|
full_audit:logfile |
/var/log/samba/log.audit |
Destination log file, written via the rsyslog rule in /etc/rsyslog.d/fullaudit.conf. |
Archivo de log de destino, escrito mediante la regla rsyslog en /etc/rsyslog.d/fullaudit.conf. |
full_audit:prefix |
%I|%m|%S |
Fields prepended to each log entry: %I = client IP address, %m = client machine name, %S = share name. |
Campos que se anteponen a cada entrada del log: %I = IP del cliente, %m = nombre del equipo cliente, %S = nombre del share. |
full_audit:success |
mkdirat renameat unlinkat pwrite |
VFS operations logged when they succeed. See table below. | Operaciones VFS que se registran cuando tienen éxito. Ver tabla a continuación. |
full_audit:failure |
none |
No failed operations are logged. | No se registran operaciones fallidas. |
full_audit:facility |
LOCAL5 |
rsyslog facility used to route audit entries to the dedicated log file, keeping them separate from general system logs. | Facility de rsyslog usada para enrutar las entradas de auditoría al archivo dedicado, manteniéndolas separadas de los logs generales del sistema. |
full_audit:priority |
notice |
Syslog priority level assigned to audit entries. | Nivel de prioridad syslog asignado a las entradas de auditoría. |
| Samba syscall | Triggered by | Desencadenado por |
|---|---|---|
mkdirat |
Creating a directory via SMB or the web interface | Creación de un directorio vía SMB o la interfaz web |
renameat |
Renaming or moving a file or folder. Also triggered by Windows clients when saving a file (temp file + rename pattern). | Renombrado o movimiento de archivo o carpeta. También lo disparan los clientes Windows al guardar un archivo (patrón de archivo temporal + renombrado). |
unlinkat |
File deletion — permanent or moved to the recycle bin. See caveat below. | Borrado de archivo — permanente o movido a la papelera. Ver matiz abajo. |
pwrite |
Data written to an open file, via SMB or via the web interface. See caveat below. | Datos escritos en un archivo abierto, vía SMB o vía la interfaz web. Ver matiz abajo. |
|
|
openat is not included in full_audit:success by default.Every file or directory open generates an entry, including browsing, reads and downloads, not only writes. A single Explorer window open on a busy folder can produce dozens of near-identical lines per second. This volume of records can hide the events actually worth reviewing, and adds no further traceability, since pwrite records the write itself.To audit opens and reads as well, add it manually in /etc/samba/smb.conf:full_audit:success = mkdirat renameat unlinkat pwrite openatThen run testparm and systemctl restart smbd. --update will not modify this setting: smb.conf is not overwritten after the installation, so the change is preserved.
|
openat no se incluye en full_audit:success por defecto.Cada apertura de archivo o carpeta genera una entrada, incluida la navegación, las lecturas y las descargas, no solo las escrituras. Una sola ventana del Explorador abierta sobre una carpeta con actividad puede producir decenas de líneas casi idénticas por segundo. Este volumen de registros puede ocultar los eventos que sí conviene revisar y no aporta trazabilidad adicional, ya que pwrite registra la escritura propiamente dicha.Para auditar también las aperturas y lecturas, agréguelo manualmente en /etc/samba/smb.conf:full_audit:success = mkdirat renameat unlinkat pwrite openatLuego, ejecute testparm y systemctl restart smbd. --update no modificará este ajuste: smb.conf no se sobrescribe después de la instalación, por lo que el cambio se conserva.
|
smbload.sh is a service watchdog that checks that smbd and winbind are running. Neither unit has a Restart= policy configured, so they are not restarted automatically when they stop.It also checks that smbwatch.sh is still running and restarts it if it has stopped.The installer adds smbload.sh to cron automatically. It runs every five minutes from /etc/smbstack/tools/.
|
smbload.sh es un watchdog de servicios que comprueba que smbd y winbind estén en ejecución. Ninguna de las dos unidades tiene configurada una política Restart=, por lo que no se reinician automáticamente cuando se detienen.También comprueba que smbwatch.sh siga ejecutándose y lo reinicia si ha dejado de hacerlo.El instalador registra automáticamente smbload.sh en cron para que se ejecute cada cinco minutos desde /etc/smbstack/tools/.
|
# sudo cat /etc/cron.d/smbstack
*/5 * * * * root /etc/smbstack/tools/smbload.sh
smbload.shreads no configuration of its own. It checks whether the watcher is running and callssmbwatch.sh --startif it is not. It skips that restart whilesmbwatch.sh --install,smbwatch.sh --uninstallorsmbsetup.sh --uninstallholds the configuration lock. Untilsmbwatch.sh --installhas been run from a terminal, that call aborts on its own key check, sosmbload.shlogs a-alertwarning pointing atsmbwatch.log, where the missing or invalid key is named.
smbload.shno lee configuración propia. Comprueba si el vigilante corre y llama asmbwatch.sh --startsi no. Omite ese reinicio mientrassmbwatch.sh --install,smbwatch.sh --uninstallosmbsetup.sh --uninstallretiene el bloqueo de configuración. Hasta que se haya ejecutadosmbwatch.sh --installdesde un terminal, esa llamada aborta en su propia verificación de claves, así quesmbload.shregistra un aviso-alertque apunta asmbwatch.log, donde se nombra la clave que falta o es inválida.
smbwatch.sh monitors first-level subfolders and their contents in real time with inotifywait.If a folder exceeds its configured size limit, a newly completed or moved-in file is moved to .recycle/smbwatch/<YYYYMMDD>/. This channel is separate from .recycle/smbguest/ and .recycle/www-data/. See Recycle bin channels.smbwatch.sh is managed independently of the installer, through five actions: --install, --uninstall, --start, --stop and --status.--install asks for the two values, registers the @reboot entry and starts the watcher. It requires an interactive terminal and is run once. --uninstall asks for confirmation before removing its cron entry, stopping the watcher and deleting the two values.Caution: Do not modify smbstack.env until SMBwatch removal finishes.--start never writes: it validates the keys and launches the watcher. If a key is missing or invalid it aborts, naming each failure and telling the operator to run --install first. This is the action cron runs on every boot, and the one smbload.sh uses to restart a stopped watcher.The folder list is built once, when the watcher starts. First-level folders can only be created by the administrator from the server shell, since SMB clients and the web panel are blocked at the share root. After creating one, run --stop and --start so the new folder is monitored.
|
smbwatch.sh vigila en tiempo real las carpetas de primer nivel y su contenido mediante inotifywait.Si una carpeta supera el límite configurado, mueve a .recycle/smbwatch/<AAAAMMDD>/ los archivos que acaban de terminar de escribirse o que acaban de llegar. Este canal es independiente de .recycle/smbguest/ y .recycle/www-data/. Consulta la sección Recycle bin channels.smbwatch.sh se administra de forma independiente del instalador, mediante cinco acciones: --install, --uninstall, --start, --stop y --status.--install solicita los dos valores, registra el inicio automático con @reboot y arranca el monitor. Requiere una terminal interactiva y se ejecuta una vez. --uninstall pide confirmación antes de eliminar la entrada de cron, detener el monitor y borrar esos dos valores.Advertencia: No modifiques smbstack.env hasta que termine la desinstalación de SMBwatch.--start nunca escribe: valida las claves y lanza el vigilante. Si falta una clave o es inválida, aborta nombrando cada fallo e indicando que se ejecute --install primero. Esta es la acción que cron ejecuta en cada arranque, y la que usa smbload.sh para reiniciar un vigilante detenido.La lista de carpetas se construye una sola vez, al arrancar el vigilante. Las carpetas de primer nivel solo las crea el administrador desde la consola del servidor, porque los clientes SMB y el panel web no pueden escribir en la raíz del recurso. Después de crear una, ejecuta --stop y --start para que quede vigilada.
|
smbstack.env variable |
Default | Purpose | Propósito |
|---|---|---|---|
WATCH_LIMIT_GB |
10 |
Size limit per monitored folder, in GB | Límite de tamaño por carpeta monitoreada, en GB |
WATCH_EXCLUDE |
NONE |
Comma-separated folder names excluded from monitoring (e.g. FINANCE,LEGAL) |
Nombres de carpetas separados por comas excluidas del monitoreo |
WATCH_ROOT_ALLOW |
DEMO,DEMO2,demo.url |
Optional; --install writes DEMO, the folder created by smbsetup.sh, plus two samples of the format. Replace them with the real names. Comma-separated folders and files allowed in the share root (e.g. FINANCE,LEGAL,SWIM.url). Anything else that appears there is moved to the recycle bin. Names must be 1–255 ASCII characters: start with a letter or digit; then letters, digits, internal spaces, hyphens, underscores and dots. No trailing space or dot. Hidden names, non-ASCII characters, paths, wildcards and control characters are rejected. Separate names with commas, without surrounding spaces or empty entries. Matching is case-sensitive. An invalid list prevents startup; the warning identifies the entry number. Examples are not created automatically. Empty or missing: the root guard is off |
Opcional; --install escribe DEMO, la carpeta que crea smbsetup.sh, y dos ejemplos del formato. Reemplázalos por los nombres reales. Carpetas y archivos separados por comas permitidos en la raíz del recurso (p. ej. FINANCE,LEGAL,SWIM.url). Todo lo demás que aparezca ahí se mueve a la papelera. Los nombres deben tener entre 1 y 255 caracteres ASCII: empezar por letra o número; después pueden contener letras, números, espacios internos, guiones, guiones bajos y puntos. No pueden terminar en espacio ni punto. Se rechazan nombres ocultos, caracteres no ASCII, rutas, comodines y caracteres de control. Separe los nombres con comas, sin espacios alrededor ni elementos vacíos. Se distinguen mayúsculas y minúsculas. Una lista inválida impide el arranque; el aviso identifica el número de elemento. Los ejemplos no se crean automáticamente. Vacía o ausente: la vigilancia de la raíz queda apagada |
WATCH_ROOT_SYSTEM |
.Trash-*,System Volume Information,$RECYCLE.BIN,lost+found,.Trashes,.Spotlight-V100,.fseventsd,.TemporaryItems,LOST.DIR,.android_secure |
Required; --install writes it. Comma-separated system folders of Windows, Linux, macOS and Android in the share root. smbwatch never moves, measures or reports them. Names may be hidden; a trailing * matches any name that starts with the text before it (e.g. .Trash-*). Paths, commas and control characters are rejected. Missing or empty: --start aborts |
Obligatoria; --install la escribe. Carpetas de sistema de Windows, Linux, macOS y Android en la raíz del recurso, separadas por comas. smbwatch nunca las mueve, mide ni informa. Se admiten nombres ocultos; un * final coincide con cualquier nombre que empiece por el texto anterior (p. ej. .Trash-*). Se rechazan rutas, comas y caracteres de control. Ausente o vacía: --start aborta |
SMB clients cannot write in the share root, but the owner of the root and root can, for example a sync tool running on the server. With WATCH_ROOT_ALLOW set, the watcher moves any new folder or file of the root that is not in that list to .recycle/smbwatch/<YYYYMMDD>/. Entries already present at start are not moved; each one that is not in the list is reported with a WARNING. A listed name missing from the root, or an empty key, is reported too. .recycle is always allowed, and the names in WATCH_ROOT_SYSTEM are never moved or reported.To add a new folder or file to the root: add its exact name to WATCH_ROOT_ALLOW, run --stop and --start, and then create it.
|
Los clientes SMB no pueden escribir en la raíz del recurso, pero el dueño de la raíz y root sí, por ejemplo una herramienta de sincronización que corre en el servidor. Con WATCH_ROOT_ALLOW definida, el vigilante mueve a .recycle/smbwatch/<AAAAMMDD>/ cualquier carpeta o archivo nuevo de la raíz que no esté en esa lista. Lo que ya existe al arrancar no se mueve; cada entrada que no esté en la lista se informa con un WARNING. También se informa un nombre de la lista que no exista en la raíz, o la clave vacía. .recycle siempre está permitida, y los nombres de WATCH_ROOT_SYSTEM nunca se mueven ni se informan.Para agregar una carpeta o archivo nuevo en la raíz: escribe su nombre exacto en WATCH_ROOT_ALLOW, ejecuta --stop y --start, y luego créalo.
|
2026-11-13 10:00:00 INFO: root guard on: 6 allowed name(s)
2026-11-13 10:00:00 WARNING: allowed but not in root: HACINEDA -alert
2026-11-13 10:00:00 WARNING: in root but not allowed: suelto.txt -alert
2026-11-13 10:05:12 INFO: moved from root to recycle: intruso.txt
2026-11-13 10:00:00 WARNING: WATCH_ROOT_ALLOW not set, root guard off -alert
| The watcher checks a file when writing finishes or when the file arrives by a move or rename. This prevents a file moved from an excluded folder from bypassing the limit. Renaming a file inside a folder that is already over the limit also sends it to the recycle bin. Moving an entire folder is not monitored. | smbwatch revisa los archivos cuando termina su escritura o cuando llegan por movimiento o renombrado; por eso, mover un archivo desde una carpeta excluida no evita el límite. Si renombras un archivo dentro de una carpeta que ya superó el límite, también se moverá a la papelera. El monitor no detecta el traslado de una carpeta completa. |
# Install (interactive: asks for the limit and the exclusions, writes the four
# WATCH keys, adds the @reboot cron entry and starts the watcher). Run this
# once, from a terminal.
sudo /etc/smbstack/tools/smbwatch.sh --install
# Start
sudo /etc/smbstack/tools/smbwatch.sh --start
# Stop
sudo /etc/smbstack/tools/smbwatch.sh --stop
# Status (reports whether the watcher is running)
sudo /etc/smbstack/tools/smbwatch.sh --status
# Uninstall (asks for confirmation, stops it, removes the cron entry and the four keys)
sudo /etc/smbstack/tools/smbwatch.sh --uninstall
--start on a host where --install was never run reports every missing key and then aborts. It collects all the failures first, so one pass is enough to fix them:
|
--start en un host donde nunca se ejecutó --install informa cada clave que falta y luego aborta. Recoge todos los fallos primero, así una sola pasada basta para corregirlos:
|
2026-10-17 12:00:00 WARNING: WATCH_EXCLUDE missing line -alert
2026-10-17 12:00:00 WARNING: WATCH_ROOT_SYSTEM missing line -alert
2026-10-17 12:00:00 WARNING: WATCH_LIMIT_GB missing line -alert
2026-10-17 12:00:00 ERROR: [1/2] 3 key(s) invalid in smbstack.env
2026-10-17 12:00:00 ERROR: [2/2] run 'smbwatch.sh --install' first -abort
After an update. smbsetup.sh --update replaces smbwatch.sh but never edits smbstack.env. An installation made before WATCH_ROOT_SYSTEM existed lacks that key, so --start aborts and smbload.sh logs smbwatch restart FAILED every 5 minutes. Add the line to /etc/smbstack/smbstack.env, inside the SMBWATCH block, with the default value from the table above. Then run smbwatch.sh --start, or wait for smbload.sh to start it. Running smbwatch.sh --install also adds the key, but asks again for the limit and the exclusions.
|
Después de una actualización. smbsetup.sh --update reemplaza smbwatch.sh pero nunca edita smbstack.env. Una instalación hecha antes de que existiera WATCH_ROOT_SYSTEM no tiene esa clave, así que --start aborta y smbload.sh registra smbwatch restart FAILED cada 5 minutos. Agrega la línea a /etc/smbstack/smbstack.env, dentro del bloque SMBWATCH, con el valor por defecto de la tabla anterior. Luego ejecuta smbwatch.sh --start, o espera a que smbload.sh lo arranque. Ejecutar smbwatch.sh --install también añade la clave, pero vuelve a preguntar el límite y las exclusiones.
|
2026-10-17 12:00:00 INFO: Stopping smbwatch...
2026-10-17 12:00:00 INFO: SMBwatch status...
The list of monitored folders is built once, when smbwatch starts. First-level folders can only be created by the administrator from the server shell, since SMB clients and the web panel cannot create them at the root of the shared folder.After adding a folder, restart smbwatch (--stop and then --start) so that it is included in the monitoring.
|
La lista de carpetas monitoreadas se genera una sola vez al iniciar smbwatch. Las carpetas de primer nivel solo pueden ser creadas por el administrador desde el shell del servidor, ya que los clientes SMB y el panel web no pueden crearlas en la raíz de la carpeta compartida.Después de agregar una carpeta, reinicia smbwatch (--stop y luego --start) para que quede incluida en el monitoreo.
|
installregisters the reboot entry;uninstallremoves it.stopstops the current watcher.smbload.shcan restart it during its next check.
installregistra el arranque automático;uninstalllo retira.stopdetiene el monitor actual.smbload.shpuede reiniciarlo durante su próxima comprobación.
| Description | Descripción |
|---|---|
smbbk.sh creates a single compressed archive with SMBstack's configuration. It contains:
|
smbbk.sh crea un único archivo comprimido con la configuración de SMBstack. Contiene:
|
smbbk.sh reads BACKUP_DIR from smbstack.env (Backup block). It must be /etc/bak/smbstack, a directory exclusive to smbbk.sh. Any other value aborts before anything is created, written or deleted. After publishing the archive, other contents are deleted and the three most recent archives are kept. |
smbbk.sh lee BACKUP_DIR de smbstack.env (bloque Backup). Debe ser /etc/bak/smbstack, un directorio exclusivo de smbbk.sh. Cualquier otro valor aborta antes de crear, escribir o borrar nada. Tras publicar el respaldo, se elimina el resto del contenido y se conservan los tres respaldos más recientes. |
Backs up SMBstack into /etc/bak/smbstack/smbbk_<YYYYMMDD_HHMMSS>.zip, keeping up to 3 archives. Paths that do not exist are skipped. Restore by unzipping it over /. |
Respalda SMBstack en /etc/bak/smbstack/smbbk_<YYYYMMDD_HHMMSS>.zip, conservando hasta 3 comprimidos. Las rutas que no existan se omiten. Para restaurar, descomprímalo sobre /. |
| Command | Description | Descripción |
|---|---|---|
sudo bash smbbk.sh |
Create a backup now | Crear una copia ahora |
sudo bash smbbk.sh --install |
Register the @monthly cron entry |
Registrar la entrada mensual en cron |
sudo bash smbbk.sh --uninstall |
Remove the cron entry, keeping the archives | Quitar la entrada de cron, conservando los comprimidos |
| This project uses two kinds of backup, with different purposes and rules. | Este proyecto utiliza dos tipos de respaldo, con propósitos y reglas diferentes. |
| Type | Description | Descripción |
|---|---|---|
| Project backup / Respaldo de proyecto | It is a copy of SMBstack's configuration intended for the administrator. It is stored in /etc/bak/smbstack, includes a timestamp in its name and up to three copies are kept.Only smbbk.sh creates project backups. smbsetup.sh --update runs smbbk.sh before overwriting the application code, instead of keeping a copy of its own. |
Es una copia de la configuración de SMBstack destinada al administrador. Se almacena en /etc/bak/smbstack, incluye una marca de tiempo en el nombre y se conservan hasta tres copias.Solo smbbk.sh genera respaldos de proyecto. smbsetup.sh --update ejecuta smbbk.sh antes de sobrescribir el código de la aplicación, en lugar de mantener una copia propia. |
| Routine-operation backup / Respaldo de operación rutinaria | It is the copy a script takes of one specific file right before modifying it, to allow the change to be undone. It is stored next to the original file with the .bak suffix, and only one copy is kept, overwritten on every run.Some examples are smb.conf.bak, rsyslog.conf.bak and smbd.service.bak. |
Es una copia que un script realiza de un archivo concreto justo antes de modificarlo, para permitir deshacer el cambio. Se almacena junto al archivo original con el sufijo .bak y solo se conserva una copia, que se sobrescribe en cada ejecución.Algunos ejemplos son smb.conf.bak, rsyslog.conf.bak y smbd.service.bak. |
Project log: /var/log/smbstack.log. Installation and update configure weekly rotation in /etc/logrotate.d/smbstack, keeping seven previous files plus the active log. Compression starts on the next rotation. Empty logs are not rotated; missing logs are tolerated.
|
Log del proyecto: /var/log/smbstack.log. La instalación y la actualización configuran rotación semanal en /etc/logrotate.d/smbstack. Se conservan siete archivos anteriores y el activo. La compresión comienza en la siguiente rotación. Los logs vacíos no se rotan; los ausentes se toleran.
|
|
NetBIOS is a legacy protocol with security limitations, among them unauthenticated name resolution and exposure to spoofing and name poisoning attacks, such as NBT-NS poisoning. For this reason, NetBIOS remains disabled by default through disable netbios = yes in smb.conf, and the installer offers no option to enable it.Environments that need compatibility with legacy Windows clients must enable NetBIOS manually after the installation. |
NetBIOS es un protocolo legado que presenta limitaciones de seguridad, entre ellas la resolución de nombres sin autenticación y la exposición a ataques de suplantación y envenenamiento de nombres, como NBT-NS poisoning. Por este motivo, NetBIOS permanece deshabilitado de forma predeterminada mediante disable netbios = yes en smb.conf, y el instalador no ofrece ninguna opción para activarlo.Los entornos que necesiten compatibilidad con clientes Windows antiguos deben habilitar NetBIOS manualmente después de la instalación. |
# Enable NetBIOS in smb.conf
sudo sed -i 's/^\s*disable netbios\s*=.*/ disable netbios = no/' /etc/samba/smb.conf
sudo sed -i "s/^;\s*netbios name\s*=.*/ netbios name = YOUR_HOSTNAME/" /etc/samba/smb.conf
# Start nmbd
sudo systemctl enable --now nmbd.service
sudo systemctl restart smbd
# Open the required ports (adjust IFACE to your Samba interface)
sudo iptables -A INPUT -i IFACE -p udp -m multiport --dports 137,138 -j ACCEPT
sudo iptables -A FORWARD -i IFACE -p udp -m multiport --dports 137,138 -j ACCEPT
sudo iptables -A INPUT -i IFACE -p tcp --dport 139 -j ACCEPT
sudo iptables -A FORWARD -i IFACE -p tcp --dport 139 -j ACCEPT
# Optional: rotate nmbd's log
sudo tee -a /etc/logrotate.d/samba > /dev/null <<'EOF'
/var/log/samba/log.nmbd {
weekly
missingok
rotate 7
postrotate
systemctl reload nmbd 2>/dev/null || true
endscript
compress
delaycompress
notifempty
}
EOF
Every cron entry of the project lives in /etc/cron.d/smbstack. smbsetup.sh, tools/smbwatch.sh, tools/smbreport.sh and tools/smbbk.sh add or remove their own line in that file.Each line names the user that runs the task, as required by the /etc/cron.d format. The scripts add or remove only their own entries in /etc/cron.d/smbstack.--uninstall deletes the file.
|
Todas las entradas de cron del proyecto viven en /etc/cron.d/smbstack. smbsetup.sh, tools/smbwatch.sh, tools/smbreport.sh y tools/smbbk.sh agregan o eliminan su propia línea en ese archivo.Cada línea indica el usuario que ejecutará la tarea, como requiere el formato de /etc/cron.d. Los scripts agregan o eliminan únicamente sus propias entradas en /etc/cron.d/smbstack.--uninstall elimina el archivo.
|
Each view can be opened in two ways:
|
Cada vista puede abrirse de dos maneras:
|
The audit view is one of the three tabs of the web panel. It is accessed through http://localhost:3092/?tab=audit.The audit view reads /var/log/samba/log.audit and its rotated files. smbapi.php returns the records as JSON. The maximum number returned per request is set by MAX_LOG_LINES in smbstack.env.Date, IP, action and text filters are applied in the browser to the records already received. You can view the results in pages of 50, 100, 200 or 500 records. The Export PDF button opens the browser's print window with three columns: date and time, IP and file. You can save or print the document there; the server does not generate the PDF. |
La vista de auditoría es una de las tres pestañas del panel web. Se accede mediante http://localhost:3092/?tab=audit.La vista consulta /var/log/samba/log.audit y sus archivos rotados. smbapi.php lee los registros y los entrega en formato JSON. El máximo por petición se configura con MAX_LOG_LINES en smbstack.env.Los filtros de fecha, IP, acción y texto se aplican en el navegador a los registros recibidos. Puedes ver los resultados en páginas de 50, 100, 200 o 500 registros. El botón Export PDF abre la ventana de impresión del navegador con tres columnas: fecha y hora, IP y archivo. Desde allí puedes guardar o imprimir el documento; el servidor no genera el PDF. |
The web panel is an Apache VirtualHost listening on port 3092. It is accessed through http://localhost:3092/ and has three tabs: Shared, Audit and Report. Each tab corresponds to a separate page, which index.php loads inside a frame.The Shared tab displays the contents of the shared folder. From there a document can be opened, downloaded or moved to the recycle bin. The root of the shared folder is read-only: you cannot upload files, create folders or delete items there. These actions are available inside subfolders. Apache runs the panel as the www-data user, which receives read and write permissions on the shared folder through an ACL set during the installation.The light and dark themes are selected from the top bar. The selection is stored in the browser and applied to the three tabs. |
El panel web es un VirtualHost de Apache que escucha en el puerto 3092. Se accede mediante http://localhost:3092/ y tiene tres pestañas: Shared, Audit y Report. Cada pestaña corresponde a una página independiente, que index.php carga dentro de un marco.La pestaña Shared muestra el contenido de la carpeta compartida. Desde allí se puede abrir un documento, descargarlo o moverlo a la papelera de reciclaje. La raíz de la carpeta compartida es de solo lectura: desde allí no puedes subir archivos, crear carpetas ni eliminar elementos. Estas acciones están disponibles dentro de las subcarpetas. Apache ejecuta el panel como el usuario www-data, que recibe permisos de lectura y escritura sobre la carpeta compartida mediante una ACL establecida durante la instalación.Los temas claro y oscuro se seleccionan desde la barra superior. La selección se guarda en el navegador y se aplica a las tres pestañas. |
|
|
The report view is the third tab of the web panel. It is accessed through http://localhost:3092/?tab=report.It contains three tables: the thirty extensions with the largest total size, the thirty folders with the largest total size, and the fifty largest files, with their full path. The extensions table includes the file count, the average size and the share they represent of the total. tools/smbreport.sh walks the shared folder as root and saves the results in a JSON file. Cron runs the script daily at 03:00. Because the walk can take several minutes and use the disk while SMB clients are working, it is scheduled outside working hours.The view requests the data from smbapi.php; it does not scan the disk. Until smbreport.sh completes its first scan, the tab reports that no report is available.The report excludes the recycle bin, so its files do not appear in the tables. The JSON file is also unavailable over HTTP: it does sit inside Apache's web root, but smbweb.conf denies it with a <Files smbreport.json> block, so only smbapi.php reads it directly from disk.
|
La vista de informe es la tercera pestaña del panel web. Se accede mediante http://localhost:3092/?tab=report.Contiene tres tablas: las treinta extensiones con mayor tamaño total, las treinta carpetas con mayor tamaño total y los cincuenta archivos más grandes, con su ruta completa. La tabla de extensiones incluye el número de archivos, el tamaño promedio y la proporción que representan sobre el total. tools/smbreport.sh recorre la carpeta compartida como root y guarda los resultados en un archivo JSON. Cron ejecuta el script cada día a las 03:00. Como el recorrido puede tardar varios minutos y usar el disco mientras trabajan los clientes SMB, se programa fuera del horario laboral.La vista solicita los datos a smbapi.php; no recorre el disco. Hasta que smbreport.sh complete el primer recorrido, la pestaña indicará que aún no hay un informe disponible.El informe no incluye la papelera, por lo que sus archivos no aparecen en las tablas. El archivo JSON tampoco está disponible por HTTP: sí reside dentro de la raíz web de Apache, pero smbweb.conf lo deniega con un bloque <Files smbreport.json>, así que solo smbapi.php lo lee directamente del disco.
|
| Command | Description | Descripción |
|---|---|---|
sudo bash /etc/smbstack/tools/smbreport.sh |
Build the report now | Generar el informe ahora |
sudo bash /etc/smbstack/tools/smbreport.sh --install |
Register the daily cron entry | Registrar la entrada diaria en cron |
sudo bash /etc/smbstack/tools/smbreport.sh --uninstall |
Remove the cron entry, keeping the report | Quitar la entrada de cron, conservando el informe |
CSRF protection. web/smbshared.php has no login by design. Guest access is intentional, but the installer binds Apache to 127.0.0.1:3092, so the panel is reachable from the server itself or through a local tunnel, not directly from the LAN.What it does have is a per-session token on the four forms that change state: upload, new folder, new file and recycle. A POST is accepted only if the page was actually loaded first. This blocks a malicious site from silently auto-submitting a form to your server through a visitor's browser. It does not restrict who can use the browser itself: that is still governed by network reachability, LAN or tunnel. |
Protección CSRF. web/smbshared.php no tiene login por diseño. El acceso de invitado es intencional, pero el instalador enlaza Apache a 127.0.0.1:3092, así que el panel es accesible desde el propio servidor o mediante un túnel local, no directamente desde la LAN.Lo que sí tiene es un token por sesión en los cuatro formularios que modifican estado: subir, nueva carpeta, nuevo archivo y papelera. Un POST se acepta solo si la página se cargó antes. Esto impide que un sitio malicioso envíe en silencio un formulario a su servidor a través del navegador de un visitante. No restringe quién puede usar el navegador: eso lo sigue gobernando el alcance de red, LAN o túnel. |
Folder size display. The total size shown for the folder being browsed in web/smbshared.php is cached for 30 seconds per path, to avoid re-walking a potentially large subtree on every page load.The number can therefore lag up to 30 seconds behind the real content. That is purely cosmetic: quota enforcement is handled independently by smbwatch.sh and its own size checks, not by this displayed value.
|
Tamaño de carpeta mostrado. El tamaño total que se muestra para la carpeta que se está navegando en web/smbshared.php se cachea 30 segundos por ruta, para evitar recorrer un subárbol potencialmente grande en cada carga de página.Por eso el número puede quedar hasta 30 segundos desactualizado respecto al contenido real. Es puramente cosmético: el cumplimiento de la cuota lo maneja de forma independiente smbwatch.sh con sus propios chequeos de tamaño, no este valor mostrado.
|
| This project is designed for use on a local network (LAN). It does not include the security hardening needed for direct exposure to the internet. If internet access is required, an on-demand tunnel is recommended instead of opening ports directly. This enables access when needed without leaving the server permanently exposed. | Este proyecto está diseñado para usarse en una red local (LAN). No cuenta con las medidas de seguridad necesarias para exponerlo directamente a Internet. Si se requiere acceso desde Internet, se recomienda utilizar un túnel bajo demanda en lugar de abrir puertos directamente. Así, el acceso se habilita cuando hace falta y el servidor no queda expuesto permanentemente. |
Optional tunnel:
This repository
|
Este repositorio
|
|
|
| This project uses a dual-licensing model to balance software freedom with content protection: | Este proyecto utiliza un modelo de licencia dual para equilibrar la libertad del software con la protección del contenido: |
| Content | Licensed Under |
|---|---|
| Scripts, Binaries, Infrastructure | |
| RAG, Workers, Specialized Modules, Docs |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.






