Azure Powershell: What is the opposite command to Login-AzureRmAccount (used to be Clear-AzureProfile) - azure-powershell

I have various scripts which I used to run in a wrapper to allow me to handle things like checking I had a valid connection and to ask the user if the connection/subscription currently selected is the one they want to run the script on before running it etc.
The classic commands have Clear-AzureProfile which allows me to run it from a script and effectively break the connection so that it can't be used again without calling Add-AzureAccount.
With the RM cmdlets I can only find Login-AzureRmAccount but once I've logged in...how do I call logout?
There doesn't appear to be a Logout-AzureRMAccount or Remove-AzureRMAccount and Clear-AzureProfile has no effect.
I run a dev workstation and connect to several different client subscriptions so want to be able to destroy the connection rather than just calling another login over the top of it (if that login failed I would still have the old connection set up which is dangerous for me)
I've just logged this at: https://msdn.microsoft.com/en-us/library/mt619248.aspx as from the documentation it looks like the commands may be lacking

It appears the following works:
Set-AzureRmContext -Context ([Microsoft.Azure.Commands.Profile.Models.PSAzureContext]::new())

UPDATE: For new powershell Azure "az" module, please use
Connect-AzAccount
for login and
Disconnect-AzAccount
for logout.

> get-command -Module AzureRM.Profile
CommandType Name
----------- ----
Alias Login-AzureRmAccount
Alias Select-AzureRmSubscription
Cmdlet Add-AzureRmAccount
Cmdlet Add-AzureRmEnvironment
Cmdlet Disable-AzureRmDataCollection
Cmdlet Enable-AzureRmDataCollection
Cmdlet Get-AzureRmContext
Cmdlet Get-AzureRmEnvironment
Cmdlet Get-AzureRmSubscription
Cmdlet Get-AzureRmTenant
Cmdlet Remove-AzureRmEnvironment
Cmdlet Save-AzureRmProfile
Cmdlet Select-AzureRmProfile
Cmdlet Set-AzureRmContext
Cmdlet Set-AzureRmEnvironment
Note that Login-AzureRmAccount is an alias to Add-AzureRmAccount and there's no corresponding Remove.
Set-AzureRmContext might take a $null to clear the context, but I would be surprised if it doesn't instead just give an error.

Directly closing your PS session would do. The AzureRM.Profile module won't persist your profile until you tell it to do so with Save-AzureRmProfile.

In latest powershell version 1.0.1 MS hasn't provided any cmdlets which you are searching like Logout-AzureRMAccount or Remove-AzureRMAccount and Clear-AzureRMProfile.
In your case I would rather suggest a workaround for you.
Firstly close your PS window, delete your cahce and temp data.
Secondly, Delete your name from Azure AD and then Add it back. Download a new publishsetting file and start doing afresh. Once you re-add the name it will treat everything as new for you.

It's worth noting that you can always kick out an exception if the call to Login-AzureRmAccount fails to ensure your script doesn't continue with the old account:
Login-AzureRmAccount -ErrorAction Stop
The resulting dialog won't allow an invalid login. It will let you know if you're already logged in and give the choice to stay logged in with the current account or login with another, at which point the user still has to make some sort of conscious choice to proceed. If they choose to cancel out of the login dialog, the resulting exception will stop the script.
login-azurermaccount : authentication_canceled: User canceled authentication
At line:1 char:1
+ login-azurermaccount
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationCanceledException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand

I know this is an old question. But it looks like this has been updated with Remove-AzureAccount. You can read more about it here and Remove-AzureRMAccount found here.

AzureRM context used to be bound to a powershell session, so just closing the console was enough.
But it seems latest versions of the powershell module have changed that.
Using the latest version of the powershell module, if you login in one console, you will also be logged in all the other consoles.
And you can log off using the new cmdlet Logout-AzureRmAccount.

Related

Testing if user created in AD can be logged into on a VM

I am a QA automation engineer and in the web app I test there's a feature that creates Active Directory users.
My tools are - Selenium (Java), RemoteWebDriver, Selenium Grid (Docker)
I was trying to find ways to validate this process and came to a stop - this field (AD) is new
to me and I need to find a way to make sure the user was created and can be logged into in the
network.
I was trying to find a way to do this and came up with 2 options, where the first one is the least
preferred way:
Make a request (API? 3rd side tool?) to get the relevant user(s).
The issue:
A user created and registered in the AD doesn't necessarily mean that the client can log into it (at least by the way I understood how AD works), and so it loses the most important consequence of the feature.
Use a VM, get the AD user information (username + password: possible) and try to log into the VM using those details.
The issue:
I haven't came across a tool that does it, the closest thing is Robot class or WinAppDriver.
WinAppDriver seems like the best solution as of now although I don't know how to make the login process work since it's the process starts before the desktop is open and I don't know how to locate the username and password field, so I figured using Robot class seems like the simplest solution, if it works on a VM that is, which as of now doesn't seem like it does.
So, before advancing on learning how to use WinAppDriver with my current automation, I'd like and appreciate your opinions about the matter or if you have simpler solutions.
Thank you very much for reading!
• We can check whether a user is created successfully or not and if that user can log in to the AD domain or not by executing a script as below. It is a powershell script that auto logs in through remote desktop protocol in the other domain joined VM from an Azure domain joined VM that checks whether the recently created user can login or not.
Powershell script : -
cmdkey /list | ForEach-Object{if($_ -like "*target=TERMSRV/*"){cmdkey /del:($_ -replace " ","" -replace "Target:","")}}
echo "Connecting to 192.168.1.100"
$Server="192.168.1.100"
$User="Administrator"
$Password="AdminPassword"
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password
mstsc /v:$Server
• In the above script, replace the ‘$user’ value by the user principal name of the newly created user, i.e., ‘$User=”testdemo#example.com”’ and the ‘$Password’ value by the password set for that user. Also, ensure that you replace and enter the correct IP address of the domain controller/AD server. Also, ensure that before executing the above powershell script, execute the below commands in an elevated (administrator privileges) powershell console.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Lastly, please ensure that while creating the user, the option ‘User must change password at next logon’, ‘Account is Disabled’, ‘Password never expires’ and ‘User cannot change password’ are unchecked and not selected.
• Also, you can use the below command line script for logging in to the domain joined Azure VM through RDP protocol. In the below command, replace the ‘username’ and ‘password’ with the username and password of the user created recently to log in to the Azure VM with this command line script. Also, replace the ‘TERMSRC’ with the hostname of the server system or the domain joined VM where the specified UNC path is located and replace the ‘some_unc_path’ with the actual path UNC path of the shared directory folder. Please execute the below command through elevated (administrator privileges) command prompt.
Command script: -
c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nolog -command cmdkey /generic:TERMSRC/some_unc_path /user:username /pass:pa$$word; mstsc /v:some_unc_path

Unable to supply password to runas from commandline

I am unable to supply password to runas from commandline
I have tried the following
cmd /C echo my_admin_password | runas /user:DOMAIN\my_admin_login c:\test.bat
and
echo my_admin_password | runas /user:DOMAIN\my_admin_login c:\test.bat
And the error I get is
Attempting to start c:\test.bat as user "DOMAIN\my_admin_login" ...
RUNAS ERROR: Unable to run - c:\test.bat
1326: Logon failure: unknown user name or bad password.
How do I fix this?
Take a look at this link: runas utility
It's a runas free utility that have the follwing features:
It accepts password as a command line parameter so that it can be used in batch files.
It can bind started process to the interactive user Desktop so it can be used to start interactive processes from various services such as 24x7 Scheduler, 24x7 Event Server and other.
Note: Professional version of RunAs also supports encryption of the entire command line, which administrators can use to give regular users access to certain programs requiring admin-level privileges. Users don't need to know the administrator's password and cannot use it to run anything else… simple, yet very efficient solution for this common problem.
Also you can try pass the password as input for the process using subprocess.Popen.communicate or even subprocess.Popen.stdin.write.
Other interesting links:
How to pass a password to a process?
Command-line runas with password
PsExec

[Couchbase-server]Adding user/Changing password?

I am a newbie getting started with couchbase-server.
I simply want to browse the data present in a couchbase server using UI at http://www.dataoncouchbase.com:8091/index.html.
The password for the account "Administrator" is unknown. But I need to login to see the data.
One technique for changing the administrator password on couchbase-server is the following command (I do have access to the machine via command line)
$$ /opt/couchbase/bin/couchbase-cli cluster-init -u Administrator -p old_password -c 127.0.0.1:8091 --cluster-init-username=Administrator --cluster-init-password=new_password
BUT...only works if you know the old password(which I don't have).
I also tried modifying the local.ini file present at : /opt/couchbase/etc/couchdb/ and restarting the server. I added a new line(username=password) under [admins] section in the file. However I am not able to log in with the new user as well.
It would be great if someone can give me a way to add a new user(with read/write permissions) or change password for Administrator OR point me to some resource to do the same.
cbreset_password - it'll reset Administrator password w/o need to know the prior.
Have you looked in "config.dat" according to this it may appear there in plain text. (granted, they are talking about web console).
It seems like you may have already seen this but I'll reference it just in case. The format they use for password stored in local.ini includes spaces -> "username = password" Also they recommend running the command 'ls -alR /opt/couchbase-server/etc' to help figure out where your problem might be. Perhaps you can post your output for that command here if the last two suggestions don't work out.
I had the same problem. Seems like there's no way to reset the password, but it is visible in the config.dat file. The other thing that caught me out is the username...it's case sensitive, so Admin != admin !!!
If you know the old password ( I know this is not your case, but I want to write the solution to help someone who knows old password), you should read:
I changed with this command ( although it has thrown error --> ERROR: option cluster-init-ramsize is not specified);
./couchbase-cli cluster-init -c 127.0.0.1:8091 --user=admin --password=OLDPASS --cluster-init-username=admin --cluster-init-password=NEWPASS
My configuration is;
CentOs Gnu/Linux &
Couchbase 2.5.0
I have run command under the directory: /opt/couchbase/bin
Ok man I figured it out :)
I use OSX but I guess the way will be simular.
I went into the CouchbaseServer.app in orde to view the content.
then you open the folder Content/Resources/couchbase-core/bin
and theres programm called cbreset_password :)
Then it asked you to change the admin password.....there you go.
I feel with you it took me 2 hours :)
Using couchsync with couchbase you can change all users password using the administrative REST API.
curl -vX PUT http://127.0.0.1:4985/yourdbname/_user/youruser --data "{"name":"youruser", "password":"newpassword", "admin_channels":["yourlistofchannels"], "admin_roles":["yourlistofroles"]}"
Using your command go to your Couchbase bin folder. For mac, this is
/Applications/Couchbase Server.app/Contents/Resources/couchbase-core/bin
In that folder, execute this:
./couchbase-cli reset-admin-password --new-password test123.
Your new password will be changed to test123.
Here is the detailed guide: https://docs.couchbase.com/server/4.6/cli/cbcli/reset-admin-password.html
Step1:
/opt/couchbase/bin/couchbase-cli reset-admin-password --new-password 'Pass#2020'
-------
SUCCESS
-------
You may be trying to login with username "Administrator" but you will see error sometimes. Because in some clusters "Administrator" may not be the default hard coded admin, to see the admin name see the below file (as follows):
$ ls -lrth /opt/couchbase/var/lib/couchbase/isasl.pw
$ cp /opt/couchbase/var/lib/couchbase/isasl.pw /tmp
$ cat /tmp/isasl.pw
{
"users": [
{
"n": "**Admin**",
------------------here "Admin" is the Administrator account. So use "Admin" as username to login with your new password changed in step1.

try builtin credential first, then prompt for another

I want to query a server for, say memory
gwmi win32_freephysicalmemory -computername server1 -credential $cred
I know about get-credentials and also constructing an pscredential-object,
but i want to first try to query with my current credentials, and if i get unauthorizedexception ill prompt for new credentials with get-credentials.
this way i could run the script from either my workstation or some server (i dont use the same creds)
i think i initially need to feed $cred with my current credentials and then change it in the catchblock if it fails, but how do i dump my logged on credentials to an pscreential-object?
Have you tried [System.Management.Automation.PSCredential]::Empty?
Are you using PS 3.0?
You can set of default parameter value using
$PSDefaultParameterValues.Add('Get-WMIObject:Credential',[System.Management.Automation.P
SCredential]::Empty)
And, when this fails, you can look for the Credential Parameter.

Powershell Remote: Microsoft.Update.Session, Access Denied: 0x80070005

I've written a script to search/download/install Windows Updates on a machine using the Microsoft.Update.Session COM Object. When run locally it works just fine, however when running through a remote session or through Invoke-Command I receive an access denied (0x80070005) error on Microsoft.Update.Session.CreateUpdateDownloader()
I receive the same error if I attempt to create a Downloader object directly, code to reproduce the issue:
$oUpdateDownloader = new-object -com "Microsoft.Update.Downloader"
I am an administrator on the remote machine, and passing credentials (for myself explicitly or any other admin account) to the machine does not seem to change anything.
I've seen this error posted a number of times but there does not seem to be any information on solving the problem...
Any ideas?
When you are in a remote PowerShell session your logon session on this remote computer is flagged as a "network" logon (Logon Type: 3).
For some obscure (security? sell SCCM?) reason, part of the Windows Update Agent COM APIs are restricted to only be usable by locally logged on Administrators.
Using PsExec and Scheduled Tasks have been suggested as workarounds.
IMO, the most seamless (and still secureable) solution is to facilitate the RunAs-style "Local Virtual Account" feature of PowerShell Session Configurations / JEA.
Usually, JEA is used to "restrict" what a user can do on a remote computer PowerShell-wise, but we are (ab-)using it here to gain full access as if we were a locally logged on Administrator.
(1.) Create a new unrestricted (and persistent!) session configuration on ComputerB (remote server):
New-PSSessionConfigurationFile -RunAsVirtualAccount -Path .\VirtualAccount.pssc
# Note this will restart the WinRM service:
Register-PSSessionConfiguration -Name 'VirtualAccount' [-ShowSecurityDescriptorUI] -Path .\VirtualAccount.pssc -Force
# Check the Permission property:
Get-PSSessionConfiguration -Name 'VirtualAccount'
# Those users will have full unrestricted access to the system!
(2.) From ComputerA (local client) connect to our unrestricted session configuration on ComputerB:
New-PSSession -ComputerName 'ComputerB' -ConfigurationName 'VirtualAccount' | Enter-PSSession
[ComputerB]: new-object -com "Microsoft.Update.Downloader" # Yay!
This is a known issue. It appears that there is a bug with the actual COM object itself, as this issue occurs when using VBScript, PowerShell, and even C#. There is a good article that discusses managing Windows Update with PowerShell that can be found here.
The workaround is to set up a scheduled task on the computer and you can invoke that task however you see fit.
Use PsExec (http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx) to remotely execute PowerShell with a script file:
psexec -s \\remote-server-name C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe \\server\script.ps1
I used the script detailed at http://www.ehow.com/how_8724332_use-powershell-run-windows-updates.html, and I can remotely execute it using psexec to download and install updates.
the windows update code isn't callable form a remote machine. there are a few workarounds out on the web, including using psexec and a script (powershell or vbscript).
I used WUInstall myself and BoeProx has documented a few alternatives and has started a project PoshPAIG. I moved jobs before using this so don't know if it works.
The other solution is to change Windows registry setting using PowerShell and optionally restart wuauserv for the changes to take effect.
For example in Windows Server 2008R2 AutoUpdate settings can be found at:
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update