getting the list of the saved session in putty using plink - putty

I am trying to write my scripts under windows to control putty.
Say I have a session called mySession. I can send a command to it using:
plink -load mySession -l myUserName -pw myPassowrd ps -ef
Now say I have many different sessions saved. is there a way to loop through the list of all my sessions to run this command?
Many thanks

As far as I know, the sessions are stored in the registry (HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions). At least it is the case in my environment here. You could for example use a batch script to access the session names.
#echo OFF
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions"
FOR /F "usebackq" %%A IN (`REG QUERY %KEY_NAME% 2^>nul`) DO (
FOR /F "tokens=6 delims=\" %%B IN ("%%A") DO (
#echo ON
"C:\Program Files\PuTTY\PLINK.EXE" -load %%B -l my_user -pw my_password ps -ef
#echo OFF
)
)
I used tokens=6 to only get the last part of the path (%%A). I'm not much fimiliar with batch scripting therefore I don't even know if you need setlocal ENABLEEXTENSION.
If you know your session names you could also simply use the following command:
FOR %%A IN (session1_name session2_name session3_name) DO "C:\Program Files\PuTTY\PLINK.EXE" -load %%A -l my_user -pw my_password ps -ef
Hope this helps, even though your post is nearly one year old. Comments to improve the code are welcome.

Related

Windows PowerShell command not executed in a batch script

I have the following commands written on a batch file to obtain my computer's public IP from a remote URL via powershell command:
#echo off
setlocal EnableDelayedExpansion
call :MyIP2
timeout /t 50
EXIT /B 0
:MyIP2
echo Obtaining my IP...
For /f %%A in ('powershell -NonI -NoP -C "(Invoke-Webrequest http://componentsearch.everscrape.com/scraper/ip).content"') Do echo %%A
EXIT /B 0
Now when I try to execute the batch file (even run as administrator), I got the following ouptut instead of the public IP of the computer I'm using.
Obtaining my IP...
Invoke-Webrequest
Internet
At
+
+
+
+
d
I'm currently running Windows Home with all the updates installed. Please any help is greatly appreciated.
Posting an answer to make sure there is clarity on this.
You specify in your question that all other devices work with your current script, besides this one device.
You posted an error after attempting the ode provided by Npocmaka which states:
Invoke-Webrequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again. At line:1 char:2 + (Invoke-Webrequest "http://componentsearch.everscrape.com/scraper/ip" ... +
This error has a clear message, well two in fact. It shows you the dependancy on IE as a parser on windows and more importantly it shows you the fix in this line:
Specify the UseBasicParsing parameter and try again
Simply adding the -UseBasicParsing parameter will therefore directly solve the issue without needing to run IE initially.
This is also clearly stipulated in this documentation
try like this:
For /f "tokens=* delims=" %%A in ('powershell -NonI -NoP -C "(Invoke-Webrequest """http://componentsearch.everscrape.com/scraper/ip""").content"') Do echo %%A
or
echo Obtaining my IP...
for /f "tokens=* delims=" %%A in (
'powershell -NonI -NoP -C "(Invoke-Webrequest """http://componentsearch.everscrape.com/scraper/ip""").content"'
) do (
set "my_ip=%%A"
)
echo %my_ip%
the URL needs to be in double quotes but in order to escape them when called from batch you need to use triple double quotes.
It seems this issue seem to occur on fresh installed windows. To fix, launch the Internet Explorer and select Recommended Settings.

Running Plink in a Windows Batch - Issues

I'm putting together a very basic automation script using the windows batch operation in which will loop through a list of IP addresses and run a plink command to logon and keep alive the account on the server because it has recently logged onto the server.
I believe I have most of the function working however I am having an issue with passing through the password. I'm seeing an issue where if the password I have has special characters and in which I run the script through command prompt it does not pass through the special character to the plink command. Here is a look of the script:
#echo on
SET userid=root
SET passwd=Welcome1%
for /f "delims=" %%i in ('type "ipaddress.txt" ') do (
pushd "C:\Program Files (x86)\PuTTY"
plink.exe -pw %passwd% %userid%#%%i hostname
popd
)
The ipaddress.txt file contains:
10.0.0.1
10.0.0.2
10.0.0.3
The idea is to go through the list for each IP address, logon and validate access. I'm also looking to ensure the value Y or N is passed to make sure a server is trusted or not as part of the script. Any help would be greatly appreciated.
You could see your script behaviour with #echo on (run it from within a cmd window instead of double-clicking). You are right that some special characters need to be escaped. If your password should be Welcome1% literally then use
SET passwd=Welcome1%%
or advanced set command syntax
SET "passwd=Welcome1%%"
Edit. Above advice covers particularly % percentage sign in a string. However, escaping some characters with special meaning (e.g. redirectors <, >, |, & etc.) as ^<, ^>, ^|, ^& seems to be a bit inconvenient and could not suffice. Therefore required advanced set command syntax and delayed expansion enabled instead.
For instance, Wel<come>1% string could be used as follows:
SET "userid=root"
SET "passwd=Wel<come>1%%"
for /f "delims=" %%i in ('type "ipaddress.txt" ') do (
pushd "C:\Program Files (x86)\PuTTY"
SETLOCAL EnableDelayedExpansion
plink.exe -pw !passwd! %userid%#%%i hostname
ENDLOCAL
popd
)

Redirect command as well as output to text file in Windows CLI?

I need to redirect both the command as well as its output to a text file in Windows CLI. For instance, I am running the nslookup command on a subnet using a FOR loop,
for /L %i IN (1,1,254) DO nslookup 192.168.1.%i >> nslookup.txt
However, this only redirects the output of the command.
Is there a way to redirect both the command as well as the output to a text file? Please do not tell me about clip and select all/copy commands.
You can proceed the command with "cmd /c" to start a new command prompt, and redirect the output of the command prompt:
cmd /c for /L %i IN (1,1,254) DO nslookup 192.168.1.%i > nslookup.txt
Note that you only need to use a single greater than (>) since the output of cmd is going to nslookup.txt. Sadly, this misses the error output, so you are not seeing the ***Request to UnKnown timed-out for each failed address.
Your FOR loop is right on and it sounds like you are already getting the output you want, so all you need to do is ECHO the command before running it:
for /L %i IN (1,1,254) DO ECHO nslookup 192.168.1.%i&nslookup 192.168.1.%i >> nslookup.txt
The & chains the commands together so the ECHO is run before the nslookup.
If you want to use a batch file, it becomes a bit more clear:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET Outfile=nslookup.txt
REM Log the date/time.
ECHO %DATE% - %TIME%>%Outfile%
FOR /L %%i IN (1,1,254) DO (
SET Command=nslookup 192.168.1.%%i
REM Print the command being run.
ECHO !Command!>>%Outfile%
REM Run the command.
!Command!>>%Outfile%
)
ENDLOCAL
for /L %i IN (1,1,254) DO (#echo nslookup 192.168.1.%i & nslookup 192.168.1.%i) >> nslookup.txt
This works. Still I'm sure there are smarter ways to do this.

batch script to disable/move/delete multiple computers in AD

I'm currently working in an organization that has migrated their OU groups so that everything belongs to a parent folder called "users and workstations".
This is a slight problem for me, as I have a few batch scripts that delete users and computers from a text file - something that I run fairly regularly.
The current code I use, for example, to disable a batch of machines is below
#echo off
CLS
ECHO Now Disabling Machines...
TIMEOUT 2 > nul
Pause
FOR /f %%i in (%~dp0\computernames.txt) do (
dsquery computer -name %%i | dsmod computer -disabled Yes
)
If I run this code since the change, I get the following error
dsmod failed:'Target object for this command' is missing.
type dsmod /? for help.
However, if I manually type the dsquery / dsmod line of code into command prompt and replace the "%%i" with a computer that failed, it succeeds.
I'm almost certain that this is due to the spaces within the OU folder structures, but don't know what to do to change my script to continue working.
Is there a way to change it? should I try something else? I'm going crazy trying to figure this out!!!
Thanks in advance,
Ben
P.S. I've come up with a solution that seems to work - I'll keep this open incase anyone can suggest a better way to do what i need to do. Please see below for the code that works for me. Looks like I needed to add correct delims and two sets of double-quotes to exit out correctly.... it doesn't make too much sense to me... but it works...
#echo off
setlocal disabledelayedexpansion
CLS
ECHO Now Disabling Machines...
ECHO.
Pause
FOR /f "delims= " %%i in (%~dp0\computernames.txt) do (
echo disabling %%i && echo. && dsquery computer -name ""%%i"" | dsmod computer -disabled Yes && echo.
)
Try using quotes on %%i in this line like this
dsquery computer -name "%%i" | dsmod computer -disabled Yes
Edit (added below):
Ahhhh... I bet the current directory is not what you think. Perhaps you are executing from a UNC drive. Try this:
pushd %~dp0
FOR /f %%i in (computernames.txt) do (
dsquery computer -name "%%i" | dsmod computer -disabled Yes
)
Please see original post for solution.
disabling delayed expansion and specifying the delims, along with double double quoting the variable seems to have fixed the problem!

WMI Process Call Create will not Run Batch script properately

This is what i am trying to do:
I have a NLB Cluster. There are two machines on said cluster: Node1 and Node2.
I have a third machine that is not in that, or any, cluster. This third machine is called: Monitor1
Once every hour, i would like to run a script to check if Node1 and Node2 are up.
This script will be run via TaskScheduler.
I am using the following command to execute the script on Node1 and Node2:
wmic /node:NODE1,NODE2 process call create "C:\ClusterCheck.bat"
The contents of the ClusterCheck.bat script is as follows:
NLB Query | findstr /i /R /C:"host . is stopped"
IF %ERRORLEVEL% EQU 0 (ECHO %COMPUTERNAME%_down)>DOWN.txt
IF %ERRORLEVEL% EQU 1 (ECHO %COMPUTERNAME%_up)>UP.txt
code here
When I use wmic /node:"%1" process call create "C:\ClusterCheck.bat" there is not output.
When I go into the server and manually double click the ClusterCheck.bat file, it gives me the appropriate output depending whether the node is up or down.
Does anyone have any ideas how I can get those files to output?
First problem, when you wmic process call create you should use prefix your command with cmd /c.
Next, you're right. wmic doesn't display the resulting output of the remotely created process on your local console. You'll either need to use psexec which was designed for this sort of thing, or hack a workaround by piping the command output to a log file then reading the log file. Something like the following script.
I'm not really clear, if this is going to be a scheduled task, why you're concerned with results being available to stdout. I suspect you intend to redirect the output to a log of some sort. So I put that in here as well.
#echo off
setlocal
set "user=domainadmin"
set "pass=password"
for /f %%I in ('wmic os get localdatetime') do set "timestamp=%%I"
set "today=%timestamp:~0,8%"
set logfile=c:\users\me\Desktop\logs\%today%.log
if not exist "%logfile%" mkdir "%logfile%\.." 2>NUL
>>"%logfile%" echo %time%
for %%I in (NODE1 NODE2) do (
(ping -n 1 %%I >NUL && (
net use \\%%I /user:%user% %pass% >NUL 2>NUL
wmic /node:%%I /user:%user% /password:%pass% process call create "cmd /c c:\clustercheck.bat >c:\cc.log"
type \\%%I\c$\cc.log && del \\%%I\c$\cc.log
net use \\%%I /delete >NUL 2>NUL
) || echo %%I unresponsive
)>>"%logfile%"
forfiles /p "%logfile%\.." /M *.log /d -30 /c "cmd /c del #path"
This should create Desktop\logs if it doesn't exist, then create or append to Desktop\logs\YYYYMMDD.log the output of C:\clustercheck.bat run on NODE1 and NODE2. Finally, it deletes log files that are over 30 days old.

Resources