18/4/14

Hiện & Ẩn file trong Windows bằng lệnh ATTRIB

Một số loại virus khi lây nhiễm vào máy tính thường vô hiệu hóa tính năng hiện file ẩn ( hidden file ) và các file hệ thống ( system file ), để tránh bị phát hiện bằng mắt thường virus còn đặt thêm thuộc tính system cho các file ẩn . Vì thế khi chưa diệt được virus mà bạn có cố gắng bật lại chế độ hiện file ẩn trong Folder Options cũng vô dụng và hậu quả là các file mà bạn tự đặt thuộc tính ẩn cũng không thể thấy được, ngay cả khi dùng chương trình quản lý file chuyên nghiệp như total commander.
Mình biết có rất nhiều bạn đang làm luận văn và lưu file báo cáo vào ổ đĩa usb gắn vào máy tính bị nhiễm virus ẩn file mất tiêu hết, không thấy file báo cáo đâu vì tưởng bị virus “ăn” hết. Nhiều bạn dại dột format lại usb vì tưởng usb bị lỗi.
Kết quả là phải làm lại file báo cáo từ đầu, sống dở chết dỡ luôn. Ngay cả khi bạn lưu trên ổ cứng thì vẫn có thể bị ẩn dữ liệu nếu máy tính bạn bị nhiễm virus ẩn file.
Khi gặp trường hợp này bạn có thể sử dụng câu lệnh ATTRIB trong command line ( CMD ) để loại bỏ thuộc tính ẩn ở những file và thư mục cần thiết. Lệnh này sẽ là vị cứu tinh giúp bạn lấy lại dữ liệu bị ẩn đấy nhé.
Chịu khó đọc hướng dẫn và thực hành để ứng dụng phòng thân và làm anh hùng giúp bạn bè nhé ^.^
1. Khởi động command line từ nút Start–>Run ( phím tắt Windows + R ) sau đó gõ vào cmd rồi nhấn phím enter.
2. Cách sử dụng câu lệnh ATTRIB .
Khi vào cửa sổ chương trình cmd bạn có thể gõ lệnh ATTRIB /? để xem cách viết và ý nghĩa của câu lệnh.
Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.C:\Documents and Settings\Minit>attrib /?
Displays or changes file attributes.
ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [drive:][path][filename] [/S [/D]]
+   Sets an attribute. // dấu + để thêm thuộc tính
-   Clears an attribute. // dấu – để loại bỏ thuộc tính
R   Read-only file attribute. // thuộc tính chỉ đọc
A   Archive file attribute. // thuộc tính lưu trữ
S   System file attribute. // thuộc tính hệ thống
H   Hidden file attribute. // thuộc tính ẩn
[drive:][path][filename] Specifies a file or files for attrib to process. // đường dẫn đến ổ đĩa, thư mục và tập tin cần đặt thuộc tính ( nếu tên tập tin và thư mục có chứa khoảng trắng hay kí tự đặc biệt bạn cần phải để đường dẫn trong dấu “” )
/S  Processes matching files in the current folder
and all subfolders. // tham số này sẽ thực hiện lệnh đố với file nằm trong thư mục hiện hành và tất cả thư mục con
/D  Processes folders as well. // tham số này chỉ dùng để đặt thuộc tính cho thư mục và thư mục con chứ không đặt thuộc tính cho file bên trong thư mục
3. Ví dụ minh họa:
1. Giả sử trên máy tính của mình có một loạt file có thuộc tính ẩn nằm trong thư mục clip hot của ổ D ( D:\clip hot\ ) đã bị ẩn.
Để nhìn thấy được các file ẩn này mình dùng lệnh sau để loại bỏ thuộc tính ẩn cho các file này:
attrib -s -h “D:\clip hot\*”
- Vì thư mục clip hot có chứa khoảng trắng nên mình phải đặt đường dẫn trong dấu “”
- Kí tự * là kí tự đại diện cho phép lệnh thực hiện đối với tất cả các file có trong thư mục “clip hot”. bạn có thể sử dụng *.jpg hay *.avi hay bất kì đuôi nào để thao tác với các tập tin có phần đuôi mở rộng là jpg, avi,…
- Nếu bên trong thư mục “clip hot” có chứa các thư mục con khác cũng bị ẩn thì bạn thêm vào sau lệnh 2 tham số /s và /d để lệnh thực hiện đối với tất cả các thư mục và tập tin bên trong .
attrib -s -h “D:\clip hot\*” /s /d
2. Loại bỏ thuộc tính ẩn (-h) và thuộc tính file hệ thống (-s) cho toàn bộ file và folder trong ổ D từ dấu nháy ta đánh lệnh di chuyển đến ổ D bằng lệnh D:  sau đó gõ tiếp lệnh sau:
attrib -h -s *.* /S /D
(D:\> attrib -h -s *.* /S /D)
Lưu ý: ký tự * hoặc *.* đại diện cho tất cả file/ thư mục/ ổ đĩa hoặc tất cả các định dạng  (đuôi mở rộng của tập tin).
4. Một số câu lệnh hỗ trợ ATTRIB .
- Lệnh chuyển ổ đĩa : để chuyển từ ổ đĩa C sang D ta thêm dấu : vào sau kí tự của ổ đĩa cần chuyển tới .
C:\Documents and Settings\Minit>D:
- Lệnh chuyển đổi thư mục : Khi đang ở D:\> nếu muốn chuyển vào thư mục clip hot ta dùng lệnh D:\>cd clip hot . Nếu muốn quay về thư mục gốc của ổ D ta dùng lệnh D:\clip hot>cd..
- Nếu đường dẫn đến tập tin quá dài bạn có thể thu gọn đường dẫn đó lại ( đường dẫn trong dos ) bằng lệnh liệt kê dir với tham số /x
D:\clip hot>dir /a /x ( /a để hiện tất cả các file ), đường dẫn file và thư mục trong cmd có thể sẽ khác đường dẫn bạn thấy trong Windows Explorer (My Computer), cho nên để lấy đường dẫn chính xác bạn nên đánh câu lệnh dir này để lấy đường dẫn.
- Ngoài ra bạn có thể đặt đường dẫn đến file hoặc folder trong cặp dấu ” ” để thực thi câu lệnh mà không cần phải dùng lệnh cd để di chuyển con nháy gõ lệnh đến thư mục cần thực thi câu lệnh.
5. Hiện tất cả các file và thư mục trong ổ đĩa chỉ với 1 cú click chuột.
Mình viết sẵn nội dung câu lệnh attrib và lưu trong một tập tin có đuôi .bat (.cmd). Bạn chỉ cần download tập tin này về hoặc là gởi link download cho bạn bè.
Khi download về xong chỉ cần bạn click chuột chạy tập tin hoặc click chuột phải lên tập vừa download về chọn Run as administrator (hien_file_o_dia_min.bat) và nhập vào đúng ký tự của ổ đĩa có file/ thư mục bị ẩn mà bạn muốn khôi phục xong bấm phím Enter. Ví dụ như i, e, f, g,…
Tools hiện dữ liệu bị ẩn trên ổ đĩa
Công cụ hiện dữ liệu bị ẩn trên ổ đĩa bằng lệnh attrib trong CMD
Nếu bạn nhập đúng ký tự ổ đĩa thì lệnh attrib sẽ hoạt động và loại bỏ thuộc tính ẩn, thuộc tính hệ thống cho tất cả file và thư mục có trong ổ đĩa bạn nhập vào, việc này có thể mất thời gian nhiều hay ít tùy theo số lượng dữ liệu có trên ổ  đĩa của bạn.
Khi chạy xong cửa sổ cmd cũng sẽ tự tất, bạn chỉ cần vào ổ đĩa kiểm tra xem có dữ liệu hiện lại hay chưa.

28/3/14

Powershell Script - Kiểm tra đồng bộ giữa các Domain Controller

Write-Host ""

$Target_rep = hostname
$date_rep =  Get-Date

$Filename_rep = "C:\Log_Replication\" + $Target_rep + "_" + $date_rep.Hour + $date_rep.Minute + "_" + $Date_rep.Day + "-" + $Date_rep.Month + "-" + $Date_rep.Year + ".hta"



Clear-Host;
Write-host ""
Write-host "Nhap bat ky ky tu nao, se thuc hien kiem tra Replication tai may chu Domain controller hien tai"
write-host "Nhap '*' de thuc hien kiem tra Replication tren tat ca Domain Controller." -foregroundcolor red -backgroundcolor yellow
$SERVERS = (Read-Host "Kiem tra Replication tren Domain Controller")
if ($SERVERS -ne "*")
{
Write-host ""
write-host "Dang kiem tra........"
$workfile = repadmin.exe /showrepl /csv}
else
{
Write-host ""
write-host "Dang kiem tra........"
#Check the Replication with Repadmin
$workfile = repadmin.exe /showrepl * /csv
}
#if ($error -eq $null)
#{

$Report_Rep = @"

TEST REPLICATION











verify AD replication status on Domain controller:$Target_rep

Version 1.0 by Pham Duy Hieu
Report generated on $Date_rep












"@


$results = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1}
$CountFail = $results.count
#$results_show = ConvertFrom-Csv -InputObject $workfile
write-host ""
#$results_show | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status"

#$results_show | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-Html > C:\Log_Replication\Show_Test_replicate.hta

#Here you set the tolerance level for the report
$results = $results | where {$_.'Number of Failures' -gt 1 }

cls
if ($results -ne $null ) {
write-host ""
write-host "Replication Errors: $CountFail" -foregroundcolor red -backgroundcolor yellow
write-host ""
#$results | select "Source DC", "Naming Context", "Destination DC" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status"
    #$results | select "Source DC", "Naming Context", "Destination DC" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-Html > C:\Log_Replication\Test_replicate_fail.hta

$SourceDSA = $results | select 'Source DSA'
#write-host $SourceDSA



} else {


write-host ""
    write-host "There were no Replication Errors" -foregroundcolor red -backgroundcolor yellow
write-host ""
}
#===========================================================================
$Report_rep+= @"
 



Success






  Source DSA
  Naming Context
  Destination DSA
Number of Failures
Last Failure Time
Last Success Time
Last Failure Status

"@
#============================================================================
$success = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -le 0}
#write-host success_count = $success.count
foreach ($row in $success)
{

$SourceDSA = $row.'Source DSA'
$NamingContext = $row.'Naming Context'
$DestinationDSA = $row.'Destination DSA'
$NumberofFailures = $row.'Number of Failures'
$LastFailureTime = $row.'Last Failure Time'
$LastSuccessTime = $row.'Last Success Time'
$LastFailureStatus = $row.'Last Failure Status'

#============================================================================


$Report_rep+=  " "
$Report_rep+=  "$SourceDSA
" $Report_rep+=  "$NamingContext
" $Report_rep+=  "$DestinationDSA
" $Report_rep+=  "$NumberofFailures
" $Report_rep+=  "$LastFailureTime
" $Report_rep+=  "$LastSuccessTime
" $Report_rep+=  "$LastFailureStatus
" $Report_rep+=  "
"}
#===================================================================================
$Report_rep+= @"




"@

#==============================================================

$Report_rep+= @"



Failure






  Source DSA
  Naming Context
  Destination DSA
Number of Failures
Last Failure Time
Last Success Time
Last Failure Status


"@



#==================================================================

$fail = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1}
#write-host $fail_count = $fail.count
foreach ($row_fail in $fail)
{
$SourceDSA_fail = $row_fail.'Source DSA'
$NamingContext_fail = $row_fail.'Naming Context'
$DestinationDSA_fail = $row_fail.'Destination DSA'
$NumberofFailures_fail = $row_fail.'Number of Failures'
$LastFailureTime_fail = $row_fail.'Last Failure Time'
$LastSuccessTime_fail = $row_fail.'Last Success Time'
$LastFailureStatus_fail = $row_fail.'Last Failure Status'



#==============================================================


$Report_rep+=  " "
$Report_rep+=  "$SourceDSA_fail
" $Report_rep+=  "$NamingContext_fail
" $Report_rep+=  "$DestinationDSA_fail
" $Report_rep+=  "$NumberofFailures_fail
" $Report_rep+=  "$LastFailureTime_fail
" $Report_rep+=  "$LastSuccessTime_fail
" $Report_rep+=  "$LastFailureStatus_fail
" $Report_rep+=  "
"
#==============================================================
}
$Report_rep+= @"




"@

#==============================================================



$Report+= @"


"@
write-host ""
write-host "Dang tao Report........."
$Report_rep | out-file -encoding ASCII -filepath $Filename_rep

write-host ""
Write-Host "Report xem tai folder C:\Log_Replication" -foregroundcolor red -backgroundcolor yellow
write-host ""
#}else
#{write-host $error}

PowerShell Script - Create User Domain From CSV File



Chạy trên máy chủ Domain controller 2008 r2 với account có quyền tạo mới User Domain.

Đoạn Script này giúp bạn tạo User Domain từ một file CSV cho trước.
Trong file excel cần nhập các thông tin như hình dưới:


các giá trị từ cột A đến cột E bắt buộc phải nhập. Sau khi điền đầy đủ thông tin save as dưới định dạng file CSV và để cùng thư mục chạy file .ps1


import-module ActiveDirectory
$csv = import-csv -path .\username.csv
foreach ($row in $csv)
{
$dName = $row.name
$SamAccountName = $row.samaccountname
$firstName = $row.firstname
$lastName = $row.lastname
$OU = $row.ou
$passwd = $row.password
$department = $row.department
$description = $row.description

$Userprincipalname_temp = $row.Userprincipalname


$Userprincipalname = $SamAccountName + "@" + $Userprincipalname_temp


New-ADUser -Name $dName -SamAccountName $SamAccountName -GivenName $firstName -Surname $lastName -Path $OU -AccountPassword (convertto-securestring $passwd -asplaintext -force) -ChangePasswordAtLogon $false -Department $department -Description $description -UserPrincipalName $Userprincipalname -Enabled $true

}


==================================================
bqhoan@gmail

6/3/14

Script to Move AD User Objects to another OU depending on an Attribute

# 2012, Tom Schindler
# Moves User Accounts from the given Root OU into sub OUs by looking up the company Attribute of the User Object
# If the OU does not exist, it will be created (the regular expression filter is removing special characters)
 
Import-Module ActiveDirectory
$RootOU = "OU=Guests,DC=mydomain,DC=local"
$LogFile=".\ADS_MoveUsersToCompanyOU.txt"
 
$strFilter = "(&(objectCategory=User))"
 
$objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$RootOU"
 
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "OneLevel"
 
$colProplist = "name", "company", "sAMAccountName", "cn"
 
Function Write-Log {
     [cmdletbinding()]
 
    Param(
     [Parameter(Position=0)]
     [ValidateNotNullOrEmpty()]
     [string]$Message
     )
 
     Write-Host $Message
  Write-Output "$(Get-Date) $Message" | Out-File -FilePath $LogFile -Append
 
} #end function
 
 
foreach ($i in $colPropList){
 $objSearcher.PropertiesToLoad.Add($i)
 }
 
$colResults = $objSearcher.FindAll()
 
foreach ($objResult in $colResults) {
 $objItem = $objResult.Properties; 
 $strCompany = $objItem.company
 $strCN = $objItem.cn
 $strName = $objItem.name
 $strCompany = [System.Text.RegularExpressions.Regex]::Replace($strCompany,"[^1-9a-zA-Z_ ]","")
 
 Write-Log "INFO    User found         : $strName"
 Write-Log "INFO    Company            : $strCompany"
 Write-Log "INFO    Canonical Name     : $strCN"
 Write-Log "INFO    Distinguished Name : $strdistinguishedName"
 
 if (!$strCompany) {
  Write-Log "WARNING No Company Name found for User: $strName"
  }
 else {
  $fullOU = "OU=$strCompany,$RootOU"
 
  $OUExists = [ADSI]::Exists("LDAP://$fullOU")
  if ($OUExists) {
   Write-Log "INFO    OU exists already:$fullOU"
   }
  else {
   Write-Log "INFO    Creating new OU: $fullOU"
   $objDomain = [ADSI]"LDAP://$RootOU"
   $objOU = $objDomain.Create("OrganizationalUnit", "OU=$strCompany")
   try {
    $objOU.SetInfo()
    }
   catch {
    Write-Log "ERROR  Unable to set AD Info (Creating OU: $strCompany)"
    Write-Log "ERRMSG $($_.Exception.Message)"
    }
   }
   try {
    Move-ADObject -Identity "CN=$strCN,$RootOU" -TargetPath "OU=$strCompany,$RootOU"
    }
   catch {
    Write-Log "ERROR  Unable to move User:CN=$strCN,$RootOU"
    Write-Log "$($_.Exception.Message)"
    }   
  }
 }

Move list of user accounts to OU

On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("UsersList.txt", ForReading) '--- LIST OF USERNAMES
Set objOU = GetObject("LDAP://OU=UserAccounts,DC=domain,DC=com") '--- ADD YOUR PATH TO THE OU
Const ForReading = 1
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close


For Each strLine in arrFileLines
strLDAP = GetDN(strLine)
objOU.MoveHere _
    "LDAP://" & strLDAP & "", vbNullString
Next


Function GetDN(UserID) 


      Set objConn = CreateObject("ADODB.Connection")
      objConn.Provider = "ADsDSOObject"
      objConn.Open "Active Directory Provider"
      
      Dim Base, Filter, Attr, Level, Server
      Server = "DC1" '--- NAME OF DOMAIN CONTROLLER
      
      Base = " & Server & "/DC=domain,DC=com>;" '--- ADD YOUR DOMAIN
      Filter = "(&(objectClass=user)(objectCategory=person)(samAccountName=" & UserID & "));"
      Attr = "distinguishedName;"
      Level = "SubTree"
      
      Set RecordSet = objConn.Execute(Base & Filter & Attr & Level)
      
      RecordSet.MoveFirst
      While Not RecordSet.EOF
            GetDN = RecordSet.Fields(0).Value
            RecordSet.MoveNext
      Wend 

End Function 

PowerShell to Disable users account & move them to different OU using CSV

########################################################################### 
# NAME:                Script to disable users account and move them to different OU using CSV 
# AUTHOR:              Imran Pathan 
# COMMENT:             All you need is fill up the Disable user account csv with saMAccountName & OU to move to.  
# VERSION HISTORY:     1.0 
# 1.0 12/19/2012 - Initial release 
############################################################################ 
$UsersToDisbableList=IMPORT-CSV C:\Imran\DisableUsers.csv  
$PrimaryDC = 'PDC002.yourdomain.local' 
$DomainName = 'yourdomain' 
Clear-Host 
Connect-QADService -service $PrimaryDC 
 
Function DisableUsers 
{ 
    Param( 
        [string] $_SamAccountName, 
        [string] $_MoveTOOU 
        ) 
    write-host ("User: $_SamAccountName") 
    Write-Host ("Move to OU: $_MoveTOOU") 
 
Get-ADUser $_SamAccountName | Set-ADUser -Enabled $false 
Start-Sleep -s 2 
Move-QADObject -Identity $_SamAccountName -NewParentContainer $_MoveTOOU 
Start-Sleep -s 2 
} 
 
FOREACH ($User in $UsersToDisbableList) { 
    DisableUsers $User.SamAccountName $User.MoveTOOU 
}