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?

2
  • 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. Commented Apr 18, 2011 at 15:44
  • good point...but this is for learning purposes....no practical side of this Commented Apr 18, 2011 at 16:08

2 Answers 2

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');
?>
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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).
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)
You can use an existing page... Change the AJAX to page.php?command=who -- then in PHP check if $_GET['command']=="who" { exec(); }
...or just use a separate PHP page. It really doesn't make a difference.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.