1 / 41

Windows Powershell : Automatiser votre administration système

Windows Powershell : Automatiser votre administration système. Mardi 8 février 2011. Arnaud PETITJEAN Consultant et formateur PowerShell-Scripting.com. Jacques BARATHON Consultant et formateur PowerShell-Scripting.com. Agenda. La Communauté PowerShell francophone

minya
Download Presentation

Windows Powershell : Automatiser votre administration système

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Windows Powershell : Automatiser votre administration système Mardi 8 février 2011 Arnaud PETITJEAN Consultant et formateur PowerShell-Scripting.com Jacques BARATHON Consultant et formateur PowerShell-Scripting.com

  2. Agenda • La Communauté PowerShell francophone • Introduction sur Windows PowerShell • Les principaux éléments du langage • Administration de l’Active Directory • Les différentes techniques de Remoting • Q&A

  3. La Communauté Francophone Entrez dans la communauté francophone • News • Tutoriaux • Scripts • Forum

  4. Un forum vivant ! Profitez d’un partage de connaissances avec les plus grands spécialistes français

  5. La Galaxie PowerShell 

  6. Toute l’industrie informatique s’y met !

  7. Windows PowerShell • Interpréteur de commandes • Jeu de commandes normalisé • Jeu de paramètres normalisé • Langage de scripts • Concision des scripts • Comparaison avec VBScript • Sécurisé dès la conception • Règles d’exécution des scripts • S’appuie sur le Framework .NET 2.0 • Manipulation d’objets • Accès aux classes .NET • Extensibilité du langage : snap-ins, modules

  8. Un langage simple et puissant PS> get-process | where {$_.workingset -gt 100MB} | format-table name, id, handles, path -auto Name Id HandlesPath ---- -- ------- ---- OUTLOOK 2488 4708 C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE POWERPNT 1556 826 C:\Program Files\Microsoft Office\Office12\POWERPNT.EXE powershell 3656 1844 C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe PS> notepad PS> $avant = get-process PS> get-processnotepad | stop-process PS> $apres = get-process PS> compare-object $avant $apres InputObjectSideIndicator ----------- ------------- System.Diagnostics.Process (notepad) <=

  9. Filtrer: Where-Object • Examine un à un les objets transmis par le pipeline et les compare à une condition • Si la condition est remplie, l’objet est transmis à la suite du pipeline • Si la condition n’est pas remplie, l’objet n’est pas transmis • Chaque objet examiné est représenté par la variable $_ • Alias : where, ? PS > Get-Service | Where-Object {$_.Status -eq 'Stopped'} Status Name DisplayName ------ ---- ----------- Stopped AeLookupSvc Application Experience Stopped ALG Application Layer Gateway Service Stopped AppIDSvc Application Identity Stopped AxInstSV ActiveX Installer (AxInstSV) Stopped BDESVC BitLocker Drive Encryption Service Stopped bthserv Bluetooth Support Service Stopped CertPropSvc Certificate Propagation ...

  10. Traiter par lots: Foreach-Object • Exécute une série de commandes pour chaque objet transmis par le pipeline • Chaque objet transmis est représenté par la variable $_ • Alias : Foreach, % • Syntaxe : <collection> | Foreach-Object { # bloc d’instructions } • Exemple : Get-Process | foreach { "{0} démarré à {1}" –f $_.Name, $_.StartTime } ... dwm démarré à 09/21/2008 16:53:26 ehmsas démarré à 09/21/2008 16:53:36 ehtray démarré à 09/21/2008 16:53:33 explorer démarré à 09/22/2008 23:45:50 ...

  11. Trier: Sort-Object • Trie les objets transmis par le pipeline • Alias : sort PS > get-process | sort-object ID Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 0 0 0 24 0 0 Idle 696 0 60 4652 6 4 System 30 1 264 808 4 272 smss ... PS > get-process | sort-object WS –desc Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 4851 82 117108 194208 598 732,67 2488 OUTLOOK 936 84 157432 132764 420 3 988,20 1556 POWERPNT 980 20 110324 129768 289 113,32 3656 powershell 1092 44 46240 103120 339 1 154,10 2468 WINWORD ...

  12. Sélectionner: Select-Object • Sélectionne certaines propriétés des objets transmis par le pipeline, ou certains objets parmi une série • Alias : select PS > Get-Hotfix | select-object HotfixID, Description, InstalledBy HotfixID Description InstalledBy -------- ----------- ----------- KB958830 Update jbaratho07\Jacques KB2079403 Security Update NT AUTHORITY\SYSTEM ... PS > dir c:\windows | sort LastWriteTime | select -last 3 Directory: C:\windows Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 23/10/2010 16:28 1530877 WindowsUpdate.log d---- 23/10/2010 20:33 Prefetch d---- 23/10/2010 21:25 Temp

  13. Regrouper: Group-Object • Regroupe des objets transmis par le pipeline selon une (des) propriété(s) commune(s) • Alias : group PS > get-service | group-object Status Count Name Group ----- ---- ----- 75 Running {System.ServiceProcess.ServiceController, S... 84 Stopped {System.ServiceProcess.ServiceController, S... PS > get-process | group Company -noelement | sort Count -desc Count Name ----- ---- 48 Microsoft Corporation 3 Microsoft Corp. 3 2 Synaptics Incorporated 2 AMD 2 IDT, Inc. ...

  14. Mesurer: Measure-Object • Effectue des calculs sur les propriétés des objets transmis • Alias : measure PS > get-process | measure-object WorkingSet –min –max -average Count : 73 Average : 25718222,9041096 Sum : Maximum : 199229440 Minimum : 24576 Property : WorkingSet PS > get-content c:\windows\WindowsUpdate.log | measure -line -word -char Lines Words Characters ----- ----- ---------- 11503 161297 1507871

  15. Comparer: Compare-Object • Compare deux objets ou deux séries d’objets • Alias : compare PS > $anglais = ('Sophie','Ludo','Andrea','Pierre','Alex') PS > $espagnol = ('Ludo','Hubert','Lea','Sophie') PS > compare-object $anglais $espagnol InputObjectSideIndicator ----------- ------------- Hubert => Lea => Andrea <= Pierre <= Alex <= PS > compare $anglais $espagnol -IncludeEqual -ExcludeDifferent InputObjectSideIndicator ----------- ------------- Ludo == Sophie ==

  16. Démo La farandole des objets

  17. Le Couteau Suisse • Get-Command • Fournit des informations sur les commandes disponibles • Alias : gcm • Get-Help • Fournit de l’aide sur les commandes (scripts y compris) • Get-Member • Retourne les méthodes et les propriétés d’un objet • Alias : gm

  18. Démo Les 3 lames de notre Couteau Suisse

  19. Active Directory • 2 techniques pour administrer l’Active Directory : • L’API ADSI (classique) • Module Active Directory pour Windows PowerShell

  20. Module Active Directory • Installé de base sur tout DC Windows Server 2008 R2 • Installable sous Windows 7 (uniquement) via RSAT (Remote Server Administration Tools) • Le module apporte : • 76 commandelettes • Fournisseur ActiveDirectory (et son lecteur AD:) • Permet aussi d’administrer Active Directory Lightweight Domain Services (AD LDS)

  21. Module Active Directory : ADWS • Dialogue avec les ServicesWeb Active Directory (ADWS) PS> get-service –displayname '*active directory*' Status Name DisplayName ------ ---- ----------- Running ADWS Services Web Active Directory Running NTDS Services de domaine Active Directory Pensez à ouvrir une exception dans le pare-feu

  22. Active Directory Management Gateway Service (ADMGS) • ServicesWeb de Passerelle ActiveDirectory pour les anciennes versions d’Active Directory • Composantlogiciel (±1 Mo) installable sur : • DC Windows Server 2008 SP2 • DC Windows Server 2003 SP 2 / 2003 R2 SP2 • Prérequis : 1 hotfix + Framework .Net 3.5 SP 1

  23. Module Active Directory Comment accéder aux commandelettes ? • Lancer « la console » via le Menu Démarrer/Outils d’administration/Module Active Directory pour Windows PowerShell • Lancer « la console » via le Menu Démarrer/Outils d’administration/Windows PowerShell Modules • Lancer la console PowerShell classique et importer le module ActiveDirectory

  24. Module Active Directory Recherche d’objets • Plusieurs façons de faire : • Recherche basée sur un filtre au format LDAP(paramètre -LDAPFilter)Exemple: Get-ADObject -LDAPFilter '(name=admin*)' • Recherche basée sur un filtre générique(paramètre -Filter)Exemple: Get-ADObject -filter {objectclass -eq 'computer'}

  25. Module Active Directory Accès direct à un objet • On peut « adresser » un objet dès lors que l’on connait : • Son DN : CN=Jean,CN=powershell,DC=fr • Son ObjectGUID: 12f9e488-47f3-4154-b1c9-c75b9c1bf7d5 • Son SID: S-1-5-21-3628732846-2239576409-4110719840-1103 • Son SAMAccountName: Jean Exemple: Get-ADObject-Identity 12f9e488-47f3-4154-b1c9-c75b9c1bf7d5

  26. Démo Administration Active Directory

  27. L’administration à distance • Egalement appelée « Remoting » (« remote » : distant) • Avant PowerShell • Principalement de la consultation • WMI à la rescousse ! • PSExec pour l’exécution de scripts à distance • Et autres bricolages maison…

  28. L’administration à distance • Disponible dès PowerShell 1.0 • Paramètre -ComputerName • Exécute la commande sur le(s) serveur(s) distant(s) • Dans PowerShell 1.0, une seule commande : PS> get-help * -parameter computername Name ---- Get-WmiObject

  29. L’administration à distance • Paramètre -ComputerName dans PowerShell 2.0 PS> (get-help * -parameter computername).count 35  • Principe étendu à de nombreux types d’objets et d’actions Get-Process Get-Service Set-Service Get-Counter Get-EventLog Get-WinEvent Get-HotFix Write-EventLog Clear-EventLog Test-Connection Stop-Computer Restart-Computer Invoke-WmiMethod Register-WmiEvent Set-WmiInstance

  30. Démo Remoting v1

  31. L’administration à distance • Remoting avancé avec PowerShell 2.0 • Utilisation du service WinRM • Sessions « ad-hoc » (à la demande) ou persistantes • Tâches en arrière-plan (« jobs ») • Délègue l’entière exécution au serveur distant • S’intègre avec les règles de sécurité des pare-feu

  32. Le Remoting v2 • Pré-requis • PowerShell 2.0 des deux côtés • Activation explicite du Remoting sur le poste distant • Configuration de la sécurité (hors domaine) • Configurable par GPO • Les nouvelles commandes à notre disposition Enable-PSRemoting Invoke-Command New-PSSession Get-PSSession Remove-PSSession Enter-PSSession Start-Job Get-Job Wait-Job Receive-Job Stop-Job Remove-Job

  33. Démo Remoting v2

  34. Annonce Disponible sur le stand des éditions ENI

  35. MSDN et TechNet: l’essentiel des ressources techniques à portée de clic • Portail administration et infrastructure pour informaticiens • Portail de ressources technique pour développeurs http://technet.com http://msdn.com

  36. Slides de backup

  37. Démo Remoting v1 PS> gwmi win32_logicaldisk -comp frapp0028, frapp0018 -filter "drivetype=3" | select __server, deviceid, size, freespace __SERVER deviceid size freespace -------- -------- ---- --------- FRAPP0028 C: 31459717120 22950543360 FRAPP0028 D: 332708655104 25402429440 FRAPP0018 C: 8598138880 1414307840 FRAPP0018 D: 209898696704 83053187072 FRAPP0018 F: 423157035008 99024175104 PS> gwmi win32_logicaldisk -comp frapp0028, frapp0018 -filter "drivetype=3" | select __server, deviceid, @{n="Size(GB)"; e={[math]::round($_.size/1GB, 2)}}, @{n="FreeSpace(GB"; e={[math]::round($_.freespace/1GB, 2)}} __SERVER deviceid Size(GB) FreeSpace(GB) -------- -------- -------- ------------ FRAPP0028 C: 29,3 21,37 FRAPP0028 D: 309,86 23,46 FRAPP0018 C: 8,01 1,32 FRAPP0018 D: 195,48 77,35 FRAPP0018 F: 394,1 92,22 PS> gwmi Win32_ntlogevent -filter "eventidentifier=4624" | select computername, @{n="TimeWritten"; e={$_.ConvertToDateTime($_.timewritten)}}, @{n="User"; e={$_.insertionstrings[5]}} | where {$_.TimeWritten -gt (get-date).AddHours(-1)}

  38. Démo Remoting v2 PS> $demo = new-pssession -comp mce01,jbaratho07 PS> $scan = invoke-command -session $demo -scriptblock {dir c:\ *.mp3 -rec} –asjob PS> $scan.childjobs PS> $mp3 = receive-job $scan PS> $mp3 | sort pscomputername, directory PS> $mp3.count PS> $mp3 | measurelength –sum |select @{n="Sum(GB)"; e={[math]::round($_.sum / 1GB, 2)}} PS> $clean = invoke-command -session $demo -scriptblock {dir c:\ *.mp3 –rec | remove-item} –asjob

More Related