Log in postgres linux

How to login and authenticate to Postgresql after a fresh install?

There are two methods you can use. Both require creating a user and a database.

By default psql connects to the database with the same name as the user. So there is a convention to make that the «user’s database». And there is no reason to break that convention if your user only needs one database. We’ll be using mydatabase as the example database name.

    Using createuser and createdb, we can be explicit about the database name,

$ sudo -u postgres createuser -s $USER $ createdb mydatabase $ psql -d mydatabase 

You should probably be omitting that entirely and letting all the commands default to the user’s name instead.

$ sudo -u postgres createuser -s $USER $ createdb $ psql 
$ sudo -u postgres psql postgres 
CREATE ROLE myuser LOGIN PASSWORD 'mypass'; CREATE DATABASE mydatabase WITH OWNER = myuser; 
$ psql -h localhost -d mydatabase -U myuser -p
$ grep "port log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  
  • It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  • By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.
  • )" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
    )" title="">Improve this answer
    )">edited Apr 17, 2019 at 13:04
    answered Jan 31, 2010 at 17:24
    5
    • I understand that the problems do not occur if using a DB super user (-s) instead of a non-super user. Next question for me would be, what can be done do get this running even the DB user is not a super user.
      – Hartmut Pfarr
      Mar 16, 2013 at 16:09
    • 1
      In my case, after creating the user with: $ sudo -u postgres createuser -s $USER, I needed to configure a Password with: ALTER USER myuser WITH PASSWORD 'mypass'; ( after logged in postgres with: sudo -u postgres psql )
      – JeanCarlos Chavarria
      Apr 29, 2018 at 14:13
    • How should I understand the command sudo -u postgres psql postgres? I understand sudo means root privilege, -u postgres means log in as user postgres, psql is the command to connect to postgresql, but what's the last postgres doing ?
      – yuqli
      Dec 29, 2018 at 15:22
    • Is this really making it the user's database? logging in as the user, I did show config_file and show data_directory and apparently the data_directory still belongs to user postgres..
      – stucash
      Dec 13, 2022 at 12:44
    • I'm kind of lost why under linux postgres would put data directory under /root by default; database is of arbitrary usage, all sorts of data could go into a database and that's almost surely user action, not root action.
      – stucash
      Dec 13, 2022 at 12:51
    Add a comment|
    57

    by default you would need to use the postgres user:

    sudo -u postgres psql postgres

    Источник

    Работаем с PostgreSQL через командную строку в Linux

    Для подключения к базе данных PostgreSQL понадобится установленный PostgreSQL клиент:

    sudo apt install postgresql-client-

    sudo apt install postgresql-client-12

    Для установки PostgreSQL сервера:

    sudo apt install postgresql

    Проверим, можем ли мы подключиться к базе данных PostgreSQL:

    sudo -u postgres psql -c "SELECT version();"

    Вывод команды должен быть примерно таким:

    $ sudo -u postgres psql -c "SELECT version();" version ---------------------------------------------------------------------------------------------------------------------------------------- PostgreSQL 10.10 (Ubuntu 10.10-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit (1 row)

    PostgreSQL Подключение, Пользователи (Роли) и Базы Данных

    Логин в только что установленный postgreSQL сервер нужно производить под именем пользователя postgres:

    Для подключения к базе данных PostgreSQL можно использовать команду:

    Если такая команда не просит ввести пароль пользователя, то можно еще добавить опцию -W.

    $ psql -Usrv161924_dom -hpgsql-161924.srv.hoster.ru -dsrv161924_dom -W Password for user srv161924_dom:

    После ввода пароля и успешного подключения к базе данных PostgreSQL, можно посылать SQL-запросы и psql-команды.

    PostgreSQL создание новой роли и базы данных

    Создать новую роль c именем admin (указывайте нужное имя):

    sudo su - postgres -c "createuser admin"

    Создание новой базы данных:

    sudo su - postgres -c "createdb testDb"

    Дать права роли на базу данных:

    grant all privileges on database testDb to admin;

    Включить удаленный PostgreSQL доступ для пользователей

    Нам нужно отредактировать файл /etc/postgresql//main/pg_hba.conf, задав опцию md5 вместо peer.

    sudo vim /etc/postgresql/12/main/pg_hba.conf

    После этого сделать restart PostgreSQL:

    sudo service postgresql restart

    Полезные команды PostgreSQL

    Выйти из клиента PostgreSQL:

    Показать список баз данных PostgreSQL:

    Показать список пользователей (ролей):

    Показать структуру таблицы:

    Переименовать базу данных:

    ALTER DATABASE db RENAME TO newdb;

    Изменить текущую базу данных в PostgreSQL (вы не сможете переименовать или удалить текущую базу данных):

    \connect db_name или более короткий alias: \c db_name

    Удалить роль (пользователя):

    Роль не будет удалена, если у нее есть привелегии - возникнет ошибка ERROR: role cannot be dropped because some objects depend on it .

    Нужно удалить привелегии у роли, например если нужно удалить роль admin2, нужно выполнить последовательность комманд с Drop Owned:

    db=# REASSIGN OWNED BY admin2 TO postgres; REASSIGN OWNED db=# DROP OWNED BY admin2; DROP OWNED db=# drop role admin2; DROP ROLE

    Дать права пользователю/роли на логин ( role is not permitted to log in ):

    ALTER ROLE admin2 WITH login;

    Выбор shema psql в консоли:

    Посмотреть список всех схем:

    Подключиться к конкретной схеме:

    SET search_path TO schema_name

    Sequences

    Получить имена всех созданных sequences:

    select relname from pg_class where relkind='S';

    Получить последнее значение sequence, которые будет присвоено новой вставляемой в таблицу записи:

    SELECT last_value FROM order_id_seq;

    Источник

    How to Connect to a PostgreSQL Database From Command Line in Linux

    PostgreSQL is an open source relational database management system.

    Psql is an interactive terminal program for working with PostgreSQL. Use psql to edit, automate, and execute queries in PostgreSQL.

    pgAdmin is a web interface for managing PostgreSQL databases. It provides a visual, user-friendly environment with a host of practical solutions that make managing databases easy.

    In this tutorial, you will learn how to connect to PostgreSQL from the command line using psql or pgAdmin.

    connect to a postgresql database

    • This guide assumes that you have already installed PostgreSQL and created a database you want to access.
    • Access to a command-line/terminal window
    • Sudo or root privileges
    • pgAdmin 4 installed

    How to Connect to PostgreSQL Using psql

    Installing PostgreSQL creates a default database and user account, both called ‘postgres.’

    To log into the ‘postgres’ user account type the following command in the terminal:

    This example shows the command in a Debian-based distribution, Ubuntu.

    Log in to Postgre with single command.

    For the same result on a Red Hatbased system, (e.g., Centos and Fedora) use any of the following commands:

    These commands open a bash shell and give the user ‘postgres’ root privileges within that shell.

    The same command applies if you have already created a different user and a corresponding database with the same name. If a user called ‘test1’, that role will attempt to connect to a database called ‘test1’ by default.

    Note: Check out our in-depth article on different ways to create a Postgres user.

    To begin using psql, enter the command:

    The following screen confirms you are now able to edit and execute queries in PostgreSQL.

    psql-comand-terminal-program-postgres

    PostgreSQL can support and maintain a large number of databases and users simultaneously. Once you log in, it is easy to confirm the current connection and user information.

    Command to get information about your postgre connection.

    The output helps to determine which user and database you are currently interacting with.

    How to Access psql Directly Using sudo

    It is possible to connect with PostgreSQL directly and bypass the intermediary bash shell.

    If you are sure that all the components of your databases and users are correctly configured, you can log into psql directly:

    The -u (user) option causes sudo to run the specified command as a user other than root. As with the previous method, you can now work with databases by executing queries.

    How to Access PostgreSQL With pgAdmin

    The pgAdmin is a graphical tool for managing PostgreSQL databases. After installing and configuring the latest browser version of pgAdmin 4, you need to create an initial pgAdmin user account.

    The basic setup requires an email and a password to authenticate access to the web interface.

    python /usr/lib/python2.7/site-packages/pgadmin4-web/setup.py

    Once the email and password are defined, access the pgAdmin4 interface by using:

    To authenticate, use the email address and password created previously. Once the user interface loads, add a PostgreSQL server by navigating to Servers > Create > Server.

    How to access postgre using PGAdmin 3.

    The General and Connection tabs allow you to enter values for your server name and database user credentials.

    How to create new server with PgAdmin3.

    The Hostname/address is the location of the machine where the PostgreSQL server is running. A connection with your user account is established once you save the information entered. The interface presents an overview of the databases that your user account has access to.

    To enter and execute queries, click Tools > Query Tool or press ALT+Shift+Q within the current database.

    query tool to enter and execute queries

    This article provided two (2) simple solutions on how to connect to a PostgreSQL database.

    If you are looking for a terminal-based solution, psql is an excellent choice for speed and effectiveness.

    The GUI based pgAdmin provides a secure, user-friendly way to log in, administer, and shape databases to fit your requirements. A graphical interface can be indispensable when working on a host of databases simultaneously.

    Источник

    Читайте также:  Linux прокси сервер ubuntu
    Оцените статью
    Adblock
    detector