Screen -X isn't working (“No screen found”)

后端 未结 2 439
抹茶落季
抹茶落季 2020-12-12 03:28

I have this php code:

echo shell_exec(\'sh /backups/turnon.sh\');

The /backups/turnon.sh code is:

scree

2条回答
  •  无人及你
    2020-12-12 03:45

    Not sure why one would do this, but as a sample of one way to do it.


    www-data

    One way to solve this case would be to attach to correct user session. For Apache that is normally www-data which is a user with stripped down privileges. Use ps on apache or,

    in PHP you can run this to show you which user PHP (Apache) run as:

    
    

    Output:

    www-data
    

    Note that if you run the script using PHP from command-line you will get current user, which you do not want.


    Initiate screen session for www-data

    www-data is normally not set up with password, as such we cannot log in with that user. To run a screen session for www-data one can do the following:

    $ sudo su - www-data
    $ script /dev/null
    $ screen
    

    Or as a one-liner:

    sudo su - www-data -c 'script -c screen /dev/null'
    

    This will start a new shell in www-data's home directory, typically /var/www/. The script command is one way to prevent access error to terminal when running screen due to the use of sudo su.


    Execute script from PHP

    Now that we have a screen session for www-data we can continue with the Bash script.

    /usr/bin/screen -X stuff '/usr/bin/java -cp /some/path/ Test
    
    '
    

    and execute it from PHP.


    Capturing output

    If you want the buffer from screen in PHP there is various ways:

    First create a log-file for www-data's screen session.

    touch /tmp/www-data-scr.log
    chown www-data:www-data /tmp/www-data-scr.log
    
    • Use logfile option in .screenrc and run screen with -L.

    • Run script -f /tmp/www-data-scr.log inside screen.

    • Start www-data script screen session with log-file, -f to flush.

        sudo su - www-data -c 'script -fc screen /tmp/www-data-scr.log'
      
    • Copy buffer to file to get a snapshot.

        /usr/bin/screen -X hardcopy /tmp/www-data-scr.log
      
    • etc.

    You would typically add a

    sleep N
    

    in your bash script after issuing the command producing some output and before reading the log file.


    To sum up

    As privileged user:

    touch /tmp/screen.log
    sudo chown www-data:www-data /tmp/screen.log
    sudo su - www-data -c 'script -c screen /dev/null'
    

    Bash script:

    #!/bin/bash
    
    /usr/bin/screen -X stuff 'java -cp /some/class/path/ Test
    
    '
    sleep 1
    /usr/bin/screen -X hardcopy /tmp/screen.log
    sed '/^$/d' /tmp/screen.log
    

    PHP:

    
    

提交回复
热议问题