Please use the script to execute any windows command or PowerShell command, and append the output in a shared file from the valid network path
Instruction:
Modify the lines of code for your requirement. they can be done after exporting the script file attached to this message
- sFolder=r'your server name here'
- sUN=r'your server username here'
- sPWD=r'your server password here'
- sFile='your server file name with extension here'
- Command=r'your valid command'
sFolder=r'your server name here' ## provide the valid network path here, Example: \\fs2.ch.office.comodo.net\Common\C4
sUN=r'your server username here' ## provide server username here, Example pattern: domain\username
sPWD=r'your server password here' ## provide server password here
sFile='your server file name with extension here' ## file name to be written with [if no file exist then create new file on the given name], Example: filename.txt
Command=r'your valid command' ## command you want to execute, if you would like to run the PowerShell command then use the notation 'powershell "PowerShell commands"'. Example: powershell "Get-WmiObject -Class Win32_Processor -ComputerName ."
def ExecuteCMD(CMD, OUT = False):
import ctypes
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
from subprocess import PIPE, Popen
with disable_file_system_redirection():
OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
out, err = OBJ.communicate()
RET = OBJ.returncode
if RET==0:
if OUT:
if out:
return out.strip()
return True
return True
return False
def writeText(file, str):
with open(file, 'a') as f:
f.write(str)
import time
import os
sPath=os.path.join(sFolder, sFile)
AS=r'net use '+sFolder+r' /user:'+sUN+r' '+sPWD+r' /P:No'
if ExecuteCMD(AS):
writeText(sPath, '='*5+os.environ['computername']+' start time: '+time.strftime("%d/%m/%Y")+' '+time.strftime("%H:%M:%S")+'='*5+'
')
str=ExecuteCMD(Command, True)
writeText(sPath, str+'
')
DS=r'net use '+sFolder+r' /delete'
writeText(sPath, '='*5+os.environ['computername']+' end time: '+time.strftime("%d/%m/%Y")+' '+time.strftime("%H:%M:%S")+'='*5+'
')
ExecuteCMD(DS)
print 'command executed successfully :)
check the output file at: '+sPath
else:
print 'the path '+sFolder+' is not accessible by the credential, username:'+sUN+' and password:'+sPWD+' :('
Sample Output:
Sample Output File:
Script File:
filename.txt (4.69 KB)
20170301-COP-37-run-powershell-command-and-output-it-to-network-file-path.json (3.51 KB)