I can use "nginx -s reload" command to restart nginx on the shell.
But, when I use os.system("nginx -s reload") command, It appears error.
/usr/local/bin/nginx: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory
For this error. I already install pcre. Is there some magic problems.
For running such commands in python scripts it's better to use subprocess library.
try this code instead of yours:
import subprocess
subprocess.call('whatever command you want to run it in terminal', shell=True)
Be lucky
hello I recommend that you first send this validation before sending the reset so you avoid headaches
reinicioNGINX = subprocess.getoutput(['nginx -t'])
if 'nginx: the configuration file /etc/nginx/nginx.conf syntax is ok' in reinicioNGINX:
_command_restart
else:
_command_avoid_restart
Related
I have issue while running subprocess in Python CGI script.
I am going to run python file as subprocess in python CGI script.
script.py
#!enable debugging
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
import subprocess
p = subprocess.Popen(["sudo", "/usr/bin/python3", "test.py"], stdout=subprocess.PIPE)
test.py
f.open("test.txt", "a")
f.write("This is test")
f.close()
If I run script.py in console, it creates test.txt file successfully.
But If I run it on browser with Python CGI, it cannot create test.txt.
I thought, it can be caused by permission, so I tried to create test.txt in script.py directly, not on 'test.py', it is created successfully.
So, main issue is Python CGI script cannot run subprocess.
I cannot get any error while running on browser as Python CGI script.
How can I fix this issue?
Please if sudo does not work, look in the system log. There can be messages that help you with the debugging. The files are in /var/log and if you list by time ls -t you will see which ones changed just now.
First try without sudo. Make your file in a place where it does not need sudo permission like /tmp/test.txt. Then you know if the problem is sudo or something else.
I am creating a script to run shell commands for simulation purposes using a web app. I want to run a shell command in a django app and then save the output to a file.
The problem I am facing is that when running the shell command, the output tries to get saved in the url that is invoked (for example: localhost:8000/projects) which is understandable.
I want to save the output to for example:
/home/myoutput/output.txt rather than /projects or /tasks
I have to run a whole script and save it's output to the txt file later but that is easy once this is done.
Tried os.chdir() function to change directory to /desiredpath already
from subprocess import run
#the function invoked from views.py
def invoke_mpiexec():
run('echo "this is a test file" > fahadTest.txt')
FileNotFoundError at /projects
Exception Type: FileNotFoundError
First I want to say that directly calling external programs from a web request in Django is a bit of an anti-pattern. The preferred approach is to use a work queue like Celery or rq, but that comes with a bit of added complexity.
That being said, you can solve your problem with the argument shell=True:
from subprocess import run
#the function invoked from views.py
def invoke_mpiexec():
run('echo "this is a test file" > fahadTest.txt', shell=True)
Here is the documentation:
If shell is True, the specified command will be executed through the
shell. This can be useful if you are using Python primarily for the
enhanced control flow it offers over most system shells and still want
convenient access to other shell features such as shell pipes,
filename wildcards, environment variable expansion, and expansion of ~
to a user’s home directory. However, note that Python itself offers
implementations of many shell-like features (in particular, glob,
fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and
shutil).
Note: Using shell=True can lead to security issues:
If the shell is invoked explicitly, via shell=True, it is the
application’s responsibility to ensure that all whitespace and
metacharacters are quoted appropriately to avoid shell injection
vulnerabilities.
You should use subprocess.call with stdout argument
def invoke_mpiexec():
f = open("fahadTest.txt", "w")
subprocess.call(['echo', '"this is a test file"'], stdout=f)
or use write function
def invoke_mpiexec():
f = open('fahadTest.txt', 'w')
f.write("Now the file has more content!")
f.close()
So I figured it out.
Below is the fix:
run('mkdir -p $HOME/phdata/test/ && echo "this is a test file" > $HOME/phdata/test/fahadTest.txt', shell=True)
mkdir -p creates a directory if it doesn't exist
$HOME is used to go to the home directory and from there you can
navigate to folders.
shell=True argument is required to run it as shell command
You can also create a ssh connection and run the commands/ scripts on the remote server. For this, my approach will be to create a script on the remote server, call it through my app and provide arguments to it. Another workaround which is not that good but works is to create a script on the server using the above line and then call it.
I have a simple ansible playbook which will call a shell script on a remote server, the shell script will call another python script, which will do something, when I run the ansible playbook, the script is not working, but when I ssh to the server and run the same command manually, it worked. I've done some debugging, seems when calling the python script, if I delete all the import statements from the python script, it works from ansible, but I don't understand why it works when I ssh to the server and would like to have some suggestion on how to resolve this issue.
the python script:
#!/usr/bin/python
import socket
import argparse
import logging
import subprocess
import time
import imp
def main():
f = open('/afile', 'w')
f.write('a test line')
f.close()
if __name__ == '__main__':
main()
those imports are not using here, it will be used in my real script, here I just write a line into a file for debugging.
The ansible playbooks are just simply like:
---
- hosts: servers
tasks:
- name: trigger the script
shell: /start.sh
The start.sh then simply invoke the python script:
#!/bin/sh
/start.py
sorry, it's my bad, I didn't put all the scripts here, seems that there is another script which has things like
#!/bin/sh
/start & >> stdout.log
this caused the problem, I guess the first three modules imported have things related to standard io, so the solution is using nohup.
again, very sorry for the incomplete question.
I'm using Python 2.7 with the latest plumbum package from mac ports.
In general, plumbum works great. Though I'm having a heck of a time getting a sudo'd command to work. I've setup my /etc/sudoers for the commands I want to run without having to be prompted, so that's fine. I can run the commands manually without issue.
However, when I try the same from python using this:
sudo["/usr/local/some-magic-command here"]
sudo("-u " + sudoUser) # sudo user is userfoo
I receive the following error:
plumbum.commands.processes.ProcessExecutionError: Command line: ['/usr/bin/sudo', '-u userfoo']
Exit code: 1
Stderr: | sudo: unknown user: userfoo
The user does exist, so not exactly sure what the deal is here.
Comments?
There is no "-u userfoo" user. There is probably just "userfoo". Note: no -u prefix. Try:
from plumbum.cmd import sudo
as_userfoo = sudo["-u", sudo_user]
print(as_userfoo("whoami"))
Assume I have a file at http://mysite.com/myscript.sh that contains:
#!/bin/bash
echo "Hello $1"
From the command line, I can execute my script (without downloading it) using the following command:
bash <(curl -s http://mysite.com/myscript.sh) World
Now, instead of executing the above command from the command line, I want to execute it from a python script. I tried doing the following:
import os
os.system('bash <(curl -s http://mysite.com/myscript.sh) World')
...but I get the following error:
sh: -c: line 0: syntax error near unexpected token `('
How do I make this execute correctly in python?
Evidently, os.system runs its command through /bin/sh, which usually causes whichever shell it's linked to to drop to a compatibility mode that doesn't include the <(...) construction. You can get around it by either storing the result in a temporary file or using another level of shell. Ugly, but it works.
os.system('bash -c "bash <(curl -s http://mysite.com/myscript.sh) World"')
There is a libcurl for python so you don't have to go the way around to command line behaviour. Here's the function list that should really do it - have never run remote scripts myself though. If you need installing the python binding, the instructions are here.
import curl