in PHP I need to do some SFTP, but I am having issues because I am not allowed to install the SSH extension, and phpseclib is not working how I need it to.
As such, I am going to execute a Python script to do the SFTP for me. What I imaging is doing something like the following
exec("SFTPUpload.py remoteFile serverLocation");
So I execute SFTPUpload.py passing it the location of the file on my server which needs transferring, and the location on the server it needs transferring too.
In terms of the Python script (I am not too familiar with Python), I imagine it would be something like the following
username='sftpUser'
password='sftpPassword'
port=22
#SFTP
client.load_system_host_keys()
print " hostname =%s \n username=%s \n password=%s \n" (hostname,username,password)
t = paramiko.Transport((hostname, port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(source,destination)
sftp.close()
t.close()
However, the way I am calling it from PHP, I need the Python to be in a class or something so I can pass it the variables.
How would I achieve something like this?
Thanks
I believe you can do it with the exec() function as you described by simply parsing the command line parameters in Python.
Like:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Where you can access the elements in sys.argv like a list.
(You could also take a look at the getopt module which offers even more (C-like) parameter passing options, but I believe the above solution will do.)
If the exec() function does not work, I believe you could consider to use the system function in PHP:
Something like this:
$mystring = system('SFTPUpload.py remoteFile serverLocation', $retval);
Related
I have a python script (analyze.py) which takes a filename as a parameter and analyzes it. When it is done with analysis, it waits for another file name. What I want to do is:
Send file name as a parameter from PHP to Python.
Run analyze.py in the background as a daemon with the filename that came from PHP.
I can post the parameter from PHP as a command line argument to Python but I cannot send parameter to python script that already runs at the background.
Any ideas?
The obvious answer here is to either:
Run analyze.py once per filename, instead of running it as a daemon.
Pass analyze.py a whole slew of filenames at startup, instead of passing them one at a time.
But there may be a reason neither obvious answer will work in your case. If so, then you need some form of inter-process communication. There are a few alternatives:
Use the Python script's standard input to pass it data, by writing to it from the (PHP) parent process. (I'm not sure how to do this from PHP, or even if it's possible, but it's pretty simple from Python, sh, and many other languages, so …)
Open a TCP socket, Unix socket, named pipe, anonymous pipe, etc., giving one end to the Python child and keeping the other in the PHP parent. (Note that the first one is really just a special case of this one—under the covers, standard input is basically just an anonymous pipe between the child and parent.)
Open a region of shared memory, or an mmap-ed file, or similar in both parent and child. This probably also requires sharing a semaphore that you can use to build a condition or event, so the child has some way to wait on the next input.
Use some higher-level API that wraps up one of the above—e.g., write the Python child as a simple HTTP service (or JSON-RPC or ZeroMQ or pretty much anything you can find good libraries for in both languages); have the PHP code start that service and make requests as a client.
Here is what I did.
PHP Part:
<?php
$param1 = "filename";
$command = "python analyze.py ";
$command .= " $param1";
$pid = popen( $command,"r");
echo "<body><pre>";
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
}
pclose($pid);
?>
Python Part:
1. I used [JSON-RPC]: https://github.com/gerold-penz/python-jsonrpc to
create a http service that wraps my python script (runs forever)
2. Created a http client that calls the method of http service.
3. Printed the results in json format.
Works like a charm.
I have this small program which takes input from stdin
sample.c
#include<stdio.h>
main()
{
int l=0;
scanf("%d",&l);
printf("\n%d",l);
}
ofcourse! compiled it: cc sample.c and got a.out
and i am trying to run it via php like
$runcmd = "./a.out > output.txt";
exec($runcmd,$outp);
print_r($outp);
my problem is i dont have any idea how to give input to this program so that scanf can read that?
please help me here!
googling gave some tips like proc_open, popen .... but i couldn't make it.
Thanks in Advance.
take a look at popen
http://se1.php.net/popen
it works a bit like fopen, and when using fwrite, insted of writing to a file you can write to a prosses stdin insted.
$runcmd = "./a.out > output.txt";
$process_stdin = popen($runcmd, 'w');
fwrite($process_stdin, "text to send to process");
pclose($process_stdin);
If you design your C program as a server, you should use sockets or named pipe. That way, you will be able to interact with it without launching it.
You can use popen if you want to use it multiple time almong your script.
If you just need to use it one time, you can just pass parameter as arguments.
Why not passing it as a command line argument to your C program. Then instead of using scanf you get your input in argv[].
I am attempting to write a PHP script that will allow for me to select a few files to download from a predetermined location. I'd like my script to pass an array to a Powershell script that id written earlier and have my Powershell script handle the downloading (basically the php file just needs to tell the powershell file what needs to be downloaded).
I've looked at a few options, and it seems that exec is the command I should use for this (as I do not care about command line output I shouldnt need shell_exec).
So far I've turned OFF safe mode to allow me to use this command. I should also note that the php file will be run from a server, however the powershell files are located on a local machine.
A snippet of the code so far to handle the param passing looks like this:
if(isset($_POST['formSubmit']))
{
$choosePlugin = $_POST['wpPlugin'];
$chooseTheme = $_POST['wpTheme'];
if(isset($_POST['wpTheme']))
{
echo("<p>You selected: $chooseTheme</p>\n");
exec('powershell.exe C:\Wordpress Setup\setupThemes.ps1 $chooseTheme');
}
else
{
echo("<p>You did not select a theme</p>\n");
}
I am a bit confused as to what I should put inside the exec. When I run the above code there are no errors however nothing happens. I am a bit new to this so I apologize if more information is required. Any help is appreciated thank you.
Try to do:
echo exec('powershell.exe C:\\Wordpress Setup\\setupThemes.ps1 $chooseTheme');
to see the results of powershell.exe (remember the double \), also make sure to put the absolute path to the exe file:
echo exec('c:\\PATH_TO_POWERSHELL.EXE\\powershell.exe C:\\Wordpress Setup\\setupThemes.ps1 $chooseTheme');
If you want to pass the contents of the variable you should use double quotes to actually expand it, I guess. Furthermore you should quote the script name because the path contains spaces:
exec("powershell.exe \"C:\Wordpress Setup\setupThemes.ps1\" $chooseTheme");
I need to write a script that will give users info on a given Unix account (the same Unix server that the script lives on). Mostly thing kinds of things that are in the passwd file or available via finger.
PHP is in safe-mode, so I can't access the passwd file via something built into php like file_get_contents(). Also, because it's in safe mode, various other command-line functions are disabled.
I thought I could get the info via a socket (no clue yet what that means, but I thought I'd try) but I get a fatal error that socket_create() is an unknown function. I pulled up the php-config file (which I can't change, FYI), and sure enough, sockets are not enabled.
However, while I was in there, I saw the line '--with-exec-dir=' with no actual directory set.
So then I remembered that when I was trying EVERY command line function, that some threw "not allowed in safe-mode" type errors, while others did nothing at all. If I put something like:
echo "[[";
exec("finger user");
echo "]]";
I'd end up with [[]]. So no errors, just no results either.
Bottom line:
Is there something I haven't tried? (in general)
Is there a runtime config option I can set to make exec() work?
quick note: I tried passthru() as well, specifically passthru("pwd") with still no output.
update
based on feedback, I tried both of the following:
$stuff = exec("pwd", $return);
echo "stuff=".$stuff."\n";
echo "return=";
print_r($return);
which results in:
stuff=
return=Array
(
)
and
$stuff = passthru("pwd", $return);
echo "stuff=".$stuff."\n";
echo "return=";
print_r($return);
which results in:
stuff=
return=1
The 1 sounds hopeful, but not what I want yet.
Idea
So this is actually an update of an already existing script that (please don't ask) I don't have access to. It's a perl script that's called via cgi. Is there a way to do php via cgi (so I don't have to deal with perl or rely on the older code)?
I'm afraid you can't do that in safe-mode. You have to remove the safe-mode if you have control of the server configuration.
I think you can't rely on sockets to read local files, sockets are used for network related things.
exec doesn't inherently return any data.
Try something like,
exec("finger user",$output);
echo "[[";
foreach($output as $key => $value){
echo $value;
}
echo "]]";
Exec returns a value, so do:
$var = exec("finger user");
and then parse the output to get what you want. You can get return status by adding in an optional variable thus:
exec("finger user", $var, $return_status);
or just:
echo exec("finger user");
if all you want is to see the output.
Thanks to all that responded, the following is what finally worked:
Create a cgi-bin folder
Add the following to the top of the php script:
#!/usr/local/bin/php-cgi
I don't know if this is something special on my server configuration, but I can run exec() and get what I'm after.
I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.
Any better ideas?
Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like
preg_replace('/[^a-zA-Z0-9]/', '', $str)
The shell_exec() operator will also allow you to run python scripts using similar syntax to above
In a python file called python.py:
hello = "hello"
world = "world"
print hello + " " + world
In a php file called python.php:
$python = shell_exec(python python.py);
echo $python;
You can run a python script via php, and outputs on browser.
Basically you have to call the python script this way:
$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
usleep(100000);
}
pclose($pid);
Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.
For full codes working, visit How to execute python script from php and show output on browser
I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.
Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.
Your call_python_file.php should look like this:
<?php
$item='Everything is awesome!!';
$tmp = exec("py.py $item");
echo $tmp;
?>
This executes the python script and outputs the result to the browser.
While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:
import sys
list1 = ' '.join(sys.argv[1:])
def main():
print list1
if __name__ == '__main__':
main()
The above methods seems to be complex. Use my method as a reference.
I have this two files
run.php
mkdir.py
Here, I've created a html page which contains GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py
is so easy 😁
You can use [phpy - library for php][1]
php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page
[1]: https://github.com/Raeen123/phpy
If you want to execute your Python script in PHP, it's necessary to do this command in your php script:
exec('your script python.py')