3

As I come across issues when testing my current application, I often have to tweak the database the app uses. After losing important changes several times, I wrote a program that will back up my database to a file and then check the file into SubVersion. I have found that that backup application is not good enough.

The database is a PostgreSQL database, and my backup application invokes pg_dump to create the backup file. pg_dump is executed in a console window. When the database was on my own machine, it worked well. But when I moved the database to our test server, pg_dump asked for a password. While it's not that big a deal, I'd like to be able to supply the password automatically, since it is available in the backup application.

I've tried to follow advice I've found here, but pg_dump still stops and asks for a password. Here's the code that I thought should have supplied the password:

Process backupProcess = new Process();
backupProcess.StartInfo.UseShellExecute = false;
backupProcess.StartInfo.RedirectStandardInput = true;
backupProcess.StartInfo.FileName = dumpPath + "pg_dump.exe";
backupProcess.StartInfo.Arguments = " --host " + host + 
                                    " --port " + port + 
                                    " --username " + userName + 
                                    " --format custom --blobs --verbose --file " +
                                    "\"" + txtBackupFile.Text + "\" " + dbName;
backupProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
backupProcess.Start();
StreamWriter standardInput = backupProcess.StandardInput;
standardInput.WriteLine("mypassword");
backupProcess.WaitForExit();// Waits here for the process to exit.

Thank you for your help.

RobR

ROBERT RICHARDSON
  • 2,077
  • 4
  • 24
  • 57

2 Answers2

4

I have solved this by using

backupProcess.EnvironmentVariables["PGPASSWORD"] = "password";

This way, I avoid the password will be stored on the computer

Pavenhimself
  • 527
  • 1
  • 5
  • 18
1

Maybe it's cheating a little bit (in the sense that it doesn't really help you answer the question of how to feed input to pg_dump), but you could refer to this answer which suggests the use of a .pgpass file. It would certainly be possible to write to this file dynamically rather than try to interact with the program once it prompts.

Info on .pgpass here.

Community
  • 1
  • 1
Andrew Flanagan
  • 4,267
  • 3
  • 25
  • 37
  • Many thanks for that link. I'll see about setting up a .pgpass file, or I might use the Python script that answer also suggests. I haven't tried either one yet, but while I'm here I'll mark this as an accpeted answer. – ROBERT RICHARDSON Jan 30 '14 at 19:53
  • It sounds as if automating interaction on the command line (like you might do using the "expect" tool or something similar) in .NET is a little unreliable. By the way, the above program works for me if you write a dummy "pg_dump.exe" that's a .NET program. – Andrew Flanagan Jan 30 '14 at 19:56