5

I want to execute a linux command that returns the currently logged on user in linux.

Using jQuery and ajax, passing this command to the PHP, which will receive and execute this command using exec() function. The value should be stored and returned.

Upon returning, jquery ajax should return it to a contents of a span tag.

How can this be achieved?

user478636
  • 3,304
  • 15
  • 49
  • 76
  • 3
    What do you mean by "the" currently logged in user? There might be 50 users logged in, or there might be none. If you're talking about the user that's running the Apache process: that's defined in the Apache config file, and it usually never changes, so you shouldn't need to go to all that trouble to determine this. – Mike Baranczak Apr 18 '11 at 15:44
  • good point...but this is for learning purposes....no practical side of this – user478636 Apr 18 '11 at 16:08

2 Answers2

8

Use .load(). Something like this:

JavaScript

$('#my-span-id').load('/path/to/page.php');

PHP

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    If you are using Apache , `whoami` will certainly display 'www-data' which is the user who controls Apache by default. the `who` command will return logged users, and `who -a` will provide more informations. – Marc Bouvier Apr 18 '11 at 15:46
  • That is a fair point; I was going more for a rough skeleton rather than the exact code to use (I've never written a single line of PHP outside of Stack Overflow). – Matt Ball Apr 18 '11 at 15:56
  • do i have to create a separate php file for this or can i use it with my existing one, (which is used to run linux commands and return the output) – user478636 Apr 18 '11 at 16:01
  • You can use an existing page... Change the AJAX to page.php?command=who -- then in PHP check if $_GET['command']=="who" { exec(); } – David Houde Apr 18 '11 at 16:11
  • ...or just use a separate PHP page. It really doesn't make a difference. – Matt Ball Apr 18 '11 at 16:13
1

This javascript sample run a tail command using node.js

#!/usr/bin/env node

var readline = require('readline');
var cp = require('child_process');
var tail = cp.spawn('tail', ['-500', 'mylogfile.log']);
var lineReader = readline.createInterface(tail.stdout, tail.stdin);

lineReader.on('line', function(line) {
    console.log('Line: ' + line);
});

tail.on('close', function(code, signal) {
    console.log('ls finished...');
});

Reference Tutorial

Sagar Naliyapara
  • 3,971
  • 5
  • 41
  • 61
Juanma
  • 11
  • 1