I am running a batch file which in turn runs a python file. I want to execute netsh command to change the IPv4 settings from static to dhcp and vice versa.
When I run the below code it executes and returns without any error
import subprocess
cmd = "netsh interface ip show config"
output = subprocess.check_output(cmd)
print output
But when I execute the this piece of code through a batch file the python file exits with exit status 1.
import subprocess
cmd = '''netsh interface ip set address "Local Area Connection 9" dhcp'''
output = subprocess.check_output(cmd)
print output
And It throws an error
Python: can't open file 'Update_DHCP.py': [Errno 2] No such file or directory
The python file and the batch file are in same folder and as per my understanding of updating the dhcp Ip, requires admin rights. I am even running the .bat file as 'Run as Administrator' but got the error [Errno 2]
I have also tried to create a task using task scheduler to grant admin rights to the .bat file and run it. But still, it din't work for me.
Can any one help me execute the command using subprocess.check_output() as I want to use the output returned by the check_output() call. Any help would be appreciated.
I am working on Windows and my python version is 2.7
Related
I am trying to run a .bat file in my Google Colab notebook, howere I cannot seem to make it happen. Whenever I navigate to the folder the code says the directory or file does not exist.
from subprocess import Popen
p = Popen("batch.bat", cwd=r"/content/drive/MyDrive/sd/stable-diffusion/merge-models-main/")
stdout, stderr = p.communicate()
Colab is an Ubuntu Linux environment so it will struggle if the file to be run contains Windows like commands. If the file contains Linux shell commands then the following code illustrates how to execute these.
This cell makes a batch.bat file (purists would argue that it should be batch.sh).
# This is a Unix shell script
with open('batch.bat', 'w') as f:
f.write('var=$(date)\r\n')
f.write('echo "$var" > output.txt\r\n')
The file is placed into /content/ by default. If you want to use a file from your own Google Drive, you have to mount this yourself.
To execute the commands in the file do this. Note how Popen takes a list with the location of the file to execute as the second parameter.
from subprocess import Popen
p = Popen(["/bin/sh", "/content/batch.bat"])
stdout, stderr = p.communicate()
Look for the file output.txt and observe the timestamp in it. This should give an indication whether it is working.
I am trying to run FreeCAD, a CAD application, through python.
You can control it through the command line by providing a script (pyhthon) to the executable.
The problem is that you need administrative privileges to run the .exe file. So what I do in Windows, is the following.
I open CMD as an administrator, and then I type:
"C:\Program Files\FreeCAD 0.18\bin\FreeCADCmd.exe" -l "C:\Users\Henry\Desktop\cylinder_macro.py"
This works!
However, I am having difficulties making it work from python.I am trying to implement what has been suggested in this post: Run process as admin with subprocess.run in python
import subprocess
prog = subprocess.run(['runas', '/noprofile', '/user:Administrator', "C:\\Program Files\\FreeCAD 0.18\\bin\\FreeCADCmd.exe","C:\\Users\\Henry\\Desktop\\cylinder_macro.py"])
It does not work.
If I print prog, I get:
CompletedProcess(args=['runas', '/noprofile', '/user:Administrator', 'C:\\Program Files\\FreeCAD 0.18\\bin\\FreeCADCmd.exe', 'C:\\Users\\Dorian\\Henry\\cylinder_macro.py'], returncode=1)
Any ideas of how to get this to work are highly appreciated
I look after a Lab with a number of Rigs in it and I am developing an automated process for running experiments. The trigger for loading the experiments is to use a particular username. I have a flowchart that identifies behaviours when logging on so that when a rig is booked to the particular username and nobody else is logged on, then it takes over and runs experiments during the night etc.
I need to be able to use python to run a batch file to log users off (unless there is a python command I can use). I have written a batch file that does this (LogOffIP.bat). If I run the batch file from a command prompt, it works fine and the users (chosen by the session id on the remote PC) get logged off and all is well.
I have a python script that calls the bat file with the same arguments and the command prompt pops up and runs but I get a different response like " 'logoff' is not recognized as an internal or external command", and the same for quser.
Please check out my code below and help me find a python solution.
Thanks...
LogOffIP.bat:
#echo off
echo Logging off Rig %1
echo at IP address %2
echo using session ID %3
echo.
echo.
logoff %3 /server:%2
echo Done...
echo
quser /server:%2
pause
rem exit
From python...
I have tried:
import os
os.system(r"path\LogOffIP.bat G 100.100.100.100 12")
this gives 'logoff' is not recognized.
I have tried:
import subprocess
answer = subprocess.call([path\LogOffIP.bat, G, 100.100.100.100, 1'])
this gives WindowsError: [Error 2] The system cannot find the file specified in python.
I have tried:
answer = subprocess.Popen([r'path','LogOffIP.bat','G 100.100.100.100 1'])
this gives WindowsError: [Error 5] Access is denied in python
I have used bogus IP addresses in the examples to protect the real ones.
I expect a short delay and the user is logged off as seen when running the batch file from a command prompt. os.system doesn't seem to support all the dos commands.
Try the following...
import subprocess
answer = subprocess.call([r'LogOffIP.bat', G, 100.100.100.100, 1'])
This is assuming that LogOffIP.bat is in the same directory as the .py file
I am connected to a first Raspberry Pi (172.18.x.x) in SSH and I would like to launch a script on the first RPI but the script is on another Raspberry Pi (192.168.x.x).
First, I did the configuration to connect without password to the second RPI from the first one.
When I am on the first one, I am launching this command :
ssh pi#192.168.x.x 'sudo python script_RPI2.py'
And this is working correctly, I can check the correct results but I would like to launch this script in another script on the first RPI. So, I put the previous command in the file : script_RPI1.py.
Then, I am launching the script : sudo python script_RPI1.py
And I got the following error :
ssh pi#192.168.x.x
^
SyntaxError: invalid syntax
Anyone has an idea concerning my problem ?
How are you launching the script? What appears from the minimal information you gave is that you are trying or to do that command within the Python interactive interpreter or that you want to execute it in the interpreter and you forgot to surround it with quotes(") in order to make it as a string.
Try to explain a bit more please.
You want to run a bash command:
ssh pi#192.168.x.x 'sudo python script_RPI2.py'
you show do it in a .sh file as in the following example:
#!/bin/sh
ssh pi#192.168.x.x 'sudo python script_RPI2.py'
After saving this file just do ./name_of_file.sh, which will simply run your bash file in the terminal, if you want to run a python script that opens a terminal in another process and executes string that are terminal commands you should look at something like this:
from subprocess import call
call(["ls"])
This will execute ls in another terminal process and return the result back to you. Please check what you want to actually do and decide on one of these paths.
Modified the entire answer and actually put some extra time on the code. The full solution for you to integrate will look something like the code below. Note that the code is setup in a way that you can define the host to connect to, along with the command you want to execute in the remote RPi
import subprocess
import sys
remoteHost="pi#192.168.x.x"
command="python /path/to/script.py"
ssh = subprocess.Popen(["ssh", "%s" % remoteHost, command],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result
yourVar = result ### This is where you assign the remote result to a variable
I am attempting to scrape a terminal window of the list of fonts installed on the curent hosting server. I have written the following code:
import subprocess
cmd = 'fc-list'
output = subprocess.Popen(cmd, stdout=subprocess.PIPE ).communicate()[0]
but when i call this code, an exception is raised:
[Errno 2] No such file or directory
I can open a terminal window, and this works fine. What am i doing wrong?
You need to provide the absolute path to the executable. When you open a terminal window you then have a shell running which will search in $PATH to find the program. When you run the program directly, via subprocess, you do not have a shell to search $PATH. (note: it is possible to tell subprocess that you do want a shell, but usually this leads to security vulnerabilities)
Here is what you would want to use:
import subprocess
cmd = '/usr/local/bin/fc-list'
output = subprocess.Popen(cmd, stdout=subprocess.PIPE ).communicate()[0]