I'm trying to run Python file with root access with php index
in php there is :
passthru('python /home/register/register.py '. $_POST['username'] . ' example.com ' . $_POST['password'] . ' ' . $_POST['email'] . ' ' . $ip . ' 1 2>&1');
and in Python file there is:
os.popen("sudo -u root -p password /sbin/ejabberdctl register %s %s %s" % (user,domain,password)).read()
is there any command with Python to login with root user then do command like : ls or mkdir
thnx.
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("mkdir foo\n")
p.stdin.write("id -u")
To see output use communicate:
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("ls -la\n")
p.stdin.write("/usr/bin/pip list\n")
p.stdin.write("id -u")
print(p.communicate()[0])
But be very sure you know what commands you are running.
I recently published a project that allows PHP to obtain and interact with a real Bash shell (as user: apache/www-data or root if needed). Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
//Setting the second argument in getShell():
//true will return a shell with root
//false will return a shell with the php execution user
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd("mkdir -p /some/path");
$return2 = $shell->exeCmd("ls --color=none /some/path");
notice the ls command has a switch called --color=none, that is needed because the bash shell will return color information as odd chars, the switch prevents it.
Related
I want to send a certificate to the remote server automatically with ssh-copy-id. I chose the python subprocess library for this, but somehow it does not send the password to the terminal.
I am aware that I can do this with sshpass or paramiko, but I don't want to choose it unless I have to. Can you help me with this? My code is below.
from subprocess import run,PIPE
send_cert = run(['ssh-copy-id', '-i', '~/.ssh/id_rsa.pub','pardus'], stdout=PIPE, input=input_cert, encoding='utf-8')
input_cert = '1'
pardus is my remote host's name. You can replace user#IP .
~ is replaced with the home directory by the shell, but you're not executing the command through a shell, so it's being interpreted literally.
You can use the os.path.expanduser() function to perform this substitution.
import os
from subprocess import run,PIPE
send_cert = run(['ssh-copy-id', '-i', os.path.expanduser('~/.ssh/id_rsa.pub'),'pardus'], stdout=PIPE, input=input_cert, encoding='utf-8')
I solved.
send_pass = 'PASSWORD' + '\n'
send_cert = 'ssh-copy-id -i ' + 'CERT_PATH' + ' ' + 'USER#HOSTNAME'
child = pexpect.spawn(send_cert,encoding='utf-8')
child.expect('password:')
child.sendline(send_pass)
time.sleep(2)
Thanks all.
I'm trying to use subprocess.run to build my CMake project but the code finishing without errors but its not working.
the code is:
import subprocess
git_repo_remvoe_destination = '/home/yaodav/Desktop/'
git_repo_clone_destination = git_repo_remvoe_destination + 'test_clone_git'
test_path = git_repo_clone_destination + "/test/"
cmake_debug_path = test_path + "cmake-debug-build"
cmake_build_command = " cmake -Bcmake-build-debug -H. -DCMAKE_BUILD_TYPE=debug -DCMAKE_C_COMPILER=/usr/local/bin/gcc " \
"-DCMAKE_CXX_COMPILER=/usr/local/bin/c++ -Bcmake-build-debug -H. " \
"-DSYTEM_ARCH=x86_64-pc-linux-gnu-gcc-7.4.0"
cmake_link_command = "cmake --build cmake-build-debug --target all"
cmake_command = ['cd '+test_path, cmake_build_command, cmake_link_command]
out = subprocess.run(cmake_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
I tried this answer but it didn't work
how to I do that?
2 Issues.
First you should call subprocess.run() once for each command instead of putting three different commands in a list.
Second: The cd ... command just changes the present working directory in one sub process and the consecutive command will not be any more in the same directory.
However there is a simple solution to it.
subprocess.run has a cwd parameter ( https://docs.python.org/2/library/subprocess.html#popen-constructor ) that allows you to specify the directory in which a subprocess should be executed.
So Following should do:
out = subprocess.run(cmake_build_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=test_path, shell=True)
out += subprocess.run(cmake_link_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=test_path, shell=True)
Based on this tutorial to build a TF image classifier, I have a bash shell in which I run a Docker image with the following command:
docker run --name fooldocker -it -v $HOME/tf_files:/tf_files/ gcr.io/tensorflow/tensorflow:latest-devel
And then in this docker image I run my Python script:
python /tf_files/label_image.py /tf_files/myimages
exit
It works.
But now, I need to automate these commands in a Python script. I tried :
p = Popen(['docker', 'run', '--rm', '--name', 'fooldocker','-it', '-v', '$HOME/tf_files:/tf_files/', 'gcr.io/tensorflow/tensorflow:latest-devel'], stdout=PIPE)
p = Popen(['docker', 'exec', 'fooldocker', 'python', '/tf_files/label_NES.py', '/tf_files/NES/WIP'])
p = Popen(['docker', 'kill', 'fooldocker'], shell=True, stdout=PIPE, stderr=PIPE)
p = Popen(['docker', 'rm', 'fooldocker'], shell=True, stdout=PIPE, stderr=PIPE)
Leading to this error after Popen #2 is run :
docker: Error response from daemon: create $HOME/tf_files: "$HOME/tf_files" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed.
The problem is that $HOME cannot be evaluated in this single quotes string. Either try doublequotes, or evaluate the variable beforehand and put it into the command string.
Also: If you set shell=True, you don't split your command into a list:
p = Popen('docker kill fooldocker', shell=True, stdout=PIPE, stderr=PIPE)
it is because Popen didn't interpret $HOME to your home path.
and it is the string $HOME and pass to docker command which not allow $ in a volume name.
maybe you can use subprocess module for convenience, for example:
import subprocess
subprocess.call("echo $HOME", shell=True)
it interpreted $HOME if shell=True specified.
Here is my situation :
We have sqlplus set up in a remote machine and I want to connect to that remote machine and then run sqlplus to execute sql queries. I am trying to write a python script to do that.
Here is my code:
import sys
import getpass
import paramiko
import time
user=raw_input('Enter User Name :')
#host_name=raw_input('Enter Host Name:')
psswd=getpass.getpass()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxx.hostname.xxx',port=22, username=user, password=psswd)
command='export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib \
sudo -S -H /XX/XX/XX/bin/sqlplus'
print 'running remote command'
print(command)
stdin, stdout, stderr=ssh.exec_command(command)
stdin.write(psswd+'\n')
stdin.flush()
for out in stdout.readlines():
print out
ssh.close()
I have two issues here
First is if i pass command like this
'export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib \
sudo -S -H /XX/XX/XX/bin/sqlplus' +' echo $ORACLE_HOME'
I get an empty response even if I have added echo that means that variable is not set correctly.
Secondly, I can't figure out what next to do here. How to provide username/password to sqlplus to allow executing sql queries and then how to supply sql statements.
I had a similar issue as you and eventually wrote a library to do this. Here's a snippet of 'psuedo psuedo code' that should point you in the right direction.
Keep in mind these are methods of a class and you'll need to adapt this pseudo code to your needs. Keep in mind you'll already need a SSHConnection from paramiko here.
def sqlplus_cmd(self, command):
# Create string which exports environmental variables from OracleEnv class ()
if 'CYGWIN' not in <return from 'uname' on the host>:
# If NOT Cygwin, concatenate environmental variable exports
oracle_exports = 'export PATH={0}:$PATH;' \
'export ORACLE_HOME={1};' \
'export ORACLE_SID={2}'.format(<oracle_path>, <oracle_home>, <oracle_sid>)
else:
# If Cygwin, need to source environmental variables for shell session from script
# TODO: May need to get Oracle Home and Path as well for some systems.
self.cmd('echo "export ORACLE_SID={0}" > /tmp/sid'.format(<oracle_sid>))
oracle_exports = 'source /tmp/sid'
# Issue concatinated one line command which exports variables, opens sqlplus, and issues a sqlplus statement
# final_command = oracle_exports + ';' + 'echo "' + command + '" | sqlplus -S / as sysdba'
final_command = '{0};echo "{1}" | sqlplus -S / as sysdba'.format(oracle_exports, command)
stdout, stderr, rc = <paramiko_SSHConnection.exec_command>(final_command)
That should do it. Have fun parsing the output and catching the ORA-xxx and SP2-xxx errors in stdout.
Why don't you split your command into a function, and use subprocess.Popen() to execute it in a subprocess?
from subprocess import *
def run_sql_query(sql_command, connection_string):
session = Popen(['sqlplus', '-S', connection_string], stdin=PIPE, stdout=PIPE, stderr=PIPE)
session.stdin.write(sql_command)
return session.communicate()
Then you can pass your connection string and command as arguments to your function:
con_str = 'xxx.hostname.xxx',port=22, username=user, password=psswd'
cmd = ''export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib sudo -S -H /apollo/env/envImprovement/bin/sqlplus'
print(run_sql_query(con_str, cmd))
This question already has answers here:
AppleScript: how to get the current directory of the topmost Terminal
(3 answers)
Closed 8 years ago.
Is there a way in Python, subprocessing Bash and/or AppleScript, for me to get the current working directory of the frontmost Terminal.app tab and window in OSX?
I've tried the solution in AppleScript: how to get the current directory of the topmost Terminal. It doesn't work in my script.
I use Python to run AppleScript through the following function:
def run(script):
"Returns the result of running string in osascript (Applescript)"
if hasattr(script, "encode"): #Assumes Python 3
script = script.encode("utf-8")
osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
results, err = osa.communicate(script)
if err:
raise Exception(err)
return results.decode("utf-8")
I have tried using the suggested answer through the following call:
def getTerminalDir():
script = '''
tell application "Terminal"
do shell script "lsof -a -p `lsof -a -c bash -u $USER -d 0 -n | tail -n +2 | awk '{if($NF==\"" & (tty of front tab of front window) & "\"){print $2}}'` -d cwd -n | tail -n +2 | awk '{print $NF}'"
end tell
'''
result = run(script)
return result
When I do that, I get the following error:
Exception: 126:127: syntax error: Expected end of line but found “"”. (-2741)
You can try something like:
tell application "Terminal"
if not (exists window 1) then reopen
activate
do script "pwd" in selected tab of window 1
set tabContents to contents of selected tab of window 1
end tell
set myPath to paragraph -2 of (do shell script "grep . <<< " & quoted form of tabContents)
Got it. Thanks for the useful AppleScript insights that helped lead to this solution, Zero.
from subprocess import Popen, PIPE, check_output, STDOUT
def runAppleScript(script):
"Returns the result of running string in osascript (Applescript)"
if hasattr(script, "encode"): #Assumes Python 3
script = script.encode("utf-8")
osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
results, err = osa.communicate(script)
if err:
raise Exception(err)
return results.decode("utf-8")
def runBash(command):
output = check_output(command, stderr=STDOUT, shell=True)
return output
def getCurrentTerminalTTYS():
script = '''
tell application "Terminal"
return (tty of selected tab of front window)
end tell
'''
result = runAppleScript(script)
return result.strip()
def getPathForTTYS(ttys):
lsof = runBash('lsof').split('\n')
process = None
for line in lsof:
if ttys in line:
process = line.split()[1]
break
path = None
for line in lsof:
if 'cwd' in line and process in line:
path = ' '.join(line.split()[8:])
break
return path
def getCurrentTerminalPath():
ttys = getCurrentTerminalTTYS()
return getPathForTTYS(ttys)
This can be stored as a string using
path = getCurrentTerminalPath()