Reset rdp session with psexec - session

We have domain users that use a remote instance of an app through RDP. The app is quite buggy, and their session needs reset frequently. I'd like to build a script that uses psexec from the client to reset the session on the server.
psexec \\server -u user -p pass query session
shows all the sessions
psexec \\server -u user -p pass reset session_id
resets the session based upon the id.
I need a way to reset the session based upon the username, instead of session name or id

Try this combination of commands to get the username and then you can kill the session by id. You will need PsLoggedOn from Windows Sysinternals Here is the a link which explains the commands. How to check who has logged into your system
PSLOGGEDON -L \\remotecomputeror
PSEXEC \\remotecomputer NET CONFIG WORKSTATION | FIND /I " name "
PSEXEC \\remotecomputer NET NAME
PSEXEC \\remotecomputer NETSH DIAG SHOW COMPUTER /V | FIND /i "username"
FOR /F %%A IN ('REG Query \\remotecomputer\HKU ˆ| FINDSTR /R /B /C:"HKEY_USERS\\S-1-5-[0-9][0-9]-[0-9-]*$"') DO (
FOR /F "tokens=3 delims=\" %%B IN ('REG Query "\\remotecomputer\%%A\Volatile Environment"') DO (
SET LoggedinUser=%%B
)
)

Related

Could not connect sessionID 1 to sessionname console, Error code 7045

I have created a self-hosted agent machine in an interactive mode (Windows 10) to run the unit tests. To disconnect from the Remote Desktop Connections while Running Automated Tests I am executing the below command from a command-line task (from Azure DevOps). This is working fine when the user logged into the agent machine. But getting an error If there is no user logged into that agent machine.
Is this expected behavior? Can we bypass this?
%windir%\System32\tscon.exe 1 /dest:console
Error:
Could not connect sessionID 1 to sessionname console, Error code 7045
Error [7045]: The requested session access is denied.
I tried with the other options as well like creating a batch file with the below code and executing it while running the pipeline.
This one is also giving the same error
for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do (
%windir%\System32\tscon.exe %%s /dest:console
)
Command query user %USERNAME% will return the session even if the user is not currently logged in.
You can run command query user ^| find "Active" to query the active login users only.
See below:
for /f "tokens=3" %%s in ('query user ^| find "Active" ') do (
%windir%\System32\tscon.exe %%s /dest:console
)

How to Find current user in shellcommand?

When running command prompt in Standard user account echo %userprofile% command shows current user name but when run as administrator it will shows admin user name.
How can i get current standard user name even the command prompt in run as administrator mode? What ShellCommand is used for this?
I found the solution.
for /f "tokens=2" %u in ('query session ^| findstr /R "^>"') do #echo %u
It works.

Selenium hover action with IE doesn't work if RDP never connected to Jenkins slaves

We create a bunch of windows Jenkins slaves on Amazon EC2, and make them autologon after they are provisioned.
Once logged on, we use connect the slaves back to master via java web start by execute "ps", with all of this, we can run selenium perfectly with IE except we can't get a higher resolution than 1024*768. We got screenshot, we can see the browser running on the GUI if connected with RDP, just like running on a physical PC.
But a flaw is that, the hover action doesn't work on IE unless we connect to the slave through remote desktop one time before the test starts, just connect once, nothing else, I can even close the RDP session.
I guess something triggered by the RDP connection, just can't figure out what is that.
You can try to adapt your test scripts to have them make an RDP connection before you start your tests, if there is none. This is the code I used for one of our projects to ensure an RDP connection is active:
REM check if user has an RDP session. Will store the session ID of the user in the SESSION variable
call :getsession computername username SESSION
if "%SESSION%" EQU "" (
REM initiate an RDP connection to 'computername', wait, and disconnect by killing the process
mstsc.exe /v:computername & ping -n 5 1.1.1.1 & taskkill /F /IM mstsc.exe
)
REM check again the session
call :getsession computername user SESSION
if %SESSION% NEQ "" (
echo start your tests
)
:getsession
for /F "tokens=1,2,3,4" %%i in ('query session /SERVER:%1 ^| findstr %2') do if %%j EQU %2 (SET %3=%%k) else (SET %3=%%j)
goto :eof
Note that the automatic connection will only be made if you save credentials on the machine from which you start the remote desktop:
cmdkey /generic:computername /user:rdp_username /pass:rdp_password
After executing this once the mstsc.exe will be able to connect to the machine without user interaction.

How to log into user account?

After someone has logged off (Start button→Logoff) for the night, at a certain time in the morning I want to have the Task Scheduler automatically log into the Windows 7 user account (the opposite of Start button→Logoff) that is password protected. The machine is 64 bit. I am doing this so systems (vbs, vba, etc.) can prep files prior to the user showing up to work.
I was pretty sure this was possible, but I can't find it anywhere online, so I am wondering if it really is possible.
I have to this in a VBScript.
For security reasons I need to log him off at night, but I figured that part out (vbs from SO):
Set = wshell = Wscript.CreateObject(Wscript.Shell")
wschell.exec("shutdown.exe -L -F") 'logoff and force shutdown programs
Edit1:
Using an answer from Sujith, I attempted to set this up. First I must point out that this is NOT a remote computer or connection. I'm trying to get the local computer to log back in to the user account.
I created logon.vbs with this vbs code:
Set = wshell = Wscript.CreateObject(Wscript.Shell")
wschell.exec("shutdown.exe -L -F") 'logoff and force shutdown programs
WScript.Sleep(5000)
computer = "computername"
username = "OTHERDOMAIN\user"
password = "password"
Set locator = CreateObject("WbemScripting.SWbemLocator")
Set wmi = locator.ConnectServer(computer, "root\default", username, password)
wmi.Security_.ImpersonationLevel = 3
In other words, I am logging off and right back on (avoiding the Task Scheduler so things are simplified). I also tried a lot of variations on this trying to get it to work. It logs me off just fine, but nothing happens after that. I have to login manually.
I also tried the Task Scheduler setting mentioned in Sujith's answer, but it never turned on that I could tell.
Edit2: Or please tell me what you need to provide an answer?
Create a task scheduler to run a vbscript, this task can be triggered while the user logs off from his session by selecting the trigger option "On disconnect from user session" & Any user.
The vbscript which is scheduled on trigger may have the code for remote login on the machine. For the code the below links will help you.
connect to Remote server in vb script
Connecting to a Remote Server on a different domain -- how do I enter the username and password?
I don't think what you're trying to do is possible. If you can do a reboot first, you can solve it by using Windows' built-in "Auto Logon" feature.
If so, I've got some suggestions for an alternate solution for you:
Logging off users at a specified time
Follow the instructions for Assigning Logon Hours. Old article, but still valid for newer Windows Server OS.
OR
Create a script that logs off all logged on users, then create a scheduled task running as NT AUTHORITY\SYSTEM to execute it at a specified time.
Automatically rebooting and logging on with a specific username/password
Create a batch file called, say, "Enable_AutoLogon_and_Reboot.cmd" and place it in a folder, e.g. "C:\BatchFiles". Contents:
set sUsername=SOMEDOMAIN\Someusername
set sPassword=somepassword
:: Enable autologon on next boot
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v AutoAdminLogon /t REG_SZ /d 1 /f
:: Set autologon to only log on once
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v AutoLogonCount /t REG_DWORD /d 1 /f
:: Set username
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultUsername /t REG_SZ /d "%sUsername%" /f
:: Set password
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultPassword /t REG_SZ /d "%sPassword%" /f
:: Reboot
shutdown /r /t 0 /f
Replace the values of the variables at the start with the actual username and password.
Create a scheduled task running as NT AUTHORITY\SYSTEM (e.g. running daily at 06:00):
schtasks /create /tn "\CustomTasks\Enable AutoLogon and Reboot" /tr "%comspec% /c C:\BatchFiles\Enable_AutoLogon_and_Reboot.cmd" /st 06:00 /sc DAILY /ru "NT AUTHORITY\SYSTEM" /f

batch file will not run as administrator

I am trying to run this code in a windows batch (.bat) file
#echo off
echo Adding New User - LogMeInRemoteUser
net user | find /i "LogMeInRemoteUser" || Net user LogMeInRemoteUser password /add /fullname:"LogMeInRemoteUser"
pause
echo Adding User to Administrators Group
NET LOCALGROUP Administrators "LogMeInRemoteUser" /ADD
pause
echo Creating Registry Keys to remove the new user from the login page
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon\SpecialAccounts\UserList" /v "LogMeInRemoteUser" /t REG_DWORD /d 0
pause
echo Finished
if i run the file normally, i get an Access Denied error so I try to run as Administrator but the cmd windows opens and instantly closes, what have i done wrong?
When you run as administrator the current directory is changed under you. To prove that (and fix it) enter these 3 lines under your #echo off
echo(%cd%
pushd %~dp0
echo(%cd%
You can remove both of the echo( statements after you see what is happening.

Resources