Ubuntu环境下Nagios集成check_postgres插件遇Peer认证失败求助
Hey there! I’ve run into this exact issue before, so let’s break down why this is happening and how to fix it quickly.
Why the Error Happens
PostgreSQL’s peer authentication checks if your system username matches the PostgreSQL username you’re trying to connect as. When you run su postgres and execute the plugin, you’re using the postgres system user which maps directly to the default postgres PostgreSQL user—so it works. But Nagios runs all its checks under the nagios system user, which doesn’t have a matching PostgreSQL user or permission to connect via peer auth.
Step-by-Step Fixes
1. Create a PostgreSQL User for Nagios
First, we need a PostgreSQL user that matches the nagios system user:
- Switch to the postgres system user:
su postgres - Create the nagios PostgreSQL user (add
-Pif you want to set a password right away, which we’ll need for password-based auth later):createuser -P nagios - Grant basic connection permissions to the user (adjust based on what checks you need):
psql -c "GRANT CONNECT ON DATABASE postgres TO nagios;"
2. Update PostgreSQL's pg_hba.conf
Next, tell PostgreSQL to allow the nagios user to connect. Open the pg_hba.conf file (location varies by PostgreSQL version, usually /etc/postgresql/<your-version>/main/pg_hba.conf):
sudo nano /etc/postgresql/14/main/pg_hba.conf
Add this line near the top of the local connections section:
local all nagios md5
Note: Using
md5means PostgreSQL will use password authentication. If you strictly want peer auth, ensure thenagiossystem user exists (it should if Nagios is installed) and replacemd5withpeer.
Save the file and restart PostgreSQL to apply changes:
sudo systemctl restart postgresql
3. Configure the Plugin in Nagios
Update your Nagios command definition to use the new nagios PostgreSQL user. For example:
define command { command_name check_postgres command_line $USER1$/check_postgres -U nagios -d postgres }
To avoid hardcoding passwords, create a .pgpass file for the nagios user:
- Switch to the nagios user:
su nagios - Create the file:
nano ~/.pgpass - Add this line (replace
<your-password>with the one you set earlier):localhost:5432:*:nagios:<your-password> - Set strict permissions (required by PostgreSQL):
chmod 600 ~/.pgpass
4. Test the Check
Before reloading Nagios, verify the plugin works as the nagios user:
su nagios /usr/lib/nagios/plugins/check_postgres -U nagios -d postgres
If it returns a normal status (like POSTGRES_CONNECT OK), you’re ready to go.
5. Reload Nagios
Finally, apply the command changes by reloading Nagios:
sudo systemctl reload nagios
That should resolve the peer authentication error! Let me know if you hit any snags.
内容的提问来源于stack exchange,提问作者Mat

