Guest User

mkusers.vbs

a guest
Mar 17th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 14.21 KB | None | 0 0
  1. ' mkusers.vbs
  2.  
  3. ' varie
  4. Const ForReading = 1, ForWriting = 2, ForAppending = 8
  5.  
  6. ' CDO
  7. Const cdoSendUsingPickup = 1, cdoSendUsingPort = 2
  8. Const cdoAnonymous = 0, cdoBasic = 1, cdoNTLM = 2
  9. Const cdoDSNDefault = 0, cdoDSNNever = 1, cdoDSNFailure = 2, cdoDSNSuccess = 4, cdoDSNDelay = 8, cdoDSNSuccessFailOrDelay = 14
  10.  
  11. ' usato per invio mail di notifica
  12. Const MAIL_SERV = ""    ' server SMTP
  13. Const MAIL_PORT = 25    ' porta
  14. Const MAIL_USER = ""    ' utente
  15. Const MAIL_PASS = ""    ' password
  16.  
  17. Const MAIL_FROM = ""    ' from per email
  18. Const MAIL_TO = ""      ' to per email
  19. Const MAIL_CC = ""      ' cc per email
  20. Const MAIL_BCC = ""      ' bcc per email
  21.  
  22. ' flags utente
  23. Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000
  24. Const ADS_UF_PASSWD_CANT_CHANGE = &h40
  25.  
  26. ' gruppo utenti (opzionale)
  27. Const GROUP_NAME = "Remote Desktop Users"
  28.  
  29. ' stringa connessione DB
  30. Const CONN_STR = "File Name=mkuser.udl"
  31.  
  32. ' debugging
  33. Const DEBUG_MODE = 0
  34.  
  35.  
  36. '__boot() {  
  37.  Dim args, fso, nExitCode
  38.   Dim gsLogFile
  39.  
  40.   On Error Resume Next  
  41.   Set args = WScript.Arguments
  42.   Set fso = CreateObject("Scripting.FileSystemObject")
  43.   gsLogFile = "log\mkuser-" & _
  44.               Right("0000" & Year(Now), 4) & Right("00" & Month(Now), 2) & Right("00" & Day(Now), 2) & "-" & _
  45.               Right("00" & Hour(Now), 2) & Right("00" & Minute(Now), 2) & ".log"
  46.  
  47.   nExitCode = main(args.Count, args)
  48.   If (nExitCode <> 0) Or (DEBUG_MODE = 1) Then
  49.     Call SendMail(MAIL_FROM,MAIL_TO,MAIL_CC,MAIL_BCC,"[MKUSERS] Elaborazione accounts utente","Elaborazione accounts utente (mkusers)",Array(gsLogFile),False)
  50.   End If
  51.   WScript.Quit nExitCode
  52. '}
  53.  
  54. ' startup
  55. Function main(argc, argv)
  56.   Dim cnCON, rsREC, cmCMD
  57.   Dim sUsername, sFullName, sDescription, sPassword
  58.   Dim nRet, lTotRec, lRecOk, lRecErr
  59.   Dim nStatus
  60.  
  61.   On Error Resume Next  
  62.   If DEBUG_MODE = 1 Then
  63.     Message "== Inizio elaborazione utenti"
  64.   End If
  65.  
  66.   nRet = 0
  67.   Set cnCON = CreateObject("ADODB.Connection")
  68.   Set rsREC = CreateObject("ADODB.Recordset")
  69.   Set cmCMD = CreateObject("ADODB.Command")
  70.  
  71.   ' --- apre la connessione al DB
  72.  If DEBUG_MODE = 1 Then
  73.     Message "Apertura connessione database..."
  74.   End If
  75.   Err.Clear
  76.   With cnCON
  77.     .ConnectionString = CONN_STR
  78.     .CursorLocation = 2 ' adUseServer
  79.    .Open
  80.   End With
  81.   If Err.Number <> 0 Then
  82.     Message "ERR(con): 0x" & Hex(Err.Number) & " " & Err.Description
  83.     main = 1
  84.     Exit Function    
  85.   End If
  86.  
  87.   ' --- inizializza il command per update
  88.  If DEBUG_MODE = 1 Then
  89.     Message "Inizializzazione oggetto command..."
  90.   End If
  91.   Err.Clear
  92.   With cmCMD
  93.     Set .ActiveConnection = cnCON
  94.     .CommandType = 1 ' adCmdText
  95.  End With
  96.   If Err.Number <> 0 Then
  97.     Message "ERR(cmd): 0x" & Hex(Err.Number) & " " & Err.Description
  98.     main = 2
  99.     Exit Function    
  100.   End If
  101.  
  102.   ' --- apre il cursore sulla tabella utenti
  103.  If DEBUG_MODE = 1 Then
  104.     Message "Apertura tabella utenti..."
  105.   End If
  106.   Err.Clear
  107.   With rsREC
  108.     Set .ActiveConnection = cnCON
  109.     .CursorType = 0     ' adOpenForwardOnly
  110.    .LockType = 1       ' adLockReadOnly
  111.    .Open "SELECT * FROM MKUSERS WHERE STATUS IN (1,2) ORDER BY USERNAME"
  112.   End With
  113.   If Err.Number <> 0 Then
  114.     Message "ERR(rec): 0x" & Hex(Err.Number) & " " & Err.Description
  115.     main = 3
  116.     Exit Function    
  117.   End If
  118.      
  119.   ' --- loop ed eliminazione/creazione utenti
  120.  If DEBUG_MODE = 1 Then
  121.     Message "Verifica utenti da elaborare..."
  122.   End If
  123.   lTotRec = 0
  124.   lRecOk = 0
  125.   lRecErr = 0
  126.   While Not rsREC.EOF
  127.     lTotRec = lTotRec + 1
  128.     sUsername = Trim("" & rsREC("USERNAME"))
  129.     sFullName = Trim("" & rsREC("FULLNAME"))
  130.     sDescription = Trim("" & rsREC("DESCRIPTION"))
  131.     sPassword = Trim("" & rsREC("PASSWORD"))
  132.     nStatus = CLng("0" & rsREC("STATUS"))
  133.     Message "Elaborazione utente " & sUsername & " (status=" & nStatus & ") ..."
  134.     DeleteUser ".", sUsername
  135.     If nStatus = 2 Then
  136.         ' --- 2: eliminazione
  137.        If DEBUG_MODE = 1 Then
  138.           Message "Eliminazione utente " & sUsername & " ..."
  139.         End If
  140.         If UpdateUserTable(cmCMD, sUsername, 6) = True Then
  141.           Message "Utente " & sUsername & " eliminato con successo."
  142.           lRecOk = lRecOk + 1
  143.         Else
  144.           Message "Errore, utente " & sUsername & " eliminato ma status non aggiornato !"
  145.           lRecErr = lRecErr + 1
  146.           nRet = 254
  147.         End If
  148.     Else
  149.       ' --- 1: creazione utente
  150.      If DEBUG_MODE = 1 Then
  151.         Message "Creazione utente " & sUsername & " ..."
  152.       End If
  153.       If CreateUser(".", sUsername, sFullName, sDescription, sPassword, GROUP_NAME) Then
  154.         If UpdateUserTable(cmCMD, sUsername, 5) = True Then
  155.           Message "Utente " & sUsername & " creato con successo."        
  156.           lRecOk = lRecOk + 1
  157.         Else
  158.           Message "Errore, utente " & sUsername & " creato ma status non aggiornato !"
  159.           lRecErr = lRecErr + 1
  160.           nRet = 254
  161.         End If
  162.       Else
  163.         Message "Utente " & sUsername & " NON creato causa errori."
  164.         If UpdateUserTable(cmCMD, sUsername, 9) = False Then
  165.           Message "ERR: Impossibile aggiornare lo status per l'utente " & sUsername      
  166.         End If
  167.         lRecErr = lRecErr + 1
  168.         nRet = 255
  169.       End If      
  170.     End If      
  171.     rsREC.MoveNext
  172.   Wend
  173.  
  174.   If DEBUG_MODE = 1 Then
  175.     Message "Chiusura connessione database..."
  176.   End If
  177.   rsREC.Close
  178.   Set rsREC.ActiveConnection = Nothing
  179.   Set rsREC = Nothing
  180.   Set cmCMD.ActiveConnection = Nothing
  181.   Set cmCMD = Nothing
  182.   cnCON.Close
  183.   Set cnCON = Nothing
  184.  
  185.   If (lTotRec > 0) Or (DEBUG_MODE=1) Then
  186.     Message "Elaborati " & lTotRec & " records"
  187.     Message lRecOk & " utenti elaborati con successo"
  188.     Message lRecErr & " utenti non elaborati causa errori"
  189.   End If
  190.  
  191.   If DEBUG_MODE = 1 Then
  192.     Message "Elaborazione utenti completata."
  193.   End If
  194.   main = nRet
  195. End Function
  196.  
  197. ' aggiorna la tabella utenti
  198. Function UpdateUserTable(cmCMD, sUserName, nStatus)
  199.   Dim sSQL, lRecNo, bRet
  200.  
  201.   On Error Resume Next
  202.   bRet = False
  203.   sSQL = "UPDATE MKUSERS SET STATUS=" & nStatus & " WHERE USERNAME='" & sUsername & "'"
  204.   If DEBUG_MODE = 1 Then
  205.     Message "Esecuzione SQL: " & sSQL
  206.   End If
  207.   cmCMD.CommandText = sSQL
  208.   lRecNo = 0
  209.   cmCMD.Execute lRecNo
  210.   If (Err.Number <> 0) Or (lRecNo < 1) Then
  211.     Message "ERR(cmd): 0x" & Hex(Err.Number) & " " & Err.Description & " (" & sSQL & ")"
  212.   Else
  213.     bRet = True    
  214.   End If
  215.   UpdateUserTable = bRet
  216. End Function
  217.  
  218. ' scrive una riga nel logfile
  219. Sub LogMsg(sStr)
  220.   Dim fp, sDate
  221.  
  222.   On Error Resume Next
  223.   Set fp = fso.OpenTextFile(gsLogFile, ForAppending, True)
  224.   sDate = Right("00" & Day(Now), 2) & "-" & Right("00" & Hour(Now), 2) & ":" & Right("00" & Minute(Now), 2)
  225.   fp.WriteLine sDate & " " & sStr
  226.   fp.Close  
  227. End Sub
  228.  
  229. ' stampa una stringa a console con crlf
  230. Sub Message(sMsg)
  231.   On Error Resume Next
  232.   WScript.StdOut.WriteLine sMsg
  233.   LogMsg sMsg
  234. End Sub
  235.  
  236. ' elimina un utente
  237. Sub DeleteUser(sComputer, sUsername)
  238.   Dim objComputer
  239.  
  240.   On Error Resume Next  
  241.   If DEBUG_MODE = 1 Then
  242.     Message "DeleteUser(" & sUserName & ")"
  243.   End If
  244.   Set objComputer = GetObject("WinNT://" & sComputer & "")
  245.   objComputer.Delete "user", sUsername
  246. End Sub
  247.  
  248. ' crea un utente
  249. Function CreateUser(sComputer, sUserName, sFullName, sDescription, sPassword, sGroup)
  250.   Dim objSystem, objUser, objUserFlags
  251.   Dim bResult
  252.  
  253.   On Error Resume Next  
  254.   bResult = False
  255.   CreateUser = bResult
  256.  
  257.   If DEBUG_MODE = 1 Then
  258.     ''Message "CreateUser(" & sUserName & "," & sFullName & "," & sDescription & "," & sPassword & "," & sGroup & ")"
  259.    Message "CreateUser(" & sUserName & "," & sFullName & "," & sDescription & "," & String(8, "*") & "," & sGroup & ")"
  260.   End If
  261.  
  262.   ' controlla la password
  263.  If IsComplex(sPassword) = False Then
  264.     Message "ERR(pwd): " & sUserName & " la password non corrisponde alle regole di complessità."
  265.     Exit Function  
  266.   End If
  267.  
  268.   ' crea l'utente
  269.  Err.Clear
  270.   Set objSystem = GetObject("WinNT://" & sComputer)
  271.   Set objUser = objSystem.Create("user", sUserName)
  272.   objUser.FullName = sFullName
  273.   objUser.Description = sDescription
  274.   objUser.SetPassword sPassword
  275.   ' @# Solo remoteAPP
  276.  'objUser.TerminalServicesInitialProgram = "%SYSTEMROOT%\system32\logoff.exe"
  277.  'objUser.TerminalServicesWorkDirectory = "%SYSTEMROOT%\system32"
  278.  objUser.SetInfo
  279.   If Err.Number <> 0 Then
  280.     Message "ERR(usr): " & sUserName & " 0x" & Hex(Err.Number) & " " & Err.Description
  281.     Exit Function
  282.   End If
  283.  
  284.   ' imposta i flags "password never expires"
  285.  ' e "user can't change password"
  286.  Err.Clear
  287.   objUserFlags = objUser.Get("UserFlags")
  288.   objPasswordExpirationFlag = objUserFlags Or ADS_UF_PASSWD_CANT_CHANGE Or ADS_UF_DONT_EXPIRE_PASSWD
  289.   objUser.Put "userFlags", objPasswordExpirationFlag
  290.   objUser.SetInfo
  291.   If Err.Number <> 0 Then
  292.     Message "ERR(pwd): " & sUserName & " 0x" & Hex(Err.Number) & " " & Err.Description
  293.     Exit Function
  294.   Else
  295.     ' se richiesto, aggiunge l'utente ad un gruppo
  296.    If Len(sGroup) > 0 Then
  297.       bRet = AddToGroup(sComputer, sUsername, sGroup)
  298.     Else
  299.       bRet = True      
  300.     End If
  301.   End If
  302.  
  303.   If bRet Then
  304.     bRet = SetInitialProg(sUserName)
  305.   End If
  306.  
  307.   CreateUser = bRet
  308. End Function
  309.  
  310. ' imposta il programma da avviare al logon
  311. Function SetInitialProg(sUserName)
  312.   Dim objUser
  313.  
  314.   On Error Resume Next
  315.   SetInitialProg = False
  316.   Err.Clear
  317.   Set objUser = GetObject("WinNT://localhost/" & sUserName)
  318.   objUser.TerminalServicesInitialProgram = "C:\Windows\System32\logoff.exe"
  319.   objUser.TerminalServicesWorkDirectory = "C:\Windows\System32"
  320.   objUser.SetInfo
  321.  
  322.   If Err.Number <> 0 Then
  323.     Message "ERR(prog): " & sUserName & " 0x" & Hex(Err.Number) & " " & Err.Description
  324.     Exit Function
  325.   End If
  326.   SetInitialProg = True
  327. End Function
  328.  
  329.  
  330. ' aggiunge l'utente ad un gruppo
  331. Function AddToGroup(sComputer, sUsername, sGroup)
  332.   Dim objUser, ObjGroup, bRet
  333.  
  334.   On Error Resume Next
  335.   If DEBUG_MODE = 1 Then
  336.     Message "AddToGroup(" & sUserName & "," & sGroup & ")"
  337.   End If
  338.   bRet = False
  339.   AddToGroup = bRet
  340.  
  341.   Err.Clear
  342.   set objUser = GetObject("WinNT://" & sUsername)
  343.   set objGroup = GetObject("WinNT://" & sComputer & "/" + sGroup & ",group")
  344.   objGroup.Add(objUser.AdsPath)
  345.   If Err.Number <> 0 Then
  346.     Message "ERR(grp): " & sUserName & " 0x" & Hex(Err.Number) & " " & Err.Description
  347.     Exit Function
  348.   Else
  349.     bRet = True    
  350.   End If
  351.   AddToGroup = bRet
  352. End Function
  353.  
  354. ' controlla se la password risponde
  355. ' alle "regole di complessità"
  356. Function IsComplex(sPassword)
  357.   Dim iChr, bFlag
  358.  
  359.   On Error Resume Next
  360.   IsComplex = True
  361.    
  362.   ' Lunghezza
  363.  If Len(sPassword) < 8 Then
  364.     IsComplex = False
  365.     Exit Function
  366.   End If
  367.  
  368.   ' numeri
  369.  bFlag = False
  370.   For iChr = 48 to 57
  371.     If Instr(1, sPassword, Chr(iChr)) > 0 Then
  372.        bFlag = True
  373.        Exit For
  374.     End If
  375.   Next
  376.   If bFlag = False Then
  377.     IsComplex = False
  378.     Exit Function
  379.   End If
  380.  
  381.   ' caratteri maiuscoli
  382.  bFlag = False
  383.   For iChr = 65 to 90
  384.     If Instr(1, sPassword, Chr(iChr)) > 0 Then
  385.        bFlag = True
  386.        Exit For
  387.     End If
  388.   Next
  389.   If bFlag = False Then
  390.     IsComplex = False
  391.     Exit Function
  392.   End If
  393.  
  394.   ' caratteri minuscoli
  395.  bFlag = False
  396.   For iChr = 97 to 122
  397.     If Instr(1, sPassword, Chr(iChr)) > 0 Then
  398.        bFlag = True
  399.        Exit For
  400.     End If
  401.   Next
  402.   If bFlag = False Then
  403.     IsComplex = False
  404.     Exit Function
  405.   End If
  406. End Function
  407.  
  408. ' Invia un messaggio email
  409. Function SendMail(sFrom, sTo, sCc, sBCc, sSubject, sBody, vaAttach, bReceipt)
  410.   Dim objMsg, objConf
  411.   Dim iAtt
  412.  
  413.   On Error Resume Next
  414.   If Len(MAIL_SERV) < 1 Then
  415.     SendMail = True
  416.     Exit Function
  417.   End If  
  418.  
  419.   SendMail = False
  420.   set objMsg = CreateObject("CDO.Message")
  421.   set objConf = CreateObject("CDO.Configuration")
  422.  
  423.   ' inizializza la config del "motore" SMTP
  424.  Message "Inizializzazione supporto email..."
  425.   Set objFlds = objConf.Fields
  426.   With objFlds
  427.     .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
  428.     .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = MAIL_SERV
  429.     .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = MAIL_PORT
  430.     If (Len(MAIL_USER) < 1) Or (Len(MAIL_PASS) < 1) Then
  431.       .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoAnonymous
  432.       .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = ""
  433.       .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = ""
  434.     Else
  435.       .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
  436.       .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = MAIL_USER
  437.       .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = MAIL_PASS
  438.     End If
  439.     .Update
  440.   End With
  441.  
  442.   ' crea ed invia il messaggio e-mail
  443.  Message "Creazione messaggio email " & Chr(34) & sSubject & Chr(34)
  444.   With objMsg
  445.     Set .Configuration = objConf
  446.     .From = sFrom
  447.     .To = sTo
  448.     .Cc = sCc
  449.     .BCc = sBcc
  450.     .Subject = sSubject
  451.     .TextBody = sBody
  452.     For iAtt = LBound(vaAttach) To UBound(vaAttach)
  453.       If Len(vaAttach(iAtt)) > 0 Then
  454.         Message "Aggiunta allegato " & vaAttach(iAtt)
  455.         .Addattachment GetFileName(vaAttach(iAtt))
  456.       End If
  457.     Next
  458.     If bReceipt = True Then
  459.       .Fields("urn:schemas:mailheader:disposition-notification-to") = sFrom
  460.       .Fields("urn:schemas:mailheader:return-receipt-to") = sFrom
  461.       .DSNOptions = cdoDSNSuccessFailOrDelay
  462.     End If
  463.     .Fields.update
  464.     Message "Invio messaggio email"
  465.     Err.Clear
  466.     .Send
  467.   End With
  468.  
  469.   ' verifica esito dell'operazione
  470.  If Err.Number <> 0 Then
  471.     Message "Errore invio email: 0x" & Hex(Err.Number) & " " & Err.Description
  472.   Else
  473.     Message "Messaggio inviato con successo"
  474.     SendMail = True
  475.   End If
  476. End Function
  477.  
  478. ' converte pathname parziale in pathname completo
  479. ' la funzione è necessaria dato che CDO richiede
  480. ' un nome file completo per gli attachments
  481. Function GetFileName(sPathName)
  482.   On Error Resume Next
  483.   GetFileName = ""
  484.   If Not fso.FileExists(sPathName) Then
  485.     Exit Function
  486.   End If  
  487.   Set fi = fso.GetFile(sPathName)
  488.   '' Message "File " & fi.Path & " ok."
  489.  GetFileName = fi.Path
  490. End Function
Add Comment
Please, Sign In to add comment