I have the code that you can see below. I'm trying to go first to the directory and then,with the pipe "|" make a backup of the MongoDB´s database.The problem is that when I launch the script the console returns me
mongodump is not an internal or external command.
On the other hand,if I launch the same line
cd C:\\...\\MongoDB\\Server\\3.6\\bin | mongodump -h ip -d database name -o C:\\Users\\...\\Desktop\\BackUpMongo
in my system cmd it works without problems. Any idea?
import sys
import os
if __name__ == '__main__':
try:
os.system('cd C:\\...\\MongoDB\\Server\\3.6\\bin | mongodump -h ip -d database name -o C:\\Users\\...\\Desktop\\BackUpMongo')
print("Copia de seguridad finalizada")
except:
print("Error during data base backup")
sys.exit(0)
Use os.chdir() instead of os.system('cd ...').
import os
os.chdir('C:\\...\\MongoDB\\Server\\3.6\\bin')
os.system('mongodump -h ip -d database name -o C:\\Users\\...\\Desktop\\BackUpMongo')
print("Copia de seguridad finalizada")
Related
I need to execute the following command from Python on Windows:
psql -h localhost -p 5432 -U postgres -f script.sql db_name
The above script works fine when ran from git bash / powershell. After entering the script in a terminal, I need to provide a password to confirm it (similar to when using sudo).
How can I do that? I keep finding solutions that I think are linux-based.
How do I do it on Windows? I have tried many variations of solutions involving subprocess, i.e:
import subprocess
p2 = subprocess.Popen(
'psql -h localhost -p 5432 -U postgres -f script.sql db_name',
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
print('this will print')
sudo_prompt = p2.communicate('THE_PASSWORD' + '\n')[1]
print('this will not')
A better option (more secure) than invoking psql with explicit mention of your password is to have a .pgpass file as described in the docs file (and keep it protected e.g. chmod 600 ~/.pgpass). This keeps your password out of the list of running processes.
On Windows:
On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).
I am trying to figure out the python command-line option -d. From the documentation it says -d Turn on parser debugging output.
But when I test, it shows me nothing but an argument:
main.py
import sys
def main(argv):
print(argv)
if __name__ == "__main__":
main(sys.argv[1:])
Execute in cmd:
$ python main.py -d /path/to/file
O/P:
['-d', 'C:/Program Files/Git/path/to/file']
Here -d print as an argument. Can anybody tell me the purpose of the -d option and how to use it?
-d is python option, not yours. So proper invocation is
$ python -d main.py /path/to/file
This is the situation:
I've 2 script in python running in 2 different shells in Linux:
1° - python3 server.py
2° - python3 roomcontrol.py
I need that the user can restart roomcontrol.py from server.py.
I tried with subprocess:
from subprocess import call
dir = os.path.dirname(os.path.realpath(__file__)) + "/roomcontrol.py"
call(["python3",dir])
These instructions just start a new istance of "roomcontrol.py" in the shell of "server.py", I need to restart roomcontrol.py in his shell. Or close his shell and open a new one.
Edit:
I also tried:
import subprocess
dir = os.path.dirname(os.path.realpath(__file__)) + "/roomcontrol.py"
subprocess.Popen([dir], stdout=subprocess.PIPE, shell=True)
It doesn't work.
It writes a lot of stuff in the same shell of server.py and my cursor become a cross and if I click somewhere it wrtes stuff like before. A little example of what it writes:
import: unable to grab mouse `': Resource temporarily unavailable # error/xwindow.c/XSelectWindow/9199.
import: unable to grab mouse `': Resource temporarily unavailable # error/xwindow.c/XSelectWindow/9199.
.
.
.
from: can't read /var/mail/xml.dom
/home/stark/Desktop/TrackingOk/Release/roomcontrol.py: 9: /home/stark/Desktop/Tr: not foundlease/roomcontrol.py:
/home/stark/Desktop/TrackingOk/Release/roomcontrol.py: 10: /home/stark/Desktop/T: not foundelease/roomcontrol.py: try:
Create a new .sh file ("restart.sh" for example):
#!/bin/bash
kill $(pgrep -f 'python3 roomcontrol.py')
python3 roomcontrol.py &
Then just call
os.system('./restart.sh')
somewhere in your "server.py" script.
PS: You have to make the .sh file executable by running the following command:
chmod +x restart.sh
Edit: I'm not sure how you can start a process from a different shell, but you can start "roomcontrol.py" in another terminal window with the following (bash) command:
gnome-terminal -x sh -c 'python3 roomcontrol.py'
But then you'd have to replace "restart.sh" by
#!/bin/bash
kill -9 $(pgrep -f 'sh -c python3 roomcontrol.py')
gnome-terminal -x sh -c 'python3 roomcontrol.py'
I am trying to execute a python script on remote machine using psexec. The python script is already on the remote machine i only want to execute it there. I am using the following command:
psexec -i -s -d \\123 -u xyz -p xyz C:/sample.py
But i get error as :
PsExec could not start C:\sample.py on 123:
The system cannot find the file specified
I tried placing the python exe path also in the psexec comand as:
psexec -i -s -d \\123 -u xyz -p xyz C:\programs\python.exe C:/sample.py
then it opens the python.exe but does not execute the sample.py. The paths are all correct. But i am not getting why the psexec command is not able to find the script. Please suggest how shall i execute the script on the remote machine using psexec.
Remove the -d option from the command and provide the path in quotes and use backslash in path
try adding " " around the exe filename
psexec -i -s -d \\123 -u xyz -p xyz "C:\programs\python.exe" C:/sample.py
if it doesn't work, try adding " " also around the parameters
psexec -i -s -d \\123 -u xyz -p xyz "C:\programs\python.exe" "C:/sample.py"
I created an SSH-Agent to provide my key to the ssh/scp cmd when connecting to my server.
I also scripted a SSH-Add with the command 'expect' to write my paraphrase when it's needed.
This works perfectly with my user "user".
But I'm executing a python script that uses /dev/mem that need to be run as root through sudo. This python script call another bash script with ssh and scp cmd inside.
Therefore all these cmd are executed as root and my agent/ssh-add doesn't work anymore, keeping asking for the paraphrase for each file.
How could I fix that ? I don't want to log as root and run a agent as root.
I tried the sudo -u user ssh but it doesn't work (ie: need to enter my paraphrase)
Any ideas?
Thanks in advance,
Mat
EDIT: my code:
The py script needing the sudo
#!/usr/bin/env python2.7
import RPi.GPIO as GPIO
import time
import subprocess
from subprocess import call
from datetime import datetime
import picamera
import os
import sys
GPIO.setmode(GPIO.BCM)
# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#set path and time to create the folder where the images will be saved
pathtoscript = "/home/pi/python-scripts"
current_time = time.localtime()[0:6]
dirfmt = "%4d-%02d-%02d-%02d-%02d-%02d"
dirpath = os.path.join(pathtoscript , dirfmt)
localdirname = dirpath % current_time[0:6] #dirname created with date and time
remotedirname = dirfmt % current_time[0:6] #remote-dirname created with date and time
os.mkdir(localdirname) #mkdir
pictureName = localdirname + "/image%02d.jpg" #path+name of pictures
var = 1
while var == 1:
try:
GPIO.wait_for_edge(23, GPIO.FALLING)
with picamera.PiCamera() as camera:
#camera.capture_sequence(["/home/pi/python-scripts/'dirname'/image%02d.jpg" % i for i in range(2)])
camera.capture_sequence([pictureName % i for i in range(19)])
camera.close()
cmd = '/home/pi/python-scripts/picturesToServer {0} &'.format(remotedirname)
call ([cmd], shell=True)
except KeyboardInterrupt:
GPIO.cleanup() # clean up GPIO on CTRL+C exit
GPIO.cleanup() # clean up GPIO on normal exit
the bash script:
#!/bin/bash
cd $1
ssh user#server mkdir /home/repulsion/picsToAnimate/"$1" >/dev/null 2>&1
ssh user#server cp "$1"/* /home/repulsion/picsToAnimate/"$1"/ >/dev/null 2>&1
for i in $( ls ); do
scp $i user#server:/home/repulsion/picsToAnimate/"$1"/ >/dev/null 2>&1
done
You will need the SSH agent environment variables to be passed in through the sudo.
To do so, you can run sudo -E to pass all environment variables in through sudo; but this can be dangerous, so it's probably better to pass just the ones you need. The easiest way to do this is for sudo to invoke env to invoke the given program with the appropriate environment variables set:
$ sudo env SSH_AGENT_PID=$SSH_AGENT_PID SSH_AUTH_SOCK=$SSH_AUTH_SOCK my-script
The environment variables needed for shh-agent are removed by sudo. see here for how to keep them.
But why do you have a ssh-add there type the passphrase for you insted of just having a ssh key with no passphrase? You can remove it with
ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]