Posts Tagged ‘Windows’

Batch-scripting

Friday, March 21st, 2008

Batch-scripting is not as powerful as WSH-scripting or PowerShell.
But with some tools you can perform some simple but useful actions.
One tool I often use is robocopy.

  1. Asking for values in a batch-script
    @echo off
    @set /P pctocheck=Enter name of pc:
    @cscript.exe "script.vbs" %pctocheck%
    pause
  2. Copy non-existing folders back to C-drive
    @echo off
    rem Check if the script was called with parameter RUN
    IF "%1"=="RUN" GOTO run
    rem Since we are not running the script with parameter RUN, start it using cmd whilst enabling delayed environment variable expansion (/V:ON)
    cmd /V:ON /C H:\copy_c-drive.cmd RUN
    GOTO :EOF
    :run
    echo ...Copying extra folders on C-drive
    rem List all existing files and directories on the C-drive, including hidden ones.
    dir /a:d /b C:\ >C:\WINDOWS\TEMP\rc_existsystemdirs.txt
    dir /a:hd /b C:\ >>C:\WINDOWS\TEMP\rc_existsystemdirs.txt
    dir /a:-d /b C:\ >C:\WINDOWS\TEMP\rc_existsystemfiles.txt
    dir /a:h-d /b C:\ >>C:\WINDOWS\TEMP\rc_existsystemfiles.txt
    rem Build up variables
    set existingdirs=
    FOR /F "delims=," %%i IN (C:\WINDOWS\TEMP\rc_existsystemdirs.txt) do set existingdirs=!existingdirs! /XD "%%i"
    set existingfiles=
    FOR /F "delims=," %%i IN (C:\WINDOWS\TEMP\rc_existsystemfiles.txt) do set existingfiles=!existingfiles! /XF "%%i"
    rem Do the copy thing
    robocopy /COPYALL /E X:\ C:\ /TEE /LOG+:C:\WINDOWS\TEMP\rc_system.log /XO /R:1 /W:3 %existingdirs% %existingfiles%

WSH Scripting

Friday, March 21st, 2008

Using WSH with WMI enables you to query lots of information of a system.
Here are some examples of code that I regularly use.

  1. Determine UpTime of a computer
    strComputer = InputBox("Enter computername","Determine Uptime",".")
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * From Win32_PerfFormattedData_PerfOS_System")
    intSystemUptime = 0
    For Each objOS in colOperatingSystems
    Dim intSystemUptimeSec
    Dim intSystemUptimeMin
    Dim intSystemUptimeHour
    Dim intSystemUptimeDay
    intSystemUptimeDay = Int(objOS.SystemUpTime / 86400)
    intSystemUptimeHour = Int(objOS.SystemUpTime / 3600) - (intSystemUptimeDay*24)
    intSystemUptimeMin = Int(objOS.SystemUpTime / 60) - (intSystemUptimeHour*60) - (intSystemUptimeDay*24*60)
    intSystemUptimeSec = Int(objOS.SystemUpTime) - (intSystemUptimeMin*60) - (intSystemUptimeHour*60*60) - (intSystemUptimeDay*24*60*60)
    intSystemUptime = Int(objOS.SystemUpTime / 60)
    MsgBox("Uptime for " & strcomputer &  " = " & intSystemUptimeDay & "d " & intSystemUptimeHour & "h " & intSystemUptimeMin & "m " & intSystemUptimeSec & "s")
    Next
  2. Ping a computer
    strComputer = InputBox("Enter computername","Ping a computer",".")
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
    ExecQuery("select * from Win32_PingStatus where address = '"_
    & strComputer & "'")
    For Each objStatus in objPing
    If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
    MsgBox("Ping failed")
    else
    MsgBox("Ping succeeded")
    End If
    Next
  3. Map a Networkdrive
    Set oNet = CreateObject("wscript.network")
    oNet.MapNetworkDrive "X:", "\\" & strComputer & "\c$"
  4. Get Computers from an OU in Active Directory
    Set ObjOU = GetObject("LDAP://OU=Desktops,OU=Computers,DC=corp,DC=contoso,DC=com")
    ObjOU.Filter = Array("Computer")
    For Each ObjComp in ObjOU
  5. List running processes
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\cimv2")
    Set colProcess = objWMIService.ExecQuery _
    ("Select * from Win32_Process")
    For Each objProcess in colProcess
    WScript.Echo objProcess
    Next
  6. Count DiskErrors
    Set colLoggedEvents = objWMIService.ExecQuery _
    ("Select * from Win32_NTLogEvent Where Logfile = 'System'" _
    & " and SourceName = 'disk'")
    iDiskErrors = colLoggedEvents.count
  7. Show logged on user
    Set Users = objWMIService.InstancesOf("Win32_ComputerSystem")
    for each User in Users
    If isNull(User.UserName) then
    WScript.Echo "No User is logged on"
    else
    WScript.Echo User.UserName
    end if
    Next
  8. Enumerate all profiles stored in Documents and Settings
    Set objFolder = objFSO.GetFolder("\\" & strComputer & "\c$\Documents And Settings")
    valStoredprofiles = ""
    For Each Subfolder in objFolder.SubFolders
    If IsStandardUserProfile(SubFolder.Path) then
    arrPath = split(Subfolder.Path,"\")
    'sSize = Round(SubFolder.Size/1024/1024,2)
    'valStoredprofiles = valStoredprofiles & arrPath(UBound(arrPath,1)) & "  [" & sSize & "MB] " & " - "
    valStoredprofiles = valStoredprofiles & arrPath(UBound(arrPath,1)) & " - "
    end if
    Next
    Function IsStandardUserProfile(sFolder)
    Dim iMatches
    iMatches = 0
    If Instr(sFolder,"Administrator") > 0 then iMatches = iMatches + 1
    If Instr(sFolder,"All Users") > 0 then iMatches = iMatches + 1
    If Instr(sFolder,"Default User") > 0 then iMatches = iMatches + 1
    If Instr(sFolder,"LocalService") > 0 then iMatches = iMatches + 1
    If Instr(sFolder,"NetworkService") > 0 then iMatches = iMatches + 1
    If iMatches = 0 then
    IsStandardUserProfile= true
    Else
    IsStandardUserProfile= false
    end if
    End Function
  9. Read and write an XML-file
    Set objXML = CreateObject("Microsoft.XMLDOM")
    objXML.load "result.xml"
    'WScript.Echo objXML.parseError.errorCode
    If (objXML.parseError.errorCode <> 0) Then
    Dim myErr
    Set myErr = objXML.parseError
    MsgBox("You have error " & myErr.reason)
    Else
    'WScript.Echo objXML.xml
    'WScript.Echo objXML.documentElement.attributes.item(0).nodeValue
    Dim i
    i = 1
    ReDim PreServe arrPcs(i+1)
    Set pcs = objXML.getElementsByTagName("pc")
    'WScript.Echo pcs
    for each pc in pcs
    arrPcs(i-1) = pc.getAttribute("id") & ";" & pc.getAttribute("location")
    i=i+1
    ReDim PreServe arrPcs(i)
    next
    End If
    for each pc in pcs
    pcID = pc.getAttribute("id")
    if pcID = current PC then
    '<ip>192.168.1.19</ip>
    '<uptime>0</uptime>
    '<diskerrors>0</diskerrors>
    '<user>NONE</user>
    '<storedprofiles>0</storedprofiles>
    'WScript.Echo pc.childNodes.length
    pc.childNodes.Item(0).firstChild.nodeValue = valIP
    pc.childNodes.Item(2).firstChild.nodeValue = valUptime
    pc.childNodes.Item(3).firstChild.nodeValue = valDiskerrors
    'WScript.Echo valUser
    pc.childNodes.Item(4).firstChild.nodeValue = valUser
    pc.childNodes.Item(5).firstChild.nodeValue = valStoredprofiles
    exit for
    end if
    next
    objXML.documentElement.Attributes.Item(0).nodeValue = now
    objXML.save("result.xml")

Using Debian as domain controller in a Windows network

Thursday, October 12th, 2006

Using Debian as domain controller in a Windows network
I didn’t find the for the moment to comment the commands used, but for the moment these are the steps I used.

apt-get install vim
apt-get install apache2
apt-get install libapache2-mod-php4
FQDN error
vi /etc/hosts
192.168.1.190 server.legacycode.lan server localhost
 
apt-get install slapd
DNS domain: legacycode.lan
Name of organization: legacycode.lan
 
wget http://www.nomis52.net/data/mkntpwd.tar.gz
tar zxf mkntpwd.tar.gz
cd mkntpwd
make
cp mkntpwd /usr/local/bin
 
apt-get install samba samba-doc
cd /usr/share/doc/samba-doc/examples/LDAP
gunzip samba.schema.gz
cp samba.schema /etc/ldap/schema/
vi /etc/ldap/slapd.conf
include         /etc/ldap/schema/samba.schema
/etc/init.d/slapd restart
 
apt-get install db4.2-util
 
apt-get install phpldapadmin
Authentication type: session
Configure webserver: apache2
Restart: yes
 
cd /usr/share/doc/samba-doc/examples/LDAP/smbldap-tools-0.8.7
gunzip smbldap.conf.gz
mkdir /etc/smbldap-tools/
cp smbldap.conf /etc/smbldap-tools/
cp smbldap_bind.conf /etc/smbldap-tools/
net getlocalsid
(copy SID (S-1-5-21-1646905445-4160608177-2293427999))
vi /etc/smbldap-tools/smbldap.conf
*replace sid
suffix="dc=legacycode,dc=lan"
mailDomain="legacycode.lan"
hash_encrypt="MD5"
sambaUnixIdPooldn="sambaDomainName=LEGACYCODE,${suffix}"
 
apt-get install libnet-ldap-perl
apt-get install libcrypt-smbhash-perl
vi /etc/smbldap-tools/smbldap_bind.conf
cn=admin,dc=legacycode,dc=lan
Pw="password"
smbldap-populate
 
http://server.legacycode.lan/phpldapadmin/
 
delete sambaDomainName!
 
vi /etc/samba/smb.conf
passdb backend = ldapsam:ldap://127.0.0.1
ldap suffix = dc=legacycode,dc=lan
ldap machine suffix = ou=machines
ldap user suffix = ou=users
ldap group suffix = ou=groups
ldap admin dn = cn=admin,dc=legacycode,dc=lan
ldap delete dn = no
# be a PDC
domain logons = yes
# allow user privileges
enable privileges = yes
 
smbpasswd -w password
/etc/init.d/samba restart
 
//S-1-5-21-3794264148-3631614111-1670683845
vi /usr/share/phpldapadmin/templates/template_config.php
// uncomment to set the base dn of posix groups
// default is set to the base dn of the server
$base_posix_groups="ou=groups,dc=legacycode,dc=lan";
$samba3_domains []  =
array(  'name'   =&gt; 'nomis52',
        'sid' =&gt; 'S-1-5-21-1646905445-4160608177-2293427999' );
// The base dn of samba group. (CUSTOMIZE)
$samba_base_groups = "ou=groups,dc=legacycode,dc=lan";
 
apt-get install libnss-ldap
LDAP Server Host: 127.0.0.1
DN of Search Base: dc=legacycode,dc=lan
LDAP Version: 3
Database requires login: no
Make config readable by owner only: yes
 
vi /etc/nsswitch.conf
passwd:         compat ldap
group:          compat ldap
shadow:         compat ldap
 
getent group
apt-get install libpam-ldap
Make local root db admin: yes
Database requires logging in : no
Root login account : cn=admin,dc=legacycode,dc=lan
Root password : password
Crypt : MD5
 
/etc/pam.d/common-account
# Comment out the next line
#account required pam_unix.so
# and add these two
account sufficient pam_ldap.so
account required pam_unix.so try_first_pass
 
/etc/pam.d/common-auth
# comment out the next line
#auth required pam_unix.so nullok_secure
# and add these two
auth sufficient pam_ldap.so
auth required pam_unix.so nullok_secure use_first_pass
 
/etc/pam.d/common-password
# comment out the next line
#password required pam_unix.so nullok obscure min=4 max=8 md5
# and add these two
password sufficient pam_ldap.so
password required pam_unix.so nullok obscure min=4 max=8 md5 use_first_pass 
 
apt-get install nscd
 
samba afconfigureren
/etc/samba/smb.conf
netbios name = server
add user script = /usr/sbin/smbldap-useradd -m "%u"
delete user script = /usr/sbin/smbldap-userdel "%u"
add machine script = /usr/sbin/smbldap-useradd -w "%m"
add group script = /usr/sbin/smbldap-groupadd -p "%g"
add user to group script = /usr/sbin/smbldap-groupmod -m "%u" "%g"
delete user from group script = /usr/sbin/smbldap-groupmod -x "%u" "%g"
set primary group script = /usr/sbin/smbldap-usermod -g "%g" "%u"
ldap password sync = yes
 [homes]
   comment = Home
   valid users = %S
   read only = no
   browsable = no
 [printers]
   comment = All Printers
   path = /var/spool/samba
   printable = yes
   guest ok = yes
   browsable = no
 [netlogon]
   comment = Network Logon Service
   path = /home/samba/netlogon
   admin users = Administrator
   valid users = %U
   read only = no
 [profile]
   comment = User profiles
   path = /home/samba/profiles
   valid users = %U
   create mode = 0600
   directory mode = 0700
   writable = yes
   browsable = no
 
mkdir /home/samba
mkdir /home/samba/netlogon
mkdir /home/samba/profiles
mkdir /var/spool/samba
chmod 777 /var/spool/samba/
chown -R root:users /home/samba/
chmod -R 771 /home/samba/
 
smbpasswd -a domadmin1
use phpldapadmin to add user to the Domain Admins <img src="/web/20120304212301im_/https://www.legacycode.net/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
net rpc -Udomadmin1 rights grant "Domain Admins" SeMachineAccountPrivilege
 
apt-get install bind9 bind9-doc dnsutils
vi /etc/bind/named.conf.options
 forwarders {
                192.168.1.1;
 };
 allow-transfer { none; };
 
vi /etc/bind/named.conf.local
zone "legacycode" {
    type master;
    file "/etc/bind/zone.legacycode.lan";
};
zone "1.168.192.in-addr.arpa"{
    type master;
    file "/etc/bind/zone.1.168.192.in-addr.arpa";
};
 
/etc/bind/zone.legacycode.lan
@    IN SOA server.legacycode.lan. support.legacycode.lan. (
        20060702
        172800
        960
        1209600
        3600
)
@    IN    NS server.legacycode.lan.
server    IN    A    192.168.1.190
 
/etc/bind/zone.1.168.192.in-addr.arpa
@ IN SOA server.legacycode.lan. support.legacycode.lan. (
 20060702
 172800
 960
 1209600
 3600
)
@    IN    NS server.legacycode.lan.
190    IN    PTR server.legacycode.lan.
 
Add WindowsXP Client
LEGACYCODE.lan
domadmin1 (= Domain Administrator account)
...
 
apt-get install squid
/etc/squid/squid.conf
acl mynetwork src 192.168.1.0/255.255.255.0
http_access allow mynetwork
 
apt-get install ntpdate
 
 smbldap-useradd -a -d /home/user1 -k /etc/skel user1
smbldap-passwd user1
\\SERVER\homes\<user>
\\SERVER\homes\<user>\profile
 
smbldap-adduser.sh
#!/bin/bash
if  [ ! -e /home/$1 ] ; then
   echo "Creating home dir for $1" >>/var/log/smbldap-adduser.log
   mkdir -p /home/$1
   cp /etc/skel/* /home/$1
   cp /etc/skel/.* /home/$1
fi
mkdir -p /home/$1/profile
smbldap-useradd -a -d /home/$1 $1
smbldap-usermod -C "" $1
smbldap-usermod -D "" $1
smbldap-usermod -E "" $1
smbldap-usermod -F "" $1
chown -R "$1":"Domain Users" /home/$1
chmod -R 750 /home/$1
smbldap-passwd $1
exit 0
 
chown -R "Administrator":"Domain Users" /home/samba/netlogon/
chown -R "Administrator":"Domain Users" /home/samba/profiles/
chmod 740 /home/samba/netlogon/<user>.cmd