简体   繁体   中英

Executing a python script from PHP to open a socket

I have a python script chatserver.py that includes:-

#!/usr/bin/python
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
<SNIP>
reactor.listenTCP(3800, factory)
print "Server Started"
reactor.run()

This opens a socket on port 3800 which works if I start from SSH but I want to do a check for the open port and if it is closed reopen using PHP but I cannot seem to get the python script to execute.

Here is how I am calling it via PHP at the moment

function serverCheck() {
   $host = "MYHOST";
   $port = 3800;
   $connection = @fsockopen($host, $port);

   if ( !is_resource($connection) ) { // port not open
       exec('/usr/bin/python PATH_TO_FILE/chatserver.py 2>&1');

    if($connection)
       fclose($connection);
}

I have tried a lot of things I have found on my searches but I just cannot seem to get the file to execute.

Looks like a permission issue. chatserver.py as it stands needs root user to run it.

Don't just chmod 777 chatserver.py . That is dangerous.

The way I like is to create a group for these administrative tasks:

groupadd chatserver

Then add yourself to that group:

usermod -a -G chatserver willroberts

Then change chatserver.py to be owned by that group:

chown root:chatserver chatserver.py

When php is run by your user, it will have the correct group membership to run the py file. This method allows more flexibility for more "chatserver" executables. Here's more reading if you're interested: https://wiki.archlinux.org/index.php/Users_and_Groups and http://www.tldp.org/LDP/intro-linux/html/sect_03_04.html

Problem is fixed :)

It was the shebang in the end :| I know.... I feel stupid!

It should have been #!/usr/bin/python but for some reason I had changed it thorugh various testing of things!

Thank you for your help in this. much appreciated!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM