Selenium (Powershell) Run as a different user - powershell

I want to start Selenium (Google Chrome - WebDriver) as a different user and I am pretty much lost as I don't know where to add $mycreds. This is quite easy to achieve if I want to start a normal Chrome session, however, I am stuck when it comes to achieving this using Selenium. Any advice ?
$username = "domain\name"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $password
$Driver = Start-SeChrome
Enter-SeUrl -Url 'https://www.google.com/' -Driver $Driver
If I try to pass it along using -Arguments , it will still use my account to open the browser without returning any error.
$Driver = Start-SeChrome -Arguments $mycreds

The easy way to do this is by starting Powershell as-another-user instead. Make sure you have the module set up for that user as well as any other environment stuff you might need.
The selenium-powershell module itself does not support starting the selenium drivers as a different user from the current one.
You may also want to make sure you're using an updated version of the module as well, since (in pre-release):
Start-SeChrome and other have been removed in favor of Start-SeDriver -Browser Chrome (#100)

Related

Powershell script unable to decrypt password from Jenkins withCredentials()

I created a powershell script to run DB2 queries in Jenkins
withCredentials([usernamePassword(credentialsId: 'cred-id', usernameVariable: 'ID', passwordVariable: 'PASSWORD')]) {
$cn = new-object system.data.OleDb.OleDbConnection("Server=Server; Provider=IBMDADB2;DSN=DBName;User Id=$ID;Password=$PASSWORD");
$ds = new-object "System.Data.DataSet" "ds"
$q = "myQuery"
$da = new-object "System.Data.OleDb.OleDbDataAdapter" ($q, $cn)
$da.Fill($ds)
$cn.close()
}
If I run the script and hard code my credentials, it run fine.
With withCredentials(), I am getting the following error: Security processing failed with reason "15" ("PROCESSING FAILURE")
From some research, the error seems to be because DB2 can't handle encrypted data. Is there a way to overcome this error?
EDIT:
I tried to add
$SecurePassword = ConvertTo-SecureString $PASSWORD -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
at the beginning of my powershell script, but it still throws the same error even though the credential work fine if used in plain text
If I understand the docs for the Credentials Binding Jenkins plugin correctly, the variables designated in the withCredentials() call become environment variables, so as to enable their use across process boundaries.
Note that the values of these environment variables are not encrypted, so no extra (decryption) effort is required on the part of the target process.
Therefore, you need to use $env:[1] instead of just $ to refer to these variables in PowerShell:
$cn = new-object system.data.OleDb.OleDbConnection "Server=Server; Provider=IBMDADB2;DSN=DBName;User Id=$env:ID;Password=$env:PASSWORD"
[1] See the conceptual about_Environment_Variables help topic.

Powershell setting new local users forced password change

Afternoon folks,
I've got a quick question. I'm making a script to make local user accounts based off a csv file. I have it all working no problem using the New-LocalUser command. What I am curious about is there a parameter string I can add or anything to have it so the user Has to change the password upon first login?
I've looked through https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/new-localuser?view=powershell-5.1 I just was wondering if there was something I've missed.
You haven't. Most of the time, when cmdlets are released, they don't include all functionality for a particular technology (e.g. Get-Service versus Win32_Service). In this case, New-LocalUser, Get-LocalUser, Set-LocalUser are in this boat.
However, in order to achieve what you're after, the WinNT provider has exposed this functionality for a long time:
$u = New-LocalUser -Name test -Password ('123456789' | ConvertTo-SecureString -AsPlainText -Force)
$WinNt = [adsi]"WinNT://localhost/$($u.Name)"
$WinNt.PasswordExpired = 1
$WinNt.SetInfo()

What is the best way to store account credentials (especially password) for an automated email script?

I am writing a simple script (windows powershell) to send automated emails. A computer will be running at all times collecting data and then sending emails at regular intervals. Part of sending an email obviously is collecting credentials, and since its automated we cant have somebody there everytime to enter the user and password. The obvious solution is to just store info in $user and $pass vars in the script but this seems horribly unsafe to me, and prone to attacks. Is there any better way to do this? Maybe setup a secure email connection once with the user address and not have to enter it in again? I am new to powershell so im not really clear on the best ways to do this. Currently what I am doing is:
$from = 'UserEmail#anotherEmail.com'
$to = 'someEmail#SomeMail.com'
$smtpServer = 'smtp-mail.outlook.com'
$smtpPort = '587'
$mailSubject = 'PowerShell Script Email Test'
$password = 'p#ssword'
$mailBody = 'body text'
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $from, $($password | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -To "$to" -From "$from" -Subject $mailSubject -SmtpServer $smtpServer -UseSsl -Credential $credentials -BodyAsHtml -Body $mailBody
Any advice or documentation to read would be much appreciated
You may want to investigate the Protect-CMSMessage cmdlet, which allows you to encrypt/decrypt data using public key cryptography so that only users with the correct certificate would be able to decrypt the password.
If that seems like overkill, another, easier but possibly less secure, option is to export the credentials to XML and read them back when required.
To create the file, do this:
Log on as the user the script will be running as
Execute this command: Get-Credential | Export-CliXml <path>\cred.xml
When prompted enter the username/password to be used in the script
The resulting XML file will have the username and password securely stored and can be read back like this:
$cred = Import-CliXml <path>\cred.xml
You can then pass $cred to any cmdlet that has a -Credential parameter.
The password is encrypted in such a way that it can only be opened by the same user on the same computer, so if someone else opens it they won't be able to access the details. Obviously, if they can log on as the user who encrypted it (or convince that user to run a 'bad' script), then they will have access to the details, but otherwise this is pretty secure.
A third option is to use the built-in Credential Manager in Windows. This needs some complicated .NET interop for older systems, but luckily some nice person has already done the hard work for you:
PowerShell Credentials Manager
This is a bit easier in Windows 10:
PasswordVault Class

access sharepoint REST api using powershell with windows authentication

I have a sharepoint 2013 server, which I can log into using Windows Authentication via a web-browser. When I have logged on using my browser, if I then - using that same browser - browse to http://mysharepointserver/_api/web I get some useful XML.
However, I want to write a powershell script that uses this XML. To that end, following the suggestions from this page:
How to make an authenticated web request in Powershell?
I wrote the following code:
$PWord = ConvertTo-SecureString –String "MyAwesomePassword" –AsPlainText -Force
$creds = New-Object System.Net.NetworkCredential("MyUserName",$PWord,"TheDomain")
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $creds
$url = "http://mysharepointserver/_api/web"
$output = $webclient.DownloadString($url)
echo $output
However, when I run this code, I get the error message:
Exception calling "DownloadString" with "1" argument(s): "The remote server returned an error: (403) Forbidden."
Even though I can access the same URL using a web-browser, if I type in the (same) credentials using the Windows login dialog that pops up for authentication purposes.
Does anyone know if it is possible to do this using Powershell?
thanks heaps all
Why aren't you using the default CMDlets that come with Powershell (unless using PS2 or lower)?
Invoke-Webrequest and Invoke-Restmethod both support the -credential switch which can be used to authenticate against the webserver.
You can also use Get-credential to store your credentials (though you can't get yhem from a file or string that way, at least not the password)
Script (in pseudo code and since i'm on my phone no code tags) would look like this :
Invoke-Restmethod -uri 'http://bla/api' -credential (get-credential)

Copying from one server to other with credentials

I'm trying to copy a file from one server to another server so that it doesn't ask me to enter my login info and I don't have to store the password blatently in the code. The problem is, it's still coming up with a credential request GUI, even though I give the -Credential parameter. This is how I store the password in a file:
read-host -assecurestring | convertfrom-securestring | out-file C:\secString.txt
Then the code looks like this:
function GetSecureLogin() {
$username = "usa02xxxswg2\20xbackup"
$password = get-content C:\secString.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
}
function CopyFileToFolder ([string]$Source, [string]$destination){
Copy-Item "$Source" -Destination "$destination" -Credential $cred #this is where the login info box is coming up but shouldn't be
}
######################start here#####################
$cred = ""
GetSecureLogin
$tempSource = "filename.txt"
$ToLocation = "$ToLoc"
CopyFileToFolder $tempSource $ToLoc
Any ideas? I'm relatively new to PowerShell, so I could be doing something silly. I'm not sure how to tell if $cred is getting back to my Copy function ok or if it's out of scope.
I've looked at these examples but I'm having trouble deciding if I need to do something different because they are specifying the server info and I'm trying to avoid that since I just want to use UNC path like I was doing before. The copying was working fine without login because I was using my Active Directory login to save the task. Now we want to use a locally saved login (where the script is run) and then it needs a different local login when it's trying to access the other server.
copy-item with alt cred,
powershell without prompt for cred,
copy without cred,
copy with alt cred,
cred without password prompt
I'm trying to figure out if returning $cred from my GetSecureLogin function, and assigning it to $cred in the main part of the script will fix the problem where it's asking me for the login info when I do the copy. It looks like my co-worker moved all the directories, so I still have to test this once I figure out where he moved them to.
Looks like I figured it out. I did it like this link. It was a little tricky in that I didn't have to use the directory that came after my sharename, but once I got rid of the subdirectory, it worked.
copy with credentials and New-PSDrive