Category Archives: Bash

PHP function to remotely run command as root (su)

I rewrote this from somewhere and ended up not needing it, but in case I need it in the future, here it is.

The function ssh to the remote server, issues a su and then runs the command, returning true or false depending on the return code.

function RunRemoteAsRoot($ip, $username, $password, $rootPassword, $commandString)
{
	$connection = ssh2_connect($ip, 22);
	if (!$connection)
		return false;

	if (!ssh2_auth_password($connection, $username, $password))
		return false;

	$stream = ssh2_shell($connection, "vanilla", null, 200);
	if ($stream === false)
		return false;

	stream_set_blocking($stream, true);

	if (fputs($stream, "su -\n") === false)
	{
		fclose($stream);
		return false;
	}

	$line = "";
	$output = "";
	$returnCode = 1;
	while (($char = fgetc($stream)) !== false)
	{
		$line .= $char;
		if ($char != "\n")
		{
			if (preg_match("/Password:/", $line))
			{
				// Password prompt.
				if (fputs($stream, "{$rootPassword}\n{$commandString}\necho [end] $?\n") === false)
				{
					return false;
				}
				$line = "";
			}
			else if (preg_match("/incorrect/", $line))
			{
				//Incorrect root password
				return false;
			}
		}
		else
		{
			$output .= $line;
			if (preg_match("/\[end\]\s*([0-9]+)/", $line, $matches))
			{
				// End of command detected.
				$returnCode = $matches[1];
				break;
			}
			$line = "";
		}
	}
	fclose($stream);

	return ($returnCode == 0);
}

Altering creation dates in image exif data

Whilst attempting to get a Kodak digital photo frame to display the photos in the correct order, I worked out how to set the creation dates to a sequential order (don’t ask).

First, install ExifTool.

Then run something like this (copy it to a file, e.g. renameFile.sh, then run renameFile.sh whilst in a directory of files to alter):

a=1
for i in *; do
	touch i
	new=$(printf "%04d.jpg" ${a}) #04 pad to length of 4
	if [ "${i}" != "${new}" ]; then
		mv ${i} ${new}
	fi

	minutes=$(( $a * 60 ))

	timeString=$(echo $minutes | awk '{printf("%s", strftime("%H:%M:%S", $1));}';)
	exiftool "-FileModifyDate=2012:03:09 $timeString" \
	"-ModifyDate=2012:03:09 $timeString" \
	"-DateTimeOriginal=2012:03:09 $timeString" \
	"-CreateDate=2012:03:09 $timeString" \
	"-DateTimeDigitized=2012:03:09 $timeString" \
	"-MetadataDate=2012:03:09 $timeString" ${new}

	let a=a+1
done

It was more complicated than it should have been, and I think there may be a bug somewhere in it.

The code just sets the time of the various dates in the exif data to a value based on the file number.  It also names the files in a sequential order.