Wednesday, April 18, 2012

PHP usergroup parser (/etc/group)

Either I'm too lazy to have searched for an existing method, or there isn't one.

So long as your system isn't confined by open_basedir or something like that, this should work. Personally, I need this to get the names of the groups by their numeric ID without having to use a bunch of calls to filegroup() or by using DirectoryIterator::getGroup, although now that I take a closer look at the latter it seems like a better and better idea. Originally, I was going to use stat() and parse the results from what my script finds in /etc/group.

I might still use this for something or other, or perhaps not. Either way, here it is for your using and viewing pleasure.

The script will read the contents of /etc/group and return an array where the keys are the user group names and the value is their numeric id. That's just how I whipped it up though it would probably make more sense to have it the other way around.
<?php

$g = file_get_contents('/etc/group');

$g = explode("\n", $g);
$c = count($g) - 1;

$groups = array();
$x = 0;
foreach ($g as $row) {
  if ($x === $c) {break;}
    $row = explode(':', $row);
    $groups[$row[0]] = intval($row[2]);
    $x++;
  }

echo json_encode($groups);
?>

Sunday, April 15, 2012

Change MySQL root password

After initially installing MySQL on any platform your root user usually has no password. To set it from the command line issue the command:

# mysqladmin -u root password NEWPASSWORD


That's pretty basic stuff, but what if you get locked out of your server from having a typo in the password set, forgetting the password, etc, etc?

First, you need to stop the mysql daemon from running.
Then start the daemon again without the grant tables (the tables containing permissions and user data), and if you are on a live server, you may want to start it without networking since without the grant tables ANYONE can access ANY database from ANYWHERE.

Note: If you are running as root user on your system you will need to add the --user=USER argument to the following command, where user is the user that mysqld will run as (usually mysql)

# mysqld --skip-grant-tables --skip-networking [--user=mysql] &


Now you can log in to mysql without a password or user:

# mysql


Now you just need to update the root user password using mysql:

mysql> UPDATE mysql.user SET Password=PASSWORD('NewPass') WHERE User='root';


Then flush the privileges table:

mysql> FLUSH PRIVILEGES;


After that is done, you need to stop mysqld and restart it normally. You will now be able to gain access to the root user with the password you have set.