I am trying to log on to an https site using a powershell script.
I've tried using a PSCredential, but I get a 401 unauthorized error when I do.
I am providing the username and password in the script. I want it to log me in without being prompted.
What is the best way to do this? Is it best to use an httprequest?
Here's what I have so far.
$userName = "username"
$secure_password = ConvertTo-SecureString "my password" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($userName, $secure_password)
$proxy = New-WebServiceProxy -Uri "url_for_the_download" -Credential $credential
Something like this should work:
$client = New-Object System.Net.Webclient
$client.Credentials = New-Object System.Net.NetworkCredential("user","pass")
$client.DownloadFile("http://somesite.com/somefile.zip","C:\somefile.zip")
Related
I have written a script that utilizes try catch to install software on a remote computer using PowerShell.
The script tries to install the software and if successfully is supposed to send an email to the user advising of completion. All works as I had expected except for the send email section.
I am using the following simple snippet to carry out the sending of the email:
$username = "someone#example.com"
$password = "*****"
$sstr = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $sstr
$body = "Update installed successfully"
$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$name = $searcher.FindOne().Properties.mail
Send-MailMessage -To $name, "someone#example.com" -From "someone#example.com" -Subject 'Test message' -Body $body -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587
However, as I am running the script as myself (for elevated privilege's) on the remote computer the following part of the script is returning my email address and not the end users and therefore sending the email to myself and not the end user:
$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$name = $searcher.FindOne().Properties.mail
Example
echo $name
myemail#example.com
Any suggestions on how I can return the name of the user I am installing the software on instead of my own?
Thanks in advance.
I am writing a script in PowerShell that is testing login credentials to a target SharePoint 2013 URL that are passed through to an Invoke-WebRequest command that calls the URL in question. When I use -UseDefaultCredential, the returned status is a 200, but when I replace that and try the following code passed in to a -Credential property of the same command, I get a 401 error:
[string][ValidateNotNullOrEmpty()] $userPassword = "password"
[SecureString] $userPassword = ConvertTo-SecureString -String $userPassword -AsPlainText -Force
[PSCredential] $userCredential = New-Object -TypeName
System.Management.Automation.PSCredential("userName", $userPassword)
Invoke-Webrequest -Credential $userCredential -uri "https://connect.adler.edu"
powershell -noexit
Any thoughts as to why I'm getting the 401 Error when using the -Credential property? Thank you!
When I try to connect to tfs the function Get-Data failed with 401 error although the function Get-DataWithCred succeed with the same argument.
And don't understand the difference with this two ?
function Get-Data([string]$username, [string]$password, [string]$url)
{
# Step 1. Create a username:password pair
$credPair = "$($username):$($password)"
# Step 2. Encode the pair to Base64 string
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
# Step 3. Form the header and add the Authorization attribute to it
$headers = #{ Authorization = "Basic $encodedCredentials" }
# Step 4. Make the GET request
$responseData = Invoke-WebRequest -Uri $url -Method Get -Headers $headers
return $responseData
}
function Get-DataWithCred([string]$username, [string]$password, [string]$url)
{
$p = ConvertTo-SecureString -String $password -AsPlainText -Force
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $p
$responseData = Invoke-WebRequest -Uri $url -Method Get -Credential $Cred
return $responseData
}
The purpose is too connect through tfs with python script who failed the same way that the function Get-Data when I use the requests library.
>>> r = requests.get('https://tfs-url.com', auth=('user', 'pass'))
>>> r.status_code
401
Looks like there is a problem with $encodedCredentials.
Take a look at Choosing the right authentication mechanism
For my script who connect to TFS i use the following code :
$strUser = 'domain\userID'
$password = "YOURPASSWORD"
$strPass = ConvertTo-SecureString -String $password -AsPlainText -Force
$cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)
And than connect to the TFS as you did :
$responseData = Invoke-WebRequest -Uri $url -Method Get -Credential $cred
Or, If you would like to connect to the TFS with the user who runs the script you can use
-UseDefaultCredentials
code snippet :
$responseData = Invoke-WebRequest -Uri $url -Method Get -UseDefaultCredentials
You need to use a microsoft way to pass your credential : the ntlm protocol.
This protocol are not supported by default by requests but a library requests_ntlm extend requests by adding support to ntlm.
A simple example:
import os
import requests
from requests_ntlm import HttpNtlmAuth
def main():
user = "user"
password = "password"
session = requests.Session()
session.auth = HttpNtlmAuth(user, password)
url = "https://tfs-url.com"
response = session.get(url)
print(response)
if __name__ == "__main__":
main()
I would like to login to Power BI Online service and remove rows from a dataset using the REST API. I have the rest of the code going fine but the login seems to not work. This is what I tried. Can someone help me please? Thank you!
$pbiUsername = "abc.xyz#xxx.com"
$pbiPassword = "Password"
$clientId = "a81b2cc1-4c97-2323-bal4-eeb21c4c6e46"
$body = #{"resource" = "https://analysis.windows.net/powerbi/api"
"client_id" = $clientId;
"grant_type" = "password";
"username" = $pbiUsername;
"password" = $pbiPassword;
"scope" = "openid"
}
$authUrl = "https://login.windows.net/common/oauth2/token/"
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body
$headers = #{
"Content-Type" = "application/json";
"Authorization" = $authResponse.token_type + " " +
$authResponse.access_token
}
$restURL = "https://api.powerbi.com/v1.0/myorg/groups"
$restResponse = Invoke-RestMethod -Uri $restURL –Method GET -Headers $headers
"Login doesn't seems to work" doesn't give us enough information to hint you what is the problem.
I will recommend you to use the official Microsoft Power BI Cmdlets to do tasks like this. It has big advantage - you don't need to register an application to use it. Here is how your code would look like in this case:
Import-Module MicrosoftPowerBIMgmt
Import-Module MicrosoftPowerBIMgmt.Profile
$password = "Password" | ConvertTo-SecureString -asPlainText -Force
$username = "abc.xyz#xxx.com"
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential
Invoke-PowerBIRestMethod -Url 'groups/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/datasets/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/tables/xxxxxx/rows' -Method Delete
Disconnect-PowerBIServiceAccount
Since PowerBI now has enabled the Service Principal, you don't need to worry about the username and password and more importantly, you DON'T NEED PRO Licenses
using the Service Principal you can now able to log in without popup as well as username, password
$applicationId = "xxxxxxxx";
$securePassword = "xxxxxx" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId "xxxx"
The error is not handled with try catch - you still get the same error with this:
try {Connect-PowerBIServiceAccount} catch {"Boo"}
I follow the steps to fix this issue.
RESOLUTION
To resolve this issue, we need to install the correct module. It may not be the latest build, but the builds have to match in order for things to work for us. In my scenario, I installed the MicrosoftPowerBIMgmt.Workspaces 1.0.830 so that it matched the MicrosoftPowerBIMgmt.Profile.
I went to the PowerShell Gallery to get the Install-Module cmd.
https://www.powershellgallery.com/packages/MicrosoftPowerBIMgmt/1.0.326
From an Administrative Command-Prompt, type Install-Module -Name MicrosoftPowerBIMgmt.Workspaces -RequiredVersion 1.0.830
NOTE: Remember, for my lab scenario, I used the MicrosoftPowerBIMgmt.Workspaces Module. You will need to install the module that you are focused.
Once installed, close all PowerShell Windows or open a brand new PowerShell window and then type Get-Module. Now the installed modules should match.
NOTE: You have to start a new PowerShell session. If you don’t the error may not go away.
https://dastrongman.wordpress.com/2020/01/11/pbiwiki-login-with-the-power-bi-service-account/
I am trying to use PowerShell to log into a website and download a file.
However I can't get PS to pass the credentials properly.
Here is my PS:
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential("username","password","domain")
$webpage = $webclient.DownloadString("url goes here")
Here is the log in box I get when I hit the site in IE:
This is what I got to work. I believe the key part is the "Basic" in the CredentialCache
$webclient = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential("un","pw")
$credCache.Add("url", "Basic", $creds)
$webclient.Credentials = $credCache
$webpage = $webclient.DownloadString("url")
If you want to use Invoke-WebRequest instead of the WebClient:
$securepassword = ConvertTo-SecureString "password" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential("username", $securepassword)
Invoke-WebRequest -Uri "url goes here" -Credential $credentials
I based the code on this blog article by Douglas Tarr. Note that in the article the username and password are confused, but I've fixed them in my sample.
For some reason I wasn't able to get any of these solutions to work (using PowerShell 5 on Win 10). Could perhaps be an obvious, fool-hardy situation since I don't use PS very often. But FWIW this is how I was able to get it to work, by manually setting the Authorization header.
$url = "{url here}"
$username = "{username here}"
$password = "{password here}"
$b = [System.Text.Encoding]::UTF8.GetBytes($username + ":" + $password)
$p = [System.Convert]::ToBase64String($b)
$creds = "Basic " + $p
Invoke-WebRequest -Uri $url -Headers #{"Authorization"=$creds}
For whatever reason, the other answers here did make requests but no Authorization header was ever sent.
This is how I did it,
first created a download.ps1 file that contains the powershell script,
Then running this script through a batch file:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\Users\SS\Desktop\download.ps1
this is the PowerShell script:
$Username = 'Domain\user'
$Password = 'pass'
$Url = "http://google.com/target/filename.zip"
$Path = "C:\path\to\downloaded\file\filename.zip"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$WebClient.DownloadFile( $url, $path )
What you have should work (try the code with some other sites). Normally, an invalid username/password would cause the code to fail with a 401 error (not the windows security login window). The problem may be related to the web site requiring Windows Integrated Authentication