Check and obtain Server access using Windows Batch File - windows

First of all I'm a complete noob to Batch scripting and networking, with that being said, Here is what I'm trying to accomplish.
I want to check if the server has provided this batch file executing pc to access it, if not create access to it. (many different pc's run this batch file)
This what I came up with for now in my batch file.
net use * \\ip\My_WebApp /Persistent:yes /user:Username Password
Exit
This batch file command create access to the server just fine but It creates a new access connection every time this file get executed. Which is not needed and might crash the server load.
How can I check if the Server already has provided the access, Only if not, execute the above command in a batch file. my logic like like....
boolean status = check_server_accessibility()
if(!status){
net use * \\ip\My_WebApp /Persistent:yes /user:Username Password
}
Exit
Appreciate any help, Thank you so much for your time.

You should only ever need to perform the task once, which suggests that a scripted solution isn't needed, (persistent means that!). I would assume that the following may be sufficient:
#Set "MyMap=\\ip\My_WebApp"
#%__AppDir__%wbem\WMIC.exe LogicalDisk Where "DriveType='4'" Get ProviderPath 2>NUL | %__AppDir__%findstr.exe /R /I "%MyMap:\=\\%\>" 1>NUL && GoTo :EOF
#%__AppDir__%net.exe Use * "%MyMap%" /Persistent:Yes /User:Username Password
Alternatively, if you needed to know which drive letter is currently assigned to it, then use a for-loop to retrieve the data:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Call :MapChk "\\ip\My_WebApp"
GoTo :EOF
:MapChk
Set "MyMap=%~1"
Set "MyDrv="
For /F "Skip=1 Delims=:" %%G In (
'%__AppDir__%wbem\WMIC.exe LogicalDisk Where "DriveType='4' And ProviderPath='%MyMap:\=\\%'" Get DeviceID 2^>NUL'
) Do For %%H In (%%G) Do Set "MyDrv=%%G:"
If Defined MyDrv (
Echo %MyMap% is already mapped to drive %MyDrv%.
%__AppDir__%timeout.exe /T 5 /NoBreak >NUL
GoTo :EOF
)
%__AppDir__%net.exe Use * "%MyMap%" /Persistent:Yes /User:Username Password
I've made this one into a callable label, so that you can more easily extend it for other mappings too, e.g. before the GoTo :EOF, (line 6), Call :MapChk "\\Server\My Share".
Note: These solutions are untested, I do not use a PC and have no mapped network locations to test them against. Please let me know if I have made a mistake somewhere.

Related

dot net command: net use - How to only get Alphabet and pathname?

When I do a "net use" on my command prompt, it will display the following:
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK W: \\hfs2\ATS\Novell Profile Backup\wk\one\two\three\four\five\six\seven\eight\nine\ten\eleven\twelve\thirteen
Microsoft Windows Network
OK X: \\hfs2\ATS\Novell Profile Backup\wk\one\two\three\four\five\six\seven\eight\nine\ten
Microsoft Windows Network
OK Y: \\hfs2\ATS\Novell Profile Backup
Microsoft Windows Network
Unavailable Z: \\hfs2\ATS Microsoft Windows Network
The command completed successfully.
How do I extract ONLY get the drive alphabet and pathname?
W:
\\hfs2\ATS\Novell Profile Backup\wk\one\two\three\four\five\six\seven\eight\nine\ten\eleven\twelve\thirteen
X:
\\hfs2\ATS\Novell Profile Backup\wk\one\two\three\four\five\six\seven\eight\nine\ten
Y:
\\hfs2\ATS\Novell Profile Backup
Z:
\\hfs2\ATS
EDIT
WMIC does not require administrator rights
It does require rights for what you are trying to do. You can't use it to do admin things if not an admin.
It also requires an administrator to run it once on a system to set it up.
From Help
User Account Control
Under UAC, accounts in the local Administrators group have two access tokens, one with standard user privileges and one with administrator privileges. Because of UAC access token filtering, a script is normally run under the standard user token, unless it is run "as an Administrator" in elevated privilege mode. Not all scripts required administrative privileges.
Scripts cannot determine programmatically whether they are running under a standard user security token or an Administrator token. The script may fail with an access denied error. If the script requires administrator privileges, then it must be run in the elevated mode. Access to WMI namespaces differs depending on whether the script is run in elevated mode. Some WMI operations, such as getting data or executing most methods, do not require that the account run as an administrator. For more information about default access permissions, see Access to WMI Namespaces and Executing Privileged Operations.
Wmic
The first time you run Wmic after system installation, it must be run from an elevated command prompt. The elevated mode may not be required for subsequent executions of Wmic unless the WMI operations require administrator privilege.
Use WMIC
wmic netuse get /format:list
gives you what's available.
Use something like
wmic netuse get remotepath, localname /format:list
To put the output in a file or on the clipboard.
WMIC specific switch
/output or /append
eg
wmic /node:"#%userprofile%\desktop\ComputerName.txt" /output:"%userprofile%\desktop\EventLog.html" /failfast:on PATH Win32_NTLogEvent where (EventIDentifier=42 or eventidentifier=1003) get /format:hform
(/node is a list of IP addresses and/or computer names of computers to run the command against, one IP address or computer name per line)
General Command Prompt File Redirection
Appending >filename.ext (or >>filename.ext to append to a file)to a command writes the output to the file rather than the screen.
wmic baseboard get product,Manufacturer,model,partnumber>MotherboardPartNum.txt
General Command Prompt Piping
Appending |command sends the output to a command rather than the screen. The usefull commands that output is sent to are
find or findstr (finds and filters text)
sort (sorts the output)
more (displays output to screen one page at a time)
clip (puts output onto the clipboard)
null (makes the data disappear for good - used for unwanted error messages)
wmic baseboard get product,Manufacturer,model,partnumber|clip
Combining Piping and Redirection
So we can combine them. To send the list to a file on the desktop in reversed sort order (z to a) with blank lines removed.
wmic service get name,displayname /format:list|findstr .|sort /r>"%userprofile%\desktop\services_reversed.txt"
WMIC Output Options
The output options are
/Format:list (a list - use notepad to view)
/format:table (a table - use notepad to view)
/format:hform (an html list - name the file's extension .html so IE will show)
/format:htable (an html table - name the file's extension .html so IE will show)
/format:csv (comma seperated variable - used for importing data into other programs such as excel)
also value, mof, rawxml, and xml.
So,
sort /?
find /?
findstr /?
more /?
clip /?
There are some problems in the output of net use
The Status field can hold information or be empty.
The Network field can have multiple values depending of network mapping. In my case i have "Microsoft Windows Network" and "Netware Services". So, there is no direct substitution.
The Network field can be in the same line that the Remote field or can be on the next line, and as the Remote field may include spaces, checking the character at the column limit position is not reliable. It is necessary to delay the check until the next line is readed to determine if it contains remote data.
So, not a one liner to handle it
#echo off
setlocal enableextensions disabledelayedexpansion
set "drive="
for /f "skip=6 tokens=1,* delims=\" %%a in ('net use') do (
if defined drive (
setlocal enabledelayedexpansion
if "%%b"=="" (
echo !drive! !networkPath!
) else (
echo !drive! !networkPath:~0,26!
)
endlocal
set "drive="
)
if not "%%b"=="" for /f "tokens=2" %%c in ("x%%a") do (
set "drive=%%c"
set "networkPath=\\%%b"
)
)
%%a loop will read the lines from net use and split them using a backslash as delimiter. This will allow us to determine if the line contains or not a network path (if there is no second token, the line did not contain a backslash).
As we are delaying the output of the information in one line until the next is readed (to determine if the remote path continues in the Network column), the first operation inside the for loop is to determine if we have data pending from previous loop. If there is data, depending on the content of the current line we select what to output.
Once the data is echoed, if the current line contains network information, it is saved for later output.
This is the faster solution, but there are two alternatives that require less code:
multiple net use commands
#echo off
setlocal enableextensions disabledelayedexpansion
rem For each line in the output of the net use that includes a drive letter
for /f "delims=" %%a in ('net use^|find ":"') do (
rem Retrieve the drive letter from the line
for /f "tokens=2" %%b in ("x%%a") do (
rem Run a net use with the drive letter and output the drive and the path
for /f "tokens=1,* delims=\" %%c in ('net use %%b') do if not "%%d"=="" echo(%%b \\%%d
)
)
Less code, but as multiple net use commands are executed, it is slower
Use WMIC
#echo off
setlocal enableextensions disabledelayedexpansion
for /f "tokens=2,3 delims=," %%a in (
'wmic netuse get LocalName^, RemoteName^, Status /format:csv ^| find ":"'
) do echo(%%a %%b
Less code, but in this case, adminitrator righs are required to run the command
I might be a little late but this helped me
WMIC NETUSE GET LocalName, RemotePath /FORMAT:TABLE | FIND /i ":"

BATCH FILE - IF Exists & Output Error

INFO: assets.txt contains a list of cpu names which I can connect to over the network.
I need to copy this new .exe to well over 200+ computers and figured i could use the c$ admin share. This is really the only way I can do this without going to workstations individually or remoting in one by one.
This script works without the 'if exists' however I need to check if the directory exists before attempting the copy. I don't understand why it isn't working. I am also running this script using my domain administrative account.
#echo off
REM Pull Computer Asset Tags from file
for /F "tokens=*" %%A in (assets.txt) do (
echo Start Processing %%A
REM Temporarily set file path for existence check
set file=\\%%A\C$\Program Files\Intouch2\Intouch2ca.exe
if EXIST "%file%" (
REM Rename old .exe
ren "\\%%A\C$\Program Files\Intouch2\Intouch2ca.exe" "Intouch2ca.bak"
REM copy new .exe from server to cpu asset
xcopy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" /Y
echo END Processing %%A
echo.
echo ------------------------------------------------------------
echo.
)
)
I also haven't been able to get the error output to a log file.
I have tried this but it isnt exactly what I would like.
xcopy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" /Y 1>>errors.log 2>&1
How can I pretty that up so it only shows errors and lists the %%A where the error occured?
Thank you all in advance for your time.
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed.
Hence, in your case, file is being changed within the block, so the value cmd uses is its initial value when the entire for is parsed.
Solution 1: use \\%%A\C$\Program Files\Intouch2\Intouch2ca.exe in place of %file%
Solution 2: start your batch with setlocal enabledelayedexpansion on a separate line after the #echo off, then use !file! in place of %var%
Solution 3: call an internal routine to use the mofified value as %file%
Solution 4: Create the directory regardless. MD newname 2>nul will silently create a new directory if it doesn't already exist
An error on a copy will set an errorlevel and you can write a custom error message.
copy "\\server\my dir\management\it\software\Intouch Upgrade\Intouch2ca.exe" "\\%%A\C$\Program Files\Intouch2\" >nul 2>&1
if errorlevel 1 >> errors.txt echo "Error in %%A"

How to read net use generated text file and use the net use command to remap the network drive

How to read net use generated text file lets called it network_drive.txt that consist of the current machine mapped network drive as image below:
New connections will be remembered.
Status --- Local --- Remote ------------------ Network
-------------------------------------------------------------------------------
OK ---------- H: ---- \\server\users\john -----
Microsoft Windows Network
OK ---------- Y: ---- \\server\e$\ --------------
Microsoft Windows Network
The command completed successfully.
How to read the file above to map the network drive again with the same Letter path and path only if the status is ok and ignore the unavailable one?
update!
#echo off
set drive=\\server\users\john\
net use > %drive%\%USERNAME%_temp_Networkdrive.txt <-- generating net use file
for /f "skip=6 delims=*" %%a in (%drive%\%USERNAME%_temp_Networkdrive.txt) do (
echo %%a >>%drive%\%USERNAME%_del_Networkdrive.txt ) <-- deleting the first 6 lines
xcopy %drive%\%USERNAME%_del_Networkdrive.txt %drive%\%USERNAME%_Networkdrive.txt /y <-- make a new copy of the network drive file after deleting the lines
findstr /v "The command completed successfully." %drive%\%USERNAME%_del_Networkdrive.txt > %drive%\%USERNAME%_Networkdrive.txt <-- find the string and delete them and make a new copy of file with just the network drives
del %drive%\%USERNAME%_del_Networkdrive.txt /f /q
del %drive%\%USERNAME%_temp_Networkdrive.txt /f /q
for /f "tokens=2,3,4" %%a in (%drive%\%USERNAME%_Networkdrive.txt) do ( net use %%a %%b ) **<-- find the letter path and the drive path and map accordingly.**
however..
in some cases, sometimes the "Microsoft Windows Network" is on the same line as the letter and Drive path and hence deleting the record/line.
can someone help pls?
Update.
I removed Microsoft Windows Network from the findstr line because the tokens in the for loop would only pick up the second and third strings for the net use command.
I have tested it and it works.
Also, it would be a good idea to use if exist command on the second line just to see if the file is exist before running the other commands.
#ECHO OFF
SETLOCAL
FOR /f "tokens=2*delims=: " %%a IN ('type q20294868.txt^|find "\"^|findstr /b "OK"') DO ECHO NET use %%a: %%b
ECHO(======================
FOR /f "tokens=2*delims=: " %%a IN ('type q20294868.txt^|find "\"^|findstr /b "OK"'') DO FOR /f %%c IN ("%%b") DO ECHO NET use %%a: %%c
GOTO :eof
This should do what you appear to want.
You should replace type q20294868.txt with net use for your situation. q20294868.txt is simply a file I used to save your test data.
There are two separate methods here. The text is filtered first for lines containing \ and then for those /b beginning "OK"
I'm unsure whether the network name may potentially be included on a data line rather than on a line by itself, consequently I've devised the second method. The first is simpler, the second more robust.
Note that your original findstr would have eliminated any lines containing ANY of the individual words contained in the quotes - see findstr /? from the prompt for more information.
And of course, the resultant NET USE command is merely ECHOed to the screen, not executed.

Running Multiple Installations with System-Reboot Inbetween them

Currently I have a set of software-Installations(and their paths) that i have to install on my Windows Machine.
What I do now is -- Hit RUN every time and type in the software installation path into it..
What I want is to design a Batch file which would install all the applications and REBOOT my system after every successful installation and then continue with the NEXT item in the list..
Is it possible using a .bat file ??
This really isn't something batch was designed for, so this will be a bit hacky. It's not elegant by any means but give it a shot, it might work for you.
for /f %%a in (C:\files.txt) do (
start /wait %%a
exit /b
)
for /f "skip=1" %%b in ("C:\files.txt) do (
echo %%b >>C:\newfiles.txt
)
xcopy C:\newfiles.txt C:\files.txt /y
del C:\newfiles.txt /f /q
shutdown /r /t 0 /f
The idea being that you have a text file with the paths of the executables that you want to install. It will go through and execute the first file in the list, wait for it to complete, then re-write the list without the file it just installed.
This is dependend on the setup file having no user interaction and exiting by itself, or maybe it's just to make things easier - in which case just go through each install yourself, and when it finishes the batch file will do the rest.
On the note of rebooting and continuing you will either need to run the batch file again yourself or put it in the registry to start up itself, the latter command being
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v "MyBatchInstaller" /d "C:\MyBatchFile.bat" /f
Hope this helps

Windows: Obtaining and Storing a Machine Name in a Variable

I have a script that is run over a network, with VPN being the same as a LAN environment.
The script previously worked fine, as we had variables that stored the username and password for the administrator. However, due to a recent change, when we map a drive over the network and whatnot, the machine name is now needed in front of the administator username, E.g. machinename2343\administrator.
What I would like to do is take an existing command - perhaps such as nbtstat - and after entering the ip address, have the program pull the machine name and insert it into a variable.
I have found that Nbtstat can give me the machine name, but provides large amounts of unnecessary information for my task. Is there a way to filter out just the machine name in a reliable and consistent manner, or is there perhaps another network related command that perform in the same capacity?
`#echo off
FOR /f "tokens=1* delims= skip=23 " %%a IN ('nbtstat -a IPADDRESS) DO (
SET VARIABLE=%%a
GOTO Done
)
:Done
echo Computer name: %VARIABLE%`
You could do ping /a. The computer name is resolved. And this computer name is the second token. I haven't taken care of Error checking. I believe you could implement that yourself.
Try this:
#ECHO OFF
FOR /f "tokens=2* delims= " %%a IN ('PING -a -n 1 IPADDRESS') DO (
SET Variable=%%a
GOTO Done
)
:Done
echo Computer name: %Variable%
Put this in your batch file where it would fit.
You could just use the %computername% environment variable.
When I first read your post I thought you were running the batch file remotely on each machine. If that were the case having %computername% in the batch file would work, because when the batch file is executed remotely %computername% would be expanded based on the remote machine's environment variable not the local machine.
Looking back on it, it's still not very clear, but based on your comment I assume the batch file is running locally and then connecting to a set of machines to perform some operation(s).
You could use tool the WMI command-line tool to get the computer name. The solution would look similar to #Thrustmaster's, but I think it's a little cleaner since the output of wmic, in this case, does "filter out just the machine name in a reliable consistent manner." Of course you'd replace the 127.0.0.1 with the ip you want to query.
#ECHO OFF
FOR /F "tokens=*" %%A IN ('wmic /node:127.0.0.1 ComputerSystem Get Name /Value ^| FIND "="') DO (
SET COMP.%%A
)
ECHO %COMP.NAME%

Resources