如何在使用psql命令时不弹出“输入用户密码”的提示?

1.问题描述

当我使用psql命令创建数据表时,发生以下问题:

user@ubuntu:~/sharedir$ ./Interface.py
psql -d postgres -U postgres -W 1234 -f /home/user/sharedir/createtable.sql
psql: warning: extra command-line argument "1234" ignored
Password for user postgres: 

程序向我提示需输入系统用户user的登录密码,在我输入密码'user'后程序才得以执行成功,执行结果如下:

CREATE TABLE
CREATE TABLE
CREATE TABLE

由于此数据表创建功能是在python程序中实现的,不应该中途停止以等待输入密码,所以不得不完善方案。

2.方案一

在查阅stackoverflow之后,找到以下几种方案:

You have four choices regarding the password prompt:

  1. set the PGPASSWORD environment variable. For details see the manual:
    PostgreSQL: Documentation: 14: 34.15. Environment Variables
  2. use a .pgpass file to store the password. For details see the manual:
    PostgreSQL: Documentation: 14: 34.16. The Password File
  3. use "trust authentication" for that specific user:
    PostgreSQL: Documentation: 14: 21.3. Authentication Methods
  4. use a connection URI that contains everything:
    PostgreSQL: Documentation: 14: 34.1. Database Connection Control Functions

一个在程序中使用环境的例子如下:

 var processStartInfo = new ProcessStartInfo();
 processStartInfo.UseShellExecute = false;
 processStartInfo.EnvironmentVariables["PGPASSWORD"] = "password";
 Process proc = Process.Start(processStartInfo);

It will work.

3.方案二

同时也有更加简单的方案:

A simple example with PGPASSWORD will be something like:

PGPASSWORD=YOUR_PASSRORD psql -h YOUR_PG_HOST -U YOUR_USER_NAME

这种方案的缺点之一是会在shell命令中暴露用户密码,从而造成安全隐患。

最后,为方便学习,在此也将原文链接贴上:How to use psql with no password prompt?


版权声明:本文为wuyy0224原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。