I'm trying to run a powershell script (with parameters) from within python (version 3.8.3), and after reading many stackoverflow posts I came to the following code:
import subprocess
path = r"'C:\Program Files\Company\Some space\Some-Script.ps1'"
args = r"-UserId abcd1234 -PageUri https://example.com/testapp -Privileges #('ReadOnly', 'ReadWrite')"
full_command = f'"& {path} {args}"';
result = subprocess.run(['powershell.exe', full_command ], capture_output=True)
print('printing out ...')
print(result.stdout)
print('printing error ...')
print(result.stderr)
However when I run the above python script, the following output is generated .... which is basically just dumping the powershell command back out without actually running it (by the looks of it)
printing out ...
b"& 'C:\\Program Files\\Company\\Some space\\Some-Script.ps1' -UserId abcd1234 -PageUri https://example.com/testapp -Privileges #('ReadOnly', 'ReadWrite')\r\n"
printing error ...
b''
The python code above was generated using the following Windows shell command, which works fine:
powershell.exe "& 'C:\Program Files\Company\Some space\Some-Script.ps1' -UserId abcd1234 -PageUri https://example.com/testapp -Privileges #('ReadOnly', 'ReadWrite')"
Can someone kindly tell me what is the issue with my python code ?
Related
I'm trying to write a python script that can launch DaVinci Resolve in headless mode, then send it some commands via its API, then close it.
What I'm looking for would look something like
Open resolve.exe with argument --nogui
Do stuff with the API here
Terminate this instance of Resolve
I've managed to launch an instance of Resolve in headless. But it always ends up being a subprocess of something else. While it's running as a subprocess, I can't get the API to communicate with it.
Here's the code of tried
import subprocess
args = ["C:\Program Files\Blackmagic Design\DaVinci Resolve\Resolve.exe", '--nogui']
resolve_headles = subprocess.Popen(args)
from python_get_resolve import GetResolve
resolve = GetResolve()
This should return an object of Resolve, but it always fails.
I believe this is because its running as a subprocess of my IDE
I've also tried this
from subprocess import call
dir = "C:\Program Files\Blackmagic Design\DaVinci Resolve"
cmdline = "Resolve.exe --nogui"
rc = call("start cmd /K " + cmdline, cwd=dir, shell=True)
This just has the same problem of Resolve running as a subprocess of Windows Command Processor.
so i have gone from a linux working environment to windows during the pandemic working from home.
I am using what was the family computer so cant really change to linux on it.
I am trying to combine two files into a third file on linux i can do this using the following
cat file1 file2 > file3
in python i can do this using subprocess this worked fine at my office
on windows i was told it can be done using type with the following command
type file1 file2 > file3
if i run this manually via cmd it works fine and results in a 7mb file but if i try and run the command using subprocess in python the result is a 165byte file
if i print the stdout i simply get the following
b''
the function i am using to run the sub process is as follows
def RUN_SUBPROCESS(COMMAND, LOG):
print('#### STARTING SUB PROCESS')
SUB_PROCESS = subprocess.Popen(COMMAND, shell=True, stdout=subprocess.PIPE)
out, err = SUB_PROCESS.communicate()
SUB_PROCESS.wait()
if LOG == 'true':
print('#### OUTPUT')
print(out)
print('#### ERROR')
print(err)
print('#### SUB PROCESS COMPLETE')
return
I have a batch file which is running a python script and in the python script, I have a subprocess function which is being ran.
I have tried subprocess.check_output, subprocess.run, subprocess.Popen, all of them returns me an empty string only when running it using a batch file.
If I run it manually or using an IDE, I get the response correctly. Below is the code for subprocess.run:
response = subprocess.run(fileCommand, shell=True, cwd=pSetTableauExeDirectory, capture_output=True)
self.writeInLog(' Command Response: \t' + str(response))
Response is in stdout=b''
When ran in batch file and from task scheduler:
Command Response: CompletedProcess(args='tableau refreshextract
--config-file "Z:\XXX\tableau_config\SampleSuperStore.txt"',
returncode=0, stdout=b'', stderr=b'')
When ran manually or in IDE:
Command Response: CompletedProcess(args='tableau refreshextract
--config-file "Z:\XXX\tableau_config\SampleSuperStore.txt"',
returncode=0, stdout=b'Data source refresh completed.\r\n0 rows uploaded.\r\n', stderr=b'')
Batch file which runs the python program. Parameters are parsed to the python application
SET config=SampleSuperStore.txt
CALL C:\XXX\AppData\Local\Continuum\anaconda3\Scripts\activate.bat
C:\XXX\AppData\Local\Continuum\anaconda3\python.exe Z:\XXX\pMainManual.py "%config%"
Why is that??
--Complete python code---
try:
from pWrapper import wrapper
import sys
except Exception as e:
print(str(e))
class main:
def __init__(self):
self.tableauPath = 'C:\\Program Files\\Tableau\\Tableau 2018.3\\bin\\'
self.tableauCommand = 'tableau refreshextract --config-file'
def runJob(self,argv):
self.manual_sProcess(argv[1])
def manual_sProcess(self,tableauConfigFile):
new_wrapper = wrapper()
new_wrapper.tableauSetup(self.tableauPath,self.tableauCommand)
if new_wrapper.tableauConfigExists(tableauConfigFile):
new_wrapper.tableauCommand(tableauConfigFile)
if __name__ == "__main__":
new_main = main()
new_main.runJob(sys.argv)
Wrapper class:
def tableauCommand(self,tableauConfigFile):
command = self.setTableauExeDirectory + ' ' + self.refreshConfigCommand + ' "' + tableauConfigFile + '"'
self.new_automateTableauExtract.runCommand(tableauConfigFile,command,self.refreshConfigCommand,self.tableauFilePath,self.setTableauExeDirectory)
Automate Class:
def runCommand(self,pConfig,pCommand,pRefreshConfigCommand,pFilePath,pSetTableauExeDirectory):
try:
fileCommand = pRefreshConfigCommand + ' "' + pFilePath + '"'
response = subprocess.run(fileCommand, shell=True, cwd=pSetTableauExeDirectory, capture_output=True)
self.writeInLog(' Command Response: \t' + str(response))
except Exception as e:
self.writeInLog('Exception in function runCommand: ' + str(e))
UPDATE: I initially thought that the bat file was causing this issue but it looks like it works when running manually a batch file but not when it is set on task scheduler
Updated
First of all, if there is a need to run anaconda-prompt by calling activate.bat file, you can simply do as follows:
import subprocess
def call_anaconda_venv():
subprocess.call('python -m venv virtual.env')
subprocess.call('cmd.exe /k /path/venv/Scripts/activate.bat')
if __name__ == "__main__":
call_anaconda_venv()
The result of the above code would be a running instance of anaconda-prompt as required.
Now as Problem Seems Like:
I have a batch file which is running a python script and in the python script, I have a subprocess function which is being run.
I have implemented the same program as required; Suppose we have
Batch File ---> script.bat **** includes a command to run python script i.e test.py. ****
Python Script File ---> test.py **** includes a method to run commands using subprocess. ****
Batch File ---> sys_info.bat **** includes a command which would give the system information of my computer. ****
Now First, script.bat includes a command that will run the required python script as given below;
python \file_path\test.py
pause
Here, pause command is used to prevent auto-closing console after execution. Now we have test.py, python script which includes subprocess method to run required commands and get their output.
from subprocess import check_output
class BatchCommands:
#staticmethod
def run_commands_using_subprocess(commands):
print("Running commands from File: {}".format(commands))
value = check_output(commands, shell=True).decode()
return value
#staticmethod
def run():
commands_from_file = "\file-path\sys_info.bat"
print('##############################################################')
print("Shell Commands using >>> subprocess-module <<<")
print('##############################################################')
values = BatchCommands.run_commands_using_subprocess(commands_from_file)
print(values)
if __name__ == '__main__':
BatchCommands.run()
Now, in the end, I have a sys_info.bat file which includes commands to renew the IP-Adress of my computer. Commands in sys_info.bat file are as follows;
systeminfo
Place multiple commands in sys_info.bat file, then you can also run multiple commands at a time like:
ipconfig/all
ipconfig/release
ipconfig/reset
ipconfig/renew
ipconfig
Before to use the file, set all files directory paths, and run the batch file i.e script.py in command-prompt as follows;
Run command-prompt or terminal as an administrator.
run \file_path\script.py
Here is the result after running the batch file in the terminal.
This is happening because your ide is not running in a shell that works in the way that open subprocess is expecting.
If you set SHELL=False and specify the absolute path to the batch file it will run.
you might still need the cwd if the batch file requires it.
I am running several python scripts via rundeck (in-line) on windows 2012 target node. These scripts used to run locally but now in the process of moving to rundeck.
One of the python scripts opens subprocess to invoke a powershell script and read the output.
import subprocess
CMD = [r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe ', '-File', r'C:\Users\Osman\Code\mop.ps1']
cmd = CMD[:]
cmd.append('arg1')
cmd.append('arg2')
cmd.append('arg3')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
r = p.communicate()
print(r)
The mop.ps1 is
Import-Module MSOnline
$domain = $args[0]
$login = $args[1]
$pass = $args[2]
$EPass = $pass | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential($login, $EPass)
Connect-MsolService -Credential $Cred
$TenantId = Get-MsolPartnerContract -Domain $domain | Select-Object -ExpandProperty TenantId
Get-MsolAccountSKU -TenantId $TenantId | select SkuPartNumber,ActiveUnits,ConsumedUnits | ConvertTo-Csv -NoTypeInformation
This part of the code always fails to execute and if I check stderr it says:
Connect-MsolService : Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
At C:\Users\Osman\Code\mop.ps1:7 char:1
+ Connect-MsolService -Credential $Cred
I'm not sure why it fails. I tried
Import-Module MSOnline -Verbose
And I can see Cmdlets being loaded. I tried creating profile.ps1 file in C:\WINDOWS\system32\WindowsPowerShell\v1.0\ location.
Everything works fine if I execute the code locally. I tried running a regular test .ps1 file 'disk.ps1' instead of my code, and that works fine because it doesn't load any modules:
get-WmiObject win32_logicaldisk -Computername $env:computername
What's the workaround to get a script with module to run properly? stdout is always empty.
Node is registered as 64 bit so I tried changing the cmd to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
I tried to copy profile.ps1 there, copied the Module there but still doesn't work via rundeck.
From your description, since you are able to get a valid output when running the script directly from the server, it may be possible that you error could be related to the “Second Hop” that you use to login into MS-Online. Currently, the Rundeck Python-Winrm plugin supports Basic, ntlm or CredSSP Authentication, and CredSSP authentication allows you to perform the second hop successfully.
So I have this python3 script that does a lot of automated testing for me, it takes roughly 20 minutes to run, and some user interaction is required. It also uses paramiko to ssh to a remote host for a separate test.
Eventually, I would like to hand this script over to the rest of my team however, it has one feature missing: evidence collection!
I need to capture everything that appears on the terminal to a file. I have been experimenting with the Linux command 'script'. However, I cannot find an automated method of starting script, and executing the script.
I have a command in /usr/bin/
script log_name;python3.5 /home/centos/scripts/test.py
When I run my command, it just stalls. Any help would be greatly appreciated!
Thanks :)
Is a redirection of the output to a file what you need ?
python3.5 /home/centos/scripts/test.py > output.log 2>&1
Or if you want to keep the output on the terminal AND save it into a file:
python3.5 /home/centos/scripts/test.py 2>&1 | tee output.log
I needed to do this, and ended up with a solution that combined pexpect and ttyrec.
ttyrec produces output files that can be played back with a few different player applications - I use TermTV and IPBT.
If memory serves, I had to use pexpect to launch ttyrec (as well as my test's other commands) because I was using Jenkins to schedule the execution of my test, and pexpect seemed to be the easiest way to get a working interactive shell in a Jenkins job.
In your situation you might be able to get away with using just ttyrec, and skip the pexpect step - try running ttyrec -e command as mentioned in the ttyrec docs.
Finally, on the topic of interactive shells, there's an alternative to pexpect named "empty" that I've had some success with too - see http://empty.sourceforge.net/. If you're running Ubuntu or Debian you can install empty with apt-get install empty-expect
I actually managed to do it in python3, took a lot of work, but here is the python solution:
def record_log(output):
try:
with open(LOG_RUN_OUTPUT, 'a') as file:
file.write(output)
except:
with open(LOG_RUN_OUTPUT, 'w') as file:
file.write(output)
def execute(cmd, store=True):
proc = Popen(cmd.encode("utf8"), shell=True, stdout=PIPE, stderr=PIPE)
output = "\n".join((out.decode()for out in proc.communicate()))
template = '''Command:\n====================\n%s\nResult:\n====================\n%s'''
output = template % (cmd, output)
print(output)
if store:
record_log(output)
return output
# SSH function
def ssh_connect(start_message, host_id, user_name, key, stage_commands):
print(start_message)
try:
ssh.connect(hostname=host_id, username=user_name, key_filename=key, timeout=120)
except:
print("Failed to connect to " + host_id)
for command in stage_commands:
try:
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
except:
input("Paused, because " + command + " failed to run.\n Please verify and press enter to continue.")
else:
template = '''Command:\n====================\n%s\nResult:\n====================\n%s'''
output = ssh_stderr.read() + ssh_stdout.read()
output = template % (command, output)
record_log(output)
print(output)