Thursday, January 28, 2016

how to connect an apache cgi-script to postgreql database

How do I connect to a local postgres database without password from a script within Apache
up vote 0 down vote favorite

I have a Python script that should load some data into postgres when a POST request is sent to Apache Webserver. In the script a system user (dbuser) is used to connect to the database (which works fine with psql). The script however cannot connect when it is executed within Apache, returning the following error:

Peer authentication failed for user dbuser

Is there a way to allow the script to connect without providing it the user password?
python apache postgresql cgi
shareimprove this question
asked Jun 4 '15 at 9:48
add a comment
1 Answer
active oldest votes
up vote 1 down vote

The solution I've found uses ident authentication with user maps.

The first thing to notice is that, although an username is provided in the script, when connecting via Apache, that user is used for peer authentication (which fails, requiring a password). However, the system user requesting access to postgresql is the one running Apache (namely www-data), thus enabling us to configure an user map, allowing is to authenticate to the server as another system user (thus leveraging ident authentication). Here follows the configuration files content:

In pg_ident.conf we configure the user map:

web            www-data                dbuser
web            dbuser                  dbuser

In pg_hba.conf we add the map as an option to the local peer authentication:

# "local" is for Unix domain socket connections only
local   all          all                 peer map=web

After reloading the server, the script can access the database as if it was executed directly the the user "dbuser", without the need for a password.
shareimprove this answer

Saturday, January 2, 2016

too many files in directory need to split into subdirectories with 100 files

#!/usr/bin/perl -w
use strict;
use File::Copy;
my $fn;
my @total= (1 .. 100);
my $dir = shift;
opendir (my $dh , $dir);

my @files = grep { $_ ne '.' && $_ ne '..' } readdir $dh;

my @letters = ("a".."z") ;

foreach my $let1 ( @letters ) {
    foreach my $let2 (@letters)   {
       mkdir "$dir$let1$let2";

for my $count (@total) {
$fn =  pop  @files;
if ( $fn ) {
  move ("$dir/$fn", "$dir$let1$let2/$fn");
} else  {
    last MYLOOPS;
} }}