Mostrando las entradas con la etiqueta scripting. Mostrar todas las entradas
Mostrando las entradas con la etiqueta scripting. Mostrar todas las entradas

viernes, 5 de octubre de 2012

Windows - net user options


You can use the following parameters with the net user command:
  • username
    Is the name of the user account you want to add, delete, modify, or view. The name of the user account can have as many as 20 characters.
  • password
    Assigns or changes a password for the user's account. A password must satisfy the minimum length set with the/minpwlen option of the net accounts command. It can contain as many as 14 characters.
  • *
    Produces a prompt for the password. The password is not displayed when you type it at a password prompt.
  • /domain
    Performs the operation on the primary domain controller (PDC) of the current domain. This parameter applies only to computers running Windows NT Workstation that are members of a Windows NT Server domain. By default, Windows NT Server-based computers perform operations on the PDC.
  • /add
    Adds a user account to the user accounts database.
  • /delete
    Removes a user account from the user accounts database.

Options for the Net User Command

  • /active:{yes | no}
    Activates or deactivates the account. If the account is not active, the user cannot gain access to the server. The default is yes.
  • /comment:"text"
    Provides a descriptive comment about the user's account (maximum of 48 characters). Be sure to put quotation marks around the text you use.
  • /countrycode:nnn
    Uses the operating system country code to implement the specified language files for a user's help and error messages. A value of 0 signifies the default country code.
  • /expires:{date | never}
    Causes the account to expire if date is set. The never option sets no time limit on the account. An expiration date is in the form mm/dd/yy or dd/mm/yy, depending on the country code. Months can be a number, spelled out, or abbreviated with three letters. Year can be two or four numbers. Use slashes (/) with no spaces to separate parts of the date.
  • /fullname:"name"
    Is a user's full name (rather than a user name). Enclose the name in quotation marks.
  • /homedir:pathname
    Sets the path for the user's home directory. The path must exist.
  • /passwordchg:{yes | no}
    Specifies whether users can change their own password. The default is yes.
  • /passwordreq:{yes | no}
    Specifies whether a user account must have a password. The default is yes.
  • /profilepath[:path]
    Sets a path for the user's logon profile.
  • /scriptpath:pathname
    Is the location of the user's logon script.
  • /times:{times | all}
    Is the logon hours. The times option is expressed as day[-day][,day[-day]],time[-time][,time [-time]], and is limited to 1-hour increments. Days can be spelled out or abbreviated. Hours can be 12-hour or 24-hour notation. For 12-hour notation, use am, pm, a.m., or p.m. The all option specifies that a user can always log on, and a blank value specifies that a user can never log on. Separate day and time entries with a comma, and separate multiple day and time entries with a semicolon.
  • /usercomment:"text"
    Lets an administrator add or change the user comment for the account.
  • /workstations:{computername[,...] | *}
    Lists as many as eight computers from which a user can log on to the network. If the /workstations option has no list or if the list is *, the user can log on from any computer.
  • net help user | more
    Displays Help one screen at a time.


jueves, 4 de octubre de 2012

Export Audit Policy Configuration - Windows


secedit command allows to export Security policy configurations besides other acctions.

The possible actions are:
  • configure 
  • analyze
  • import
  • export
  • validate
  • generaterollback
To use secedit you must have a Security Database.

To create a Security Database (sdb) you must:
  1. open "mmc" (from start>run just type "mmc")
  2. click on File > add/remove snap-in
  3. Select "Security configuration and analysis"
  4. Button "Add" & "OK"
  5. Right click & New database & Select a name for the database & click open
  6. Define the policies you would like to export (define any value if you only need to export the configuration. define the propper values if you like to analyze)
  7.  
psexec @filserver.txt secedit /export /db security.sdb /areas SECURITYPOLICY GROUP_MGMT  GROUP_MGMT  GROUP_MGMT GROUP_MGMT  GROUP_MGMT /cfg output.txt >> outputLog.txt

psexec is used to run this command in several computers. The @filserver.txt file contains a list computers / servers.

viernes, 23 de diciembre de 2011

Unix Scripting: Create users

A continuación comparto un script simple para creación de usuarios en ambientes Unix:



HOME=/export/home
#/export/home


if [ $# -eq 4 ]
then
        echo "Creating user $1, nombre $2"
else
        echo "Usage:$0 <\"username\"> <\"Descripcion\"> <\"grupo\"> <\"UID\"> "
    #echo "    groups:"
    #echo "      lista separada por comas de los grupos a los que pertenecerá"
        exit 1
fi


user=$1
nombre=$2
grupos=$3
uid=$4


sudo /usr/sbin/useradd -c "$nombre" -g $grupos -m -d $HOME/$user -s /bin/sh -u $uid $user
if [ $? -ne 0 ]
then
        exit 1
fi


echo "Setting Password"
sudo /usr/bin/passwd $user
sudo /usr/sbin/usermod -f 90 $user
sudo /usr/bin/passwd -n 7 -x 30 -w 7 -f $user
sudo /usr/bin/passwd -f $user
echo "The user $user has been created"

martes, 27 de septiembre de 2011

How to force WSUS updates to install on a computer

LA forma de fozar a un computer (workstation o server) a que se comunique con WSUS y descargue los paquetes que tiene pendientes de instalación es reiniciando los servicios que utiliza WSUS:

Desde un CMD ejcutar lo siguiente:

net stop "windows installer"
net start "windows installer"
net stop "
automatic updates"
net start "automatic updates"
net stop "background intelligent Transfer Service"
net start "background intelligent Transfer Service"



Si quieren hacer un vbscript puede hacerlo de la siguiente forma:

'Iniciar servicios de Windows Update
WSHShell.run "cmd.exe /K net stop ""windows installer"" & net start ""windows installer"" & exit", 1, true
WSHShell.run "cmd.exe /K net stop ""automatic updates"" & net start ""automatic updates"" & exit", 1, true
WSHShell.run "cmd.exe /K net stop ""background intelligent Transfer Service"" & net start ""background intelligent Transfer Service"" & exit", 1, true



Para ver el log de windows update y chequear los mensajes, desde Inicio > Ejecutar peguen esto:

notepad %WinDir%\WindowsUpdate.log

miércoles, 31 de agosto de 2011

Listar grupos y usuarios a un txt

Para listar el contenido de un grupo local de una workstation o server, podemos ejecutar el siguiente comando:


Net localgroup administrators > %temp%\lstUsersAdministrators.txt


Para hacerlo en un equipo distinto del que estamos trabajando podemos ayudarnos de la tool psexec:


psexec.exe \\Target net localgroup administrators > %temp%\lstUsersAdministrators.txt




Para listar todos los usuarios de una workstation o server, podemos ejecutar el siguiente comando:


Net users > %temp%\lstUsers.txt

Copiar una estructura de carpetas sin su archivos

Este post es bastante simple y directo... como armar una estructura de carpetas vacia copiando otra que esta llena de archivo???


Muy simple:


xcopy pathOrigen pathDestino /t /e /i


enjoy!

Error on cacls

Como resolver el siguiente error que arroja cacls: The data area passed to a system call is too small.  ???


Muy simple....
El error se debe a que la cadena pasada es muy larga y el límite es 254 caracteres


por ejemplo use este comando que da permisos de lectura al grupo group:


cacls "E:\Share\propuestas\especiales\ " /E /C /T /G  dominio\group:R

y cuando llega a este archivo da error y no aplica los permisos:

E:\Share\propuestas\especiales\1-Gestao\Biblioteca\5 - Ingenieria_Pre-Ventas\03 - Competitividades\Comparativo de Ecuanos\Acesso\Wireless\Sinalas - Sucalata\LAP 1131 e WLC 4400 - KOJNE234 – Petrecasa\RPP - ET-0663.32-5517-762-PPT-001 - Equipamento WLAN.xls

y que da este error:
The data area passed to a system call is too small

Esta es una solución a este problema de path extensos al usar cacls:
Hay que acortar el path usando una substitución:



Antes:
cacls "E:\Share\propuestas\especiales\ " /E /C /T /G  dominio\group:r

Despues:
subst X: "E:\Share\propuestas\especiales"
cacls X: /E /C /T /G  dominio\group:r


Auditing file server permissions with cacls on Windows


Un método alternativo para listar permisos de Filesystem sin usar DUMPSEC.
Esta opción es nativa de Windows por lo que no requiere instalación alguna. Es una herramienta simple y rápida.

Pueden usar este comando directamente en un cmd para listar los permisos de un directorio y sus subdirectorios:

cacls e:\share /T /C /E > permissions_share_20100706.txt

Si lo quieren ejecutar para varios equipos en forma remota puede hacerlo usando el Psexec:

Ejemplo
psexec \\207.169.84.13 net cacls e:\share /T /C /E >> permissions_share_20100706.txt

El utilitario cacls tiene algunas falencias, por lo que Microsoft desarrollo el icacls a partir de Windows Vista.

El procedimiento con cacls que es un comando estándar y que lo pueden aplicar en cualquier equipo Windows 2003 Server.

  1. brir CMD
  2.     Pararse sobre la raíz del directorio que queremos analizar
  3.     Ejecutar el comando cacls . /T /C /E > c:\ACLLog.txt
  4.     Analizar el archivo para ver que diferencias hay en los permisos.


La herramienta CACLS no tiene una salida que permita fácilmente ordenar en columnas la salida, pero es muy rápida para generar la salida.
Donde tengan muchas subcarpetas es más recomendable usar Hyena o Dumpsec.

PD: Si tuvieran que agregar permisos en muchas subcarpetas se puede usar el cacls para hacer modificaciones.

Ejemplo:
cacls x:\carpeta /G grupo:W

/G user:perm  Grant specified user access rights.
              Perm can be: R  Read
                           W  Write
                           C  Change (write)
                           F  Full control






Aqui toda la configuración completa:

 Displays or modifies access control lists (ACLs) of files

 CACLS filename [/T] [/M] [/L] [/S[:SDDL]] [/E] [/C] [/G user:perm]
        [/R user [...]] [/P user:perm [...]] [/D user [...]]
    filename      Displays ACLs.
    /T            Changes ACLs of specified files in
                  the current directory and all subdirectories.
    /L            Work on the Symbolic Link itself versus the target
    /M            Changes ACLs of volumes mounted to a directory
    /S            Displays the SDDL string for the DACL.
    /S:SDDL       Replaces the ACLs with those specified in the SDDL string
                  (not valid with /E, /G, /R, /P, or /D).
    /E            Edit ACL instead of replacing it.
    /C            Continue on access denied errors.
    /G user:perm  Grant specified user access rights.
                  Perm can be: R  Read
                               W  Write
                               C  Change (write)
                               F  Full control
    /R user       Revoke specified user's access rights (only valid with /E).
    /P user:perm  Replace specified user's access rights.
                  Perm can be: N  None
                               R  Read
                               W  Write
                               C  Change (write)
                               F  Full control
    /D user       Deny specified user access.
 Wildcards can be used to specify more than one file in a command.
 You can specify more than one user in a command.

 Abbreviations:
    CI - Container Inherit.
         The ACE will be inherited by directories.
    OI - Object Inherit.
         The ACE will be inherited by files.
    IO - Inherit Only.
         The ACE does not apply to the current file/directory.
    ID - Inherited.
         The ACE was inherited from the parent directory's ACL.


Dumpsec command line Auditing Tool for Windows

Dumpsec es una herramienta para auditoría en Windows. Es usada frecuentemente para generar reportes de permisos en file system, usuarios, grupos, registry, etc.


Aca les paso los comandos de Dumpsec que pueden usar para agilizar cualquier necesidad de auditoría.
Tienen que ejecutarlo con un CMD parados en el dir donde este el Dumpsec.exe

Desde este link pueden descargar las tools imprecindibles de la gente de SystemTools -  www.systemtools.com

Dumpsec /rpt=dir=c:\ /saveas=csv /outfile=c:\temp\dirC.txt
Dumpsec /rpt=dir=d:\ /saveas=csv /outfile=c:\temp\dirD.txt
Dumpsec /rpt=dir=e:\ /saveas=csv /outfile=c:\temp\dirE.txt

Dumpsec /rpt=userscol /saveas=csv /outfile=C:\temp\userscol.txt
Dumpsec /rpt=Groupscol /saveas=csv /outfile=C:\temp\GroupsCol.txt
Dumpsec /rpt=groups /saveas=csv /outfile=C:\temp\Groups.csv
Dumpsec /rpt=Groupsonly /saveas=csv /outfile=C:\temp\GroupsOnly.csv

Dumpsec /rpt=rights /saveas=csv /outfile=C:\temp\Rights.txt
Dumpsec /rpt=services /saveas=csv /outfile="C:\temp\" + %computername% + "_Services.txt"
Dumpsec /rpt=allsharedirs /saveas=csv /outfile=C:\temp\Allshares.txt
Dumpsec /rpt=shares /saveas=csv /outfile=C:\temp\shares.txt
Dumpsec /rpt=Policy /saveas=csv /outfile=C:\temp\Policy.txt
Dumpsec /rpt=registry=HKEY_LOCAL_MACHINE /saveas=csv /outfile=C:\temp\RegistryMachine.txt
Dumpsec /rpt=registry=HKEY_USERS /saveas=csv /outfile=C:\temp\RegistryUser.txt
Dumpsec /rpt=printers /saveas=csv /outfile=C:\temp\Printers.txt

customizable
-------------
Dumpsec /rpt=share=sharename            Specific shared directory permissions report



Mas info:


Required parameters

/rpt=report type              Type of report to produce:
dir=drive:\path Directory permissions report (drive letter path)
dir=\\computer\sharepath         Directory permissions report (UNC path)
registry=hive     Registry permissios report (hive can be HKEY_LOCAL_MACHINE or HKEY_USERS)
share=sharename           Specific shared directory permissions report
allsharedirs         All non-special shared directories permissions report
printers                Printers permissions report
shares   Shares permissions report
users     Users report (table format, all fields except groups, groupcomment and grouptype)
usersonly            Users report (table format, only username, fullname and comment fields)
userscol               Users report (column format, same fields as users report)
groups  Groups report (table format, all fields)
Groupsonly        Groups report (table format, group info, no user info)
Groupscol           Groups report (column format, same fields as groups report)
Policy    Policy report
rights     Rights report
services                Services report
/outfile=drive:\path       File in which to store report. This file will be replaced if it already exists.
Optional parameters for all reports


/computer=computer   Computer for which to dump information. Ignored for directory reports (since computer is implied by computer associated with redirected drive). Default is to dump local information.
/saveas=format                Fomat in which to store report:
native   binary format, can be loaded back into Somarsoft DumpSec
csv          comma separated columns
tsv          tab separated columns
fixed      fixed width columns, padded with blanks
Default is to save as native format.
/noheader          Do not include timestamp and other header information in saved report. Default is to include this information.
Optional parameters for permissions reports only


/noowner           Do not dump owner. Default is to dump owner.
/noperms            Do not dump permissions. Default is to dump permissions.
/showaudit         Dump audit info. Default is not to dump audit info. Ignored if audit information cannot be displayed because the current user is not a member of the Administrators group.
(only one of the following options can be specified)

/showexceptions             Show directories, files, and registry keys whose permissions differ from those of the parent directory or registry key. This is the default.
/showexcdirs     Show directories (but not files) whose permissions differ from those of the parent directory.
/showalldirs       Show all directories. Show only those files whose permissions differ from those of the parent directory.
/showdirsonly   Show all directories. Do not show any files.
/showall               Show all directories, files and registry keys.
Optional parameters for users/groups reports only


/showtruelastlogon        Query all domain controllers for "true" last logon time, which can be time consuming. Default is to use last logon time from specified computer.
/showosid           Dump SID as part of users report, which requires some additional and possible time-consuming processing. Default is not to dump SID.
/showcomputers             Show computer accounts in users reports. Default is only to show normal user accounts.
Examples:


DumpSec.exe c:\temp\users.dcl

Start Somarsoft DumpSec interactively, load and display a report that was previously saved in native format in c:\temp\users.dcl.


DumpSec.exe /rpt=dir=c:\users /showaudit /outfile=c:\temp\users.dcl

Run Somarsoft DumpSec batch mode, produce a report of directory permissions for the c:\users directory showing owner, permissions and audit settings and store the report in native file format in c:\temp\users.dcl. The report will show only those directories and files whose permissions or audit settings differ from those of parent directory.

DumpSec.exe /computer=\\server1 /rpt=users /saveas=csv /outfile=c:\temp\users.txt

Run Somarsoft DumpSec in batch mode, produce a report showing all user information in table format for users defined on \\server1, and store the report in comma separated columns format in c:\temp\users.txt.


DumpSec.exe /computer=\\server1 /rpt=share=sales /outfile=c:\temp\users.dcl /showalldirs

Run Somarsoft DumpSec in batch mode, produce a report of permissions for the \\server1\sales shared directory, showing owner and permissions but not audit settings, and store the report in native file format in c:\temp\users.dcl. The report will show all directories under the \\server1\sales tree, and only those files whose permissions differ from those of the parent directory.

lunes, 11 de abril de 2011

Script: Top ten de buenas prácticas

En este post voy a comentar las buenas prácticas que debemos tener en cuenta a la hora de realizar scripts, sobre todo en un ámbito empresarial.
Siempre que tenemos diversos sistemas operando es necesario realizar tareas repetitivas o simplemente aburridas que podemos delegarle a un script.

Como toda actividad siempre hay ciertos secretos que hay que conocer y que es bueno tener en cuenta.
Paso a enumerara la lista de "tips" que considero debemos tener en cuenta:

  1. Universal: Debe estar escrito en ingles para que pueda compartirse con cualquier "compañero" en el mundo. Incluso trabajando en una empresa pequeña, es bueno seguir estos patrones, ya que si el día de mañana pasamos a trabajar en otra empresa podemos utilizarlo y compartir facilmente.
  2. Especializado: Cada script debe realizar una función bien especifica de forma correcta. Es preferible tener dos o tres scripts para nuestras tareas que uno gran script que supuestamente hace todo. A la hora de modificarlo o debuguearlo puede convertirse en un problema.
  3. Auto describible: El nombre del archivo debe hablar por si solo, debe tener un nombre bien conciso y representativo de lo que realiza
  4. Versionado: Tanto en el interior como en el nombre del archivo, debemos incluir una versión, recomiendo utilizar la dominación vm.n (ejemplo: v0.1)
  5. Explicativo: Al abrir el script lo primero que debemos mostrar es: description, version, author, y de ser posible changeLog. La descipcion debe ser completa pero bien concisa, obviamente en inglés. Author incluye nombre completo e email. El changeLog en muy pocas palabras las modificaciones realizadas en cada versión.
  6. Parametrizado:Las variables que utilicemos en el script deben estar definidas al principio de script y con una valor asignado. También es bueno confirmar al usuario estas variables al ejecutar el mismo.
  7. Comentado: Cada bloque del script debe estar indicado para una fácil depuración y entendimiento del script.
  8. Enfocado: Arrancar a escribir un script siempre utilizando estas buenas prácticas desde cero.La realidad es que si no lo hacemos desde cero, cuando terminemos y el script este andando no vamos a querer modificarlo todo solo para agregarle cositas lindas. Si usamos estas buenas prácticas nos vamos a convencer de que es bueno usarlas desde el inicio.
  9. A prueba de errores: Siempre tener en mente mientras escribimos que las cosas pueden malir sal, por eso tengamos que cuenta esto y controlemos los posibles errores... tanto del usuario como del sistema o entorno.

Do!
  1. Compartirlos: muchas veces las mejoras ideas son de otros, hay que estar abiertos y compartir el trabajo, para que hacerle perder tiempo al resto con algo que ya alguien hizo?
Don´t!

  1. Inseguro: No poner contraseñas en los scripts, es tan simple como definir un input box para que el usuario la ingrese. En caso de que el script deba correr automáticamente podemos introducirla en forma de hash o utilizar clave publicas/privadas (según el SO donde los escribamos hay diferentes alternativas)