Wednesday, August 26, 2020

PHP Shell Exec

Prerequisite:

# Remote ssh command: Install sshpass first and copy the known_hosts file that belongs to the sysad user (/home/sysad/.ssh/known_hosts to the /var/www/.ssh/known_hosts.  Take note that the password is in single quote or it will error with permission denied.
# Add the sysad user to the /etc/group
  • adm:x:4:administrator,syslog,sysad
# Add to the last line of the sudoers file: sudo visudo
  • sysad ALL=(ALL) NOPASSWD: ALL

PHP file: test.php

<?php
$output = shell_exec("./whoami.sh 2>&1");
echo "<pre>$output</pre>";
?>
Note: must require the 2>&1 for the shell_exec to work on commands considered external.

Shell Script: whoami.sh
Content:

#!/bin/bash
whoami
sshpass -p 'password' ssh -o StrictHostKeyChecking=no -T sysad@serverIP 'ls'

Make executable
chmod +x whoami.sh