- Пароль пользователя postgres — как задать и изменить пароль
- Изменить пароль пользователя Postgres
- How to Set the Default User Password in PostgreSQL
- Login and Connect as Default User
- Authentication Error
- Changing the Password
- What is the Default Password for PostgreSQL?
- default postgres user and password
- 1 Answer 1
- Windows pgAdmin и пароли PostgreSQL
- Решение
Пароль пользователя postgres — как задать и изменить пароль
Команды по администрированию базами и пользователями выполняются от имени системного пользователя postgres
root может стать им выполнив su — postgres
Затем можно без пароля попасть в интерфейс БД psql
Или то же самое одной командой
Пользователь может создать базу
Затем добавить пользователя и задать для него пароль
=# create user appadmin with encrypted password ‘jdfh8jhtghnjkfrvhyu’;
После этого пользователю нужно дать права для работы с базой данных
=# grant all privileges on db1 mydb to appadmin;
Изменить пароль пользователя Postgres
Пользователя можно создавать и задавать ему пароль двумя раздельными командами
sudo -u postgres createuser anotheruser
Вторая служит для изменения паролей уже существующих пользователей, выполняется из консоли psql
=# alter user anotheruser with encrypted password ‘NEW_STRONG_PASSWORD’;
Непосредственно для системного пользователя postgres пароль не нужен, им может стать root выполнив su как показано ранее. Если нужна авторизация root может установить для postgres новый пароль
Затем пароль нужно ввести дважды, отображаться он не будет.
Пользователь appadmin — не системный, он существует только в postgresql.
Подключаться к базе из консоли от имени этого пользователя нужно указывая имя базы и ключ -W
psql -h myhost -d db1 -U appadmin -W
Последний ключ не обязателен, но без него в интерактивном режиме в некоторых версиях СУБД не будет запрашиваться пароль, пароль должен запрашиваться.
Про создание дампов баз данных Postgres и их загрузку.
How to Set the Default User Password in PostgreSQL
Firstly, it is important to understand that for most Unix distributions, the default Postgres user neither requires nor uses a password for authentication. Instead, depending how Postgres was originally installed and what version you are using, the default authentication method will either be ident or peer .
ident authentication uses the operating system’s identification server running at TCP port 113 to verify the user’s credentials.
peer authentication on the other hand, is used for local connections and verifies that the logged in username of the operating system matches the username for the Postgres database.
Login and Connect as Default User
For most systems, the default Postgres user is postgres and a password is not required for authentication. Thus, to add a password, we must first login and connect as the postgres user.
If you successfully connected and are viewing the psql prompt, jump down to the Changing the Password section.
If you received an error stating that the database “postgres” doesn’t exist, try connecting to the template1 database instead and if successful, continue to Changing the Password.
Authentication Error
If you receive an authentication error when attempting to connect to the psql client, you may need to alter the Postgres authentication config file (pg_hfa.conf).
Open the config file, typically located at /etc/postgresql/#.#/main/pg_hba.conf , where #.# is the Postgres version you are using:
The auth config file is a list of authentication rules. Scroll down the file until you locate the first line displaying the postgres user in the third column (if such a line exists). Uncomment the line if necessary (remove the semicolon), or otherwise if the line is missing entirely, add the following line to the top of the file and save your changes:
This authentication rule simply tells Postgres that for local connections established to all databases for the user postgres , authenticate using the peer protocol.
Note: Some older versions of Postgres prefer the default authentication method of ident, but most modern installations will utilize peer as specified above instead. You may need to test both if your results differ.
Now with your configuration file updated, repeat the steps in the Login and Connect as Default User section to try to connect to as the default postgres user. Once successful, proceed with changing the password.
Changing the Password
With a connection now established to Postgres at the psql prompt, issue the ALTER USER command to change the password for the postgres user:
If successful, Postgres will output a confirmation of ALTER ROLE as seen above.
Finally, exit the psql client by using the \q command.
You’re all done. The default postgres user now has a password associated with the account for use in your other applications.
What is the Default Password for PostgreSQL?
When connecting to PostgreSQL on Linux for the first time many admins have questions, especially if those admins are from the MySQL world. By default, when PostgreSQL is installed, a postgres user is also added.
If you run the command:
… you’ll see the postgres user.
The first question many ask is, “What is the default password for the user postgres?” The answer is easy… there isn’t a default password. The default authentication mode for PostgreSQL is set to ident.
… you’ll see the authentication mode is ident.
# IPv4 local connections:
host all all 127.0.0.1/32 ident
# IPv6 local connections:
host all all ::1/128 ident
What is the ident authentication method? Well, it works by taking the OS username you’re operating as and comparing it with the allowed database username(s). There is optional username mapping.
This means that in order to connect to PostgreSQL you must be logged in as the correct OS user. In this case, we are logged into the server as root. When we try to connect to PostgreSQL:
… we get the following error:
psql: FATAL: role «root» does not exist
However, if we become the default PostgreSQL user, postgres:
… then attempt a connection to PostgreSQL:
… I get the correct, valid response!
psql (9.3.9)
Type «help» for help.
Is your Cloud VPS slowing down your PostgreSQL instance? Liquid Web’s Dedicated Servers is the solution. Liquid Web’s server outmatches the competition on performance and support. Check out how our VPS server or Dedicated Servers can skyrocket your site’s performance.
default postgres user and password
I’m just new to postgresql db management. I’ve been playing around with a db that I didn’t create. Trying to understand the different roles that have been created.
Does the fact that I can log in doing the following mean that the postgres user has no password set up?
and I can see that there is a password set. I found this article: http://www.postgresql.org/message-id/4D958A35.8030501@hogranch.com which seeme to confirm that the postgres user is there by default. and you have to explicitly set a password. It’s the second part about the password that I’m not sure about. Is it blank by default or set to something?
I know that if pg_hba.conf is set to trust everything from 127.0.0.1, then you can log in from the local server without specifying a password. That might be what’s happening in my case. i will test by changing the pg_hba.conf file. But it’d be nice to know what the default password is for postgres user.
postgres/.pgpass file as well. – bma Nov 19 ’13 at 21:52
1 Answer 1
pg_roles is not the view that can tell whether a user has a password or not, because the password field is always set to ******** no matter what.
This comes from the definition of this view (taken from version 9.3):
Note how the rolpassword column is hardcoded to reveal nothing (We may wonder why it’s there at all. Maybe for backward compatibility?)
On the other hand , there is a pg_shadow view that displays passwords as they’re stored, in a column named passwd . This view is only readable by a superuser (typically: the postgres user).
Windows pgAdmin и пароли PostgreSQL
Добрый день, подскажите плиииз! Запутался окончательно!
Скачал с оф-сайта и установил Postgres9 на Windows. При установке меня заставили ввести целых 2 пароля. придумал сложные и ввел!
Подключаюсь на этом-же компьютере из pgAdmin (3 и 4 — на обоих пробовал) и успешно вхожу без пароля! вернее с ЛЮБЫМ паролем!
. ищу инструкцию по смене пароля (psql.exe -U postgres + \password), успешно меняю, и опять вхожу в pgAdmin (и 3, и 4) под ЛЮБЫМ паролем!
Что я сделал не так.
. планирую работать с Ps на линуксе, но разобраться с доступами хочу на винде и «графических» редакторах SQL-скриптов
Проблема с pgAdmin при установке PostgreSQL 11
Здравствуйте. Устанавливаю PostgreSQL 11. Сначала всё идёт как положено, установка внешне.
Запрос на вывод из базы PostgreSQL, PgAdmin III)
Здравствуйте, пытаюсь подключиться к базе и получить все данные по запросу, но ничего не.
Пароли в Windows 7
Всем привет. скажу сразу хакер с меня ни какой. Моя проблема- сменил пароль в майле и вскоре.
Разные пароли на wi-fi в Windows 7 и 8
У меня есть роутер (маршрутизатор) Zyxel Keenetic 4G. У него на этикетке крышке написан пин-код для.
Решение
В 1С (бухгалтерская прога) можно базу подключить к постгресу (ожидается дикий прирост скорости по сравнению с не кешированным файловым хранилищем). Обычно все работают в win-терминалах на ЭТОМ-же компе (один приличный сервер на фирму в 10-20 компов). Далеко не каждый 1Сник умеет (и имеет желание) кроме 1С еще и заниматься линуксом.
А я пытался разобраться с принципами «ролей», чтобы понять как на линукс-сервере организовать «разграничение доступов». Хотел потренироваться сначала на локальной базе с «графическим» редактором/вювером pgAdmin и неожиданно «доступ не урезается». к серверной не получилось подключить pgAmdin
Кстати, можете по линукс (debian) версии проконсультировать? Поставил на хостинг постгрес, успешно работаю ИЗНУТРИ (node-сервер на том-же хостинге), но подключиться с домашнего компа на сервер не получается (под теми-же паролем/пользователем/базой/портом, но с реальным IP хоста) — «could not connect to server: Connection refused»!
Это те-же «настройки по дефолту» чтобы снаружи «случайно» не сломали? или у меня где-то руки кривые, а у остальных «работает из коробки»?
пробую разобраться с /etc/postgresql/9.1/main/pg_hba.conf
но пока безуспешно.
скопипастить через терминал не получается. буду набирать:
все остальное заремарено.
где-то на форуме предложили добавить:
после каждой модификации пробовал перегрузить через
То есть вы в операционной системе работаете в каком-то своем окружении под пользователем myuser, даете команду оболочке от имени пользователя postgres запустить команду коннект к базе данных через доменный сокет, который расположен в директории /var/lib/postgresql. Пользователь базы данных будет по умолчанию postgres, база данных, к которой подключаетесь, будет по умолчанию тоже postgres.
2 строчка)
local = понятно
all = понятно
all = разрешает доступ всем пользователям (которые созданы в СУБД командой CREATE ROLE/USER или утилитой createuser)
md5 = разрешает доступ, только если пользователь прошел проверку своего пароля, указанного при соединении с базой данных (то есть обычная проверка по паролю)
Все вместе означает, что эта строчка авторизует коннекты к базе, которые делаются примерно такой командой
В итоге получаем, что Ваш текущий pg_hba.conf разрешает соединения ТОЛЬКО внутри данного сервера всякими разными способами (через unix-сокеты, через tcp/ip v4 и v6).
Чтобы добавить коннект извне (из Интернета) надо добавить примерно следующую строчку
5) строчка
host = понятно
all = понятно
all = понятно
1.2.3.4/24 = IP-адрес и префикс (или плюс маска) того адреса, С КОТОРОГО вы будете соединяться с базой данных (это адрес вашего провайдера). Можно указать 0.0.0.0/0, тогда будет с любого адрес (что может быть НЕБЕЗОПАСНЫМ. ).
Вместе с добавлением этой строчки нужно убедиться, что в файле postgresql.conf
параметры listen_addresses и port выставлены верно
хотя бы так
listen_addresses=’*’
port = 5432
Если я где-то ошибся, верную информацию всегда можно найти в оф. документации
Добавлено через 12 минут
p.s. Да, надо добавить, что ряд команд, которые я выше упомянул имеют свои особенности применения в разных дистрибутивах linux (в частности sudo, работа которой обычно настраивается отдельно). Также иногда psql требует явного указания параметра -W, который однозначно требует ввода пароля пользователя перед процедурой аутентификации.
p.p.s. Также коннекты извне часто ограничиваются файрволами, которые по умолчанию включены в современных дистрибутивах.
p.p.p.s. Также может вмешиваться в работу SELinux, если он поднят по умолчанию (например, CentOS).
Все эти компоненты окружения операционной системы должны быть учтены при поиске проблем подключения к базе данных. Естественно, когда речь идет о сервере на реальном адресе, простое выключение файрволов и прочих служб безопасности чревато разными проблемами в будущем.