Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Скриптовые языки администрирования Windows (http://forum.oszone.net/forumdisplay.php?f=102)
-   -   [решено] KEEPASS из powershell (http://forum.oszone.net/showthread.php?t=293209)

red.army@vk 29-12-2014 06:28 2449421

KEEPASS из powershell
 
Наверное многие, для хранения паролей пользователей пользуются KeePass . Недавно наткнулся на статью, со скриптом powershell, с помощью которого можно получать необходмые строки из базы Keepass.

Код:

param(

    $PathToKeePassFolder = "C:\Program Files (x86)\KeePass Password Safe 2"
)
#Load all .NET binaries in the folder
(Get-ChildItem -recurse $PathToKeePassFolder|Where-Object {($_.Extension -EQ ".dll") -or ($_.Extension -eq ".exe")} | ForEach-Object { $AssemblyName=$_.FullName; Try {[Reflection.Assembly]::LoadFile($AssemblyName) } Catch{ }} ) | out-null

<#
.Synopsis
  Finds matching EntryToFind in KeePass DB
.DESCRIPTION
  Finds matching EntryToFind in KeePass DB using Windows Integrated logon
.EXAMPLE
  Example of how to use this cmdlet
  FindPasswordInKeePassDB -PathToDB "C:\Powershell\PowerShell.kdbx" -EntryToFind "MasterPassword"
#>

Function Find-PasswordInKeePassDB
{
    [CmdletBinding()]
    [OutputType([String[]])]

    param(

        $PathToDB = "C:\Powershell\PowerShell.kdbx",
        $EntryToFind = "MasterPassword"
    )

    $PwDatabase = new-object KeePassLib.PwDatabase

    $m_pKey = new-object KeePassLib.Keys.CompositeKey
    $m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpUserAccount))

    $m_ioInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
    $m_ioInfo.Path = $PathToDB

    $IStatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger

    $PwDatabase.Open($m_ioInfo,$m_pKey,$IStatusLogger)

   
    $pwItems = $PwDatabase.RootGroup.GetObjects($true, $true)
    foreach($pwItem in $pwItems)
    {
        if ($pwItem.Strings.ReadSafe("Title") -eq $EntryToFind)
        {
            $pwItem.Strings.ReadSafe("Password")
        }
    }
    $PwDatabase.Close()

}

<#
.Synopsis
  Short description
.DESCRIPTION
  Long description
.EXAMPLE
  Example of how to use this cmdlet
  FindPasswordInKeePassDBUsingPassword -EntryToFind "domain\username" -PasswordToDB myNonTopSeceretPasswordInClearText
.EXAMPLE
  Find password using Integrated logon to get master password and then use that to unlock and find the password in the big one.
  FindPasswordInKeePassDBUsingPassword -EntryToFind "domain\username" -PasswordToDB (FindPasswordInKeePassDB -EntryToFind "MasterPassword")
#>
function Find-PasswordInKeePassDBUsingPassword
{
    [CmdletBinding()]
    [OutputType([String[]])]
    Param
    (
        # Path To password DB
        $PathToDB = "\\unc-path\Passwords\Passwords.kdbx",
        # Entry to find in DB
        $EntryToFind = "mattias",
        # Password used to open KeePass DB       
        [Parameter(Mandatory=$true)][String]$PasswordToDB
    )

    $PwDatabase = new-object KeePassLib.PwDatabase

    $m_pKey = new-object KeePassLib.Keys.CompositeKey
    $m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpPassword($PasswordToDB)));

    $m_ioInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
    $m_ioInfo.Path = $PathToDB

    $IStatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger

    $PwDatabase.Open($m_ioInfo,$m_pKey,$IStatusLogger)

   
    $pwItems = $PwDatabase.RootGroup.GetObjects($true, $true)
    foreach($pwItem in $pwItems)
    {
        if ($pwItem.Strings.ReadSafe("Title") -eq $EntryToFind)
        {
            $pwItem.Strings.ReadSafe("Password")
        }
    }
    $PwDatabase.Close()
    $PasswordToDB = $null

}

Но хотелось бы еще и создавать новые...
Есть метод AddEntry, как им воспользоваться?

Код:

TypeName: KeePassLib.PwGroup

Name                        MemberType Definition                                                                                                                                                         
----                        ---------- ----------                                                                                                                                                         
AddEntry                    Method    void AddEntry(KeePassLib.PwEntry pe, bool bTakeOwnership), void AddEntry(KeePassLib.PwEntry pe, bool bTakeOwnership, bool bUpdateLocationChangedOfEntry)           
AddGroup                    Method    void AddGroup(KeePassLib.PwGroup subGroup, bool bTakeOwnership), void AddGroup(KeePassLib.PwGroup subGroup, bool bTakeOwnership, bool bUpdateLocationChangedOfSub) 
AssignProperties            Method    void AssignProperties(KeePassLib.PwGroup pgTemplate, bool bOnlyIfNewer, bool bAssignLocationChanged)                                                               
BuildEntryTagsDict          Method    System.Collections.Generic.IDictionary[string,uint32] BuildEntryTagsDict(bool bSort)                                                                               
BuildEntryTagsList          Method    System.Collections.Generic.List[string] BuildEntryTagsList(), System.Collections.Generic.List[string] BuildEntryTagsList(bool bSort)                               
CloneDeep                    Method    KeePassLib.PwGroup CloneDeep(), KeePassLib.PwGroup IDeepCloneable[PwGroup].CloneDeep()                                                                             
CloneStructure              Method    KeePassLib.PwGroup CloneStructure()                                                                                                                                 
CreateNewItemUuids          Method    void CreateNewItemUuids(bool bNewGroups, bool bNewEntries, bool bRecursive)                                                                                         
DeleteAllObjects            Method    void DeleteAllObjects(KeePassLib.PwDatabase pdContext)                                                                                                             
Duplicate                    Method    KeePassLib.PwGroup Duplicate()                                                                                                                                     
EnableStringFieldProtection  Method    bool EnableStringFieldProtection(string strFieldName, bool bEnable)                                                                                                 
Equals                      Method    bool Equals(System.Object obj)                                                                                                                                     
EqualsGroup                  Method    bool EqualsGroup(KeePassLib.PwGroup pg, KeePassLib.PwCompareOptions pwOpt, KeePassLib.MemProtCmpMode mpCmpStr)                                                     
FindCreateGroup              Method    KeePassLib.PwGroup FindCreateGroup(string strName, bool bCreateIfNotFound)                                                                                         
FindCreateSubTree            Method    KeePassLib.PwGroup FindCreateSubTree(string strTree, char[] vSeparators), KeePassLib.PwGroup FindCreateSubTree(string strTree, char[] vSeparators, bool bAllowCrea...
FindEntriesByTag            Method    void FindEntriesByTag(string strTag, KeePassLib.Collections.PwObjectList[KeePassLib.PwEntry] listStorage, bool bSearchRecursive)                                   
FindEntry                    Method    KeePassLib.PwEntry FindEntry(KeePassLib.PwUuid uuid, bool bSearchRecursive)                                                                                         
FindGroup                    Method    KeePassLib.PwGroup FindGroup(KeePassLib.PwUuid uuid, bool bSearchRecursive)                                                                                         
FindObject                  Method    KeePassLib.Interfaces.IStructureItem FindObject(KeePassLib.PwUuid uuid, bool bRecursive, System.Nullable[bool] bEntries)                                           
GetAutoTypeEnabledInherited  Method    bool GetAutoTypeEnabledInherited()                                                                                                                                 
GetAutoTypeSequenceInherited Method    string GetAutoTypeSequenceInherited()                                                                                                                               
GetCounts                    Method    void GetCounts(bool bRecursive, [ref] uint32 uNumGroups, [ref] uint32 uNumEntries)                                                                                 
GetEntries                  Method    KeePassLib.Collections.PwObjectList[KeePassLib.PwEntry] GetEntries(bool bIncludeSubGroupEntries)                                                                   
GetEntriesCount              Method    uint32 GetEntriesCount(bool bRecursive)                                                                                                                             
GetFlatGroupList            Method    System.Collections.Generic.LinkedList[KeePassLib.PwGroup] GetFlatGroupList()                                                                                       
GetFullPath                  Method    string GetFullPath(), string GetFullPath(string strSeparator, bool bIncludeTopMostGroup)                                                                           
GetGroups                    Method    KeePassLib.Collections.PwObjectList[KeePassLib.PwGroup] GetGroups(bool bRecursive)                                                                                 
GetHashCode                  Method    int GetHashCode()                                                                                                                                                   
GetLevel                    Method    uint32 GetLevel()                                                                                                                                                   
GetObjects                  Method    System.Collections.Generic.List[KeePassLib.Interfaces.IStructureItem] GetObjects(bool bRecursive, System.Nullable[bool] bEntries)                                   
GetSearchingEnabledInherited Method    bool GetSearchingEnabledInherited()                                                                                                                                 
GetType                      Method    type GetType()                                                                                                                                                     
IsContainedIn                Method    bool IsContainedIn(KeePassLib.PwGroup pgContainer)                                                                                                                 
SearchEntries                Method    void SearchEntries(KeePassLib.SearchParameters sp, KeePassLib.Collections.PwObjectList[KeePassLib.PwEntry] listStorage), void SearchEntries(KeePassLib.SearchParam...
SetCreatedNow                Method    void SetCreatedNow(bool bRecursive)                                                                                                                                 
SortSubGroups                Method    void SortSubGroups(bool bRecursive)                                                                                                                                 
TakeOwnership                Method    void TakeOwnership(bool bTakeSubGroups, bool bTakeEntries, bool bRecursive)                                                                                         
ToString                    Method    string ToString()                                                                                                                                                   
Touch                        Method    void Touch(bool bModified), void Touch(bool bModified, bool bTouchParents), void ITimeLogger.Touch(bool bModified)                                                 
TraverseTree                Method    bool TraverseTree(KeePassLib.TraversalMethod tm, KeePassLib.Delegates.GroupHandler groupHandler, KeePassLib.Delegates.EntryHandler entryHandler)


Kazun 29-12-2014 09:23 2449441

Код:

$general = $PwDatabase.RootGroup.FindGroup($PwDatabase.RootGroup.Groups.Uuid[0].UuidBytes,0)
               
$ent = New-Object KeePassLib.PwEntry($general , $true , $true)
       
$title = New-Object KeePassLib.Security.ProtectedString($true , "Title")
$pass = New-Object KeePassLib.Security.ProtectedString($true , "Password")
$user = New-Object KeePassLib.Security.ProtectedString($true , "UserName")
       
$ent.Strings.Set("Title",$title)
$ent.Strings.Set("Password",$pass)
$ent.Strings.Set("UserName",$user)
       
$general.AddEntry($ent,1)
$PwDatabase.Save($IStatusLogger)


red.army@vk 29-12-2014 12:02 2449502

Работает))))) Казун вы БОГ повершелла... Как вы это сделали?
http://keepassps.codeplex.com/ может добавите сюда?


Время: 20:50.

Время: 20:50.
© OSzone.net 2001-