IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Scripts/Batch Discussion :

Cacher mot de passe dans script d'envoi de mail [PowerShell]


Sujet :

Scripts/Batch

  1. #1
    Membre du Club
    Homme Profil pro
    Analyse système
    Inscrit en
    Octobre 2016
    Messages
    65
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loiret (Centre)

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Octobre 2016
    Messages : 65
    Points : 49
    Points
    49
    Par défaut Cacher mot de passe dans script d'envoi de mail
    Bonjour,

    Grâce à pas mal de forum, j'ai réussi à faire un script d'envoi de mail. Jusque la tout va bien et tout fonctionne. Sauf que le mot de passe du compte émetteur apparaît en clair dans le script, y a t-il possibilité de le cacher dans le script ou sinon lors de l’exécution du script, qu'une fenêtre s'affiche et demande l'@mail ainsi que le mot de passe pour le compte émetteur ?

    Voici mon script :

    Code powershell : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $From = "mymail@gmail.com"
    $To = "tomail@mymail.com"
    $SMTPServer = "smtp.gmail.com"
    $SMTPPort = 587
    $Username = "mymail@gmail.com"
    $subject = "mysubject"
    $body = "mymessage"
     
    $mdp = "mypwd"
    $PWord = ConvertTo-SecureString –String $mdp –AsPlainText -Force
    $Credential = New-Object System.Management.Automation.PSCredential ($Username, $PWord)
    Send-MailMessage -To $To -From $From -Subject $subject -SmtpServer $SMTPServer -Body $body -Credential $Credential  -Port $SMTPPort -UseSsl

    Merci par avance et bonne journée

    Alexis

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    105
    Détails du profil
    Informations personnelles :
    Âge : 56
    Localisation : Suisse

    Informations forums :
    Inscription : Septembre 2007
    Messages : 105
    Points : 145
    Points
    145
    Par défaut
    Bonjour,

    Tu peux utiliser la commande Get-Credential.
    Attention la propriété Password sera du type SecureString.

    Voici un exemple pour récupérer un mot de passe avec cette commande:
    Code PowerShell : Sélectionner tout - Visualiser dans une fenêtre à part
    $myPassword = (Get-Credential).Password

    Par contre si tu ne dois pas créer un courriel complexe, il y a aussi la commande Send-Email.

    Salutations.

  3. #3
    Membre du Club
    Homme Profil pro
    Analyse système
    Inscrit en
    Octobre 2016
    Messages
    65
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loiret (Centre)

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Octobre 2016
    Messages : 65
    Points : 49
    Points
    49
    Par défaut
    Salut,

    Donc avec le code que tu m'as donné, sur la fenêtre qui s'ouvre, j'ai juste besoin de remplir le champ mot de passe du coup ?

    Ou je peut aussi faire en sorte de mettre le champ identifiant dans une variable avec la même fenêtre ?

    Merci

  4. #4
    Expert éminent
    Avatar de hackoofr
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2009
    Messages
    3 839
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Juin 2009
    Messages : 3 839
    Points : 9 222
    Points
    9 222

  5. #5
    Membre habitué
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    105
    Détails du profil
    Informations personnelles :
    Âge : 56
    Localisation : Suisse

    Informations forums :
    Inscription : Septembre 2007
    Messages : 105
    Points : 145
    Points
    145
    Par défaut
    Bonjour,

    Tu demandais un mot de passe, je t'ai proposé un mot de passe.

    Non, plus sérieusement, tu n'es pas obligé de récupérer uniquement la propriété Password. Tu peux effectivement obtenir tout l'objet, puis travailler avec les différentes propriétés.
    La commande Get-Member et la méthode GetType() te permettront de mieux appréhender les possibilités.

    La commande Get-Member te permet de connaître les membres d'un objet et avec le paramètre -Force (pour le côté obscure) les membres cachés.
    La méthode GetType() pour connaître le type de l'objet en question. ^^
    Code PowerShell : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    $myCredential = Get-Credential
    $myCredential | Get-Member
     
       TypeName : System.Management.Automation.PSCredential
     
    Name                 MemberType Definition
    ----                 ---------- ----------
    Equals               Method     bool Equals(System.Object obj)
    GetHashCode          Method     int GetHashCode()
    GetNetworkCredential Method     System.Net.NetworkCredential GetNetworkCredential()
    GetObjectData        Method     void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingCont...
    GetType              Method     type GetType()
    ToString             Method     string ToString()
    Password             Property   securestring Password {get;}
    UserName             Property   string UserName {get;}
     
    $myCredential.GetType()
     
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     PSCredential                             System.Object

    Comme tu peux le voir, si tu enregistres l'objet PSCredential résultant de la commande Get-Credential, tu pourras accéder au nom d'utilisateur avec la propriété UserName et au mot de passe avec la propriété Password.

    Salutations.

  6. #6
    Expert éminent
    Avatar de hackoofr
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2009
    Messages
    3 839
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Juin 2009
    Messages : 3 839
    Points : 9 222
    Points
    9 222
    Par défaut

    Après avoir lu cet article :
    1. Secure Password with PowerShell: Encrypting Credentials – Part 1
    2. Secure Password with PowerShell: Encrypting Credentials – Part 2

    On peut alors, créer ce script en deux étapes : La 1ère étape, peut se faire une seule fois et qui consiste à créer une clé de crypatge AES qui nous permet de crypter notre mot de passe et l'enregistrer dans un fichier.

    1 ère étape :
    Code Powershell : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #################################### First 1 Step ###########################################
    # First Step we encrypt the Plain Text Password to an encrypted one using the key AES.key
    # Première étape, nous cryptons le mot de passe en clair vers un mot de passe chiffré
    # à l'aide de la clé AES.key
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $KeyFile = $AppData+"\AES.key"
    $Key = New-Object Byte[] 32   # You can use 16, 24, or 32 for AES 
    [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
    $Key | out-file $KeyFile
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $Key = Get-Content $KeyFile
    $Password = Read-Host "Please Enter your Gmail Password to be encrypted " -AsSecureString | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
    #################################### First 1 Step ###########################################

    2 ème étape :

    Nous envoyons le courrier électronique avec les informations d'identification cryptés.
    Juste changer ces deux variables $GmailUserName et $EmailFrom
    Code Powershell : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #################################### Second 2 Step ##########################################
    # We send the email with our encrypted Credentials
    # You have to change in this sctipt just two variables to yours
    # $GmailUserName = "YourGmailAccount" and $EmailTo = "AnotherEmail@yahoo.fr" just all
    # Nous envoyons le courrier électronique avec les informations d'identification cryptés
    #################################### Second 2 Step ##########################################
    $GmailUserName = "YourGmailAccount"
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $keyFile = $AppData+"\AES.Key"
    $key = Get-Content $KeyFile
    $GmailEncryptedPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key
    $Credentials = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList($GmailUserName,$GmailEncryptedPassword)
    $EmailFrom = $GmailUserName+"@gmail.com"
    $EmailTo = "AnotherEmail@yahoo.fr"
    $Subject = "Subject from the sender"
    $Body = (Get-Date -format F)  + "  Hello ! the sending email is working now !"
    $SMTPServer = "smtp.gmail.com"
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,587)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = $Credentials
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
    #################################### Second 2 Step ##########################################

  7. #7
    Expert éminent
    Avatar de hackoofr
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2009
    Messages
    3 839
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Juin 2009
    Messages : 3 839
    Points : 9 222
    Points
    9 222
    Par défaut Gmail_Batch_PS_Sender.bat

    J'ai fait un code hybrid Batch et PowerShell pour envoyer l'email , juste vous copiez ce code en tant que fichier batch Gmail_Batch_PS_Sender.bat
    Code BAT : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    <# : Batch portion
    @rem # The previous line does nothing in Batch, but begins a multiline comment block
    @rem # in PowerShell.  This allows a single script to be executed by both interpreters.
    @echo off & Mode 100,5 & color 0A
    Title Sending E-mail with SSL Authentification with an Hybrid code Batch and Powershell Script by Hackoo
    echo(
    rem # This a Powershell command executes the hybrid portion at the bottom of this script
    for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do set "%%I"
    exit /b
    rem # End multi-line PowerShell comment block.  Begin PowerShell scripting.
    : end Batch / begin PowerShell hybrid code #>
    #################################### First 1 Step ###########################################
    # First Step we encrypt the Plain Text Password to an encrypted one using the key AES.key
    # Première étape, nous cryptons le mot de passe en clair vers un mot de passe chiffré
    # à l'aide de la clé AES.key
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $KeyFile = $AppData+"\AES.key"
    $Key = New-Object Byte[] 32   # You can use 16, 24, or 32 for AES 
    [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
    $Key | out-file $KeyFile
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $Key = Get-Content $KeyFile
    $GmailUserName = Read-Host "Please enter your Gmail Account without ""@gmail.com"" "
    $Password = Read-Host "Please enter your Gmail Password to be encrypted " -AsSecureString `
    | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
    #################################### First 1 Step ###########################################
     
    #################################### Second 2 Step ##########################################
    # We send the email with our encrypted Credentials
    # Nous envoyons le courrier électronique avec les informations d'identification cryptés
    #############################################################################################
    Function Show-BalloonTip {
      [CmdletBinding(SupportsShouldProcess = $true)]
      param (
        [Parameter(Mandatory=$true)]$Text,
        [Parameter(Mandatory=$true)]$Title,   
        [ValidateSet('None', 'Info', 'Warning', 'Error')]$Icon = 'Info',
        $Timeout = 10000
      )
      Add-Type -AssemblyName System.Windows.Forms
     
      if ($script:balloon -eq $null) { $script:balloon = New-Object System.Windows.Forms.NotifyIcon }
     
      $path                    = Get-Process -id $pid | Select-Object -ExpandProperty Path
      $balloon.Icon            = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
      $balloon.BalloonTipIcon  = $Icon
      $balloon.BalloonTipText  = $Text
      $balloon.BalloonTipTitle = $Title
      $balloon.Visible         = $true
      $balloon.ShowBalloonTip($Timeout)
      Start-Sleep -s 10
      $balloon.Dispose()
    }
    ################################################################################################
    function Show-Message {
     
    param (
        [string]$Message = "Veuillez entrer votre message",
        [string]$Titre = "Titre de la fenêtre",
        [switch]$OKCancel,
        [switch]$AbortRetryIgnore,
        [switch]$YesNoCancel,
        [switch]$YesNo,
        [switch]$RetryCancel,
        [switch]$IconErreur,
        [switch]$IconQuestion,
        [switch]$IconAvertissement,
        [switch]$IconInformation
        )
     
    # Affecter la valeur selon le type de boutons choisis
    if ($OKCancel) { $Btn = 1 }
    elseif ($AbortRetryIgnore) { $Btn = 2 }
    elseif ($YesNoCancel) { $Btn = 3 }
    elseif ($YesNo) { $Btn = 4 }
    elseif ($RetryCancel) { $Btn = 5 }
    else { $Btn = 0 }
     
    # Affecter la valeur pour l'icone 
    if ($IconErreur) {$Icon = 16 }
    elseif ($IconQuestion) {$Icon = 32 }
    elseif ($IconAvertissement) {$Icon = 48 }
    elseif ($IconInformation) {$Icon = 64 }
    else {$Icon = 0 }
     
    # Charger la biblithèque d'objets graphiques Windows.Forms
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
     
    # Afficher la boite de dialogue et renvoyer la valeur de retour (bouton appuyé)
    $Reponse = [System.Windows.Forms.MessageBox]::Show($Message, $Titre , $Btn, $Icon)
    Return $Reponse
    }
    ################################################################################################
    $SuccessMsg = "The email was sent successfully ; Please, check your email !"
    $FailureMsg = "ERROR occurred while sending the email"
    $AppData = [Environment]::GetFolderPath('ApplicationData')
    $PasswordFile = $AppData+"\Password.txt"
    $keyFile = $AppData+"\AES.Key"
    $key = Get-Content $KeyFile
    $GmailEncryptedPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key
    $Credentials = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList($GmailUserName,$GmailEncryptedPassword)
    $EmailFrom = $GmailUserName+"@gmail.com"
    $EmailTo = $EmailFrom
    $Subject = "Sending E-mail with SSL Authentification with an Hybrid code Batch and Powershell Script"
    $Body = (Get-Date -format F)  + "  Hello ! the sending email is working now with PowerShell and Batch Script!"
    $SMTPServer = "smtp.gmail.com"
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,587)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = $Credentials
    try
    {
      $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
      Show-Message -Message $SuccessMsg -Titre $SuccessMsg -IconInformation
      Show-BalloonTip -Text $SuccessMsg -Title $SuccessMsg -Icon 'Info'
    }
    catch
    {
      Show-Message -Message $_.Exception.Message -Titre $FailureMsg -IconErreur
      Show-BalloonTip -Text $_.Exception.Message -Title 'ERROR occurred while sending the email' -Icon 'Error' 
    }
    exit(1)

  8. #8
    Membre du Club
    Homme Profil pro
    Analyse système
    Inscrit en
    Octobre 2016
    Messages
    65
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loiret (Centre)

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Octobre 2016
    Messages : 65
    Points : 49
    Points
    49
    Par défaut
    Bonjour,

    Merci pour vos réponses. C'est exactement ce dont j'avais besoin. Je vais tester les différentes façons que vous m'avez proposé.

    Un grand merci pour votre aide

    Alexis

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Cacher un mot de passe dans un script
    Par sky2orion dans le forum Général Python
    Réponses: 3
    Dernier message: 23/12/2016, 20h46
  2. Mot de passe dans script
    Par Lyude dans le forum Général Python
    Réponses: 5
    Dernier message: 20/01/2014, 18h21
  3. Envoi login et mot de passe dans une URL
    Par xssoum dans le forum Android
    Réponses: 2
    Dernier message: 17/03/2011, 15h14
  4. Login et mot de passe dans un script
    Par Safaritn dans le forum Applications et environnements graphiques
    Réponses: 7
    Dernier message: 06/12/2007, 08h06
  5. Mettre un mot de passe dans script
    Par jeanbi dans le forum Shell et commandes GNU
    Réponses: 4
    Dernier message: 18/01/2007, 17h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo