Help:PGAdmin4 with python
PGADMIN4 ON UBUNTU 16.04
=== 1. Install
2. Allow Remote Access
3. Run as a Service
4. Access PGAdmin 4
5. Enable Postgresql remote Access
===
1. Install dependencies, create a virtual environment, download, install & configure Using Python2.x sudo apt-get install virtualenv python-pip libpq-dev python-dev
cd virtualenv pgadmin4 cd pgadmin4 source bin/activate
pip install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.1/pip/pgadmin4-2.1-py2.py3-none-any.whl Using Python3.x (Preferred to avoid encoding related issues) sudo apt-get install virtualenv python3-pip libpq-dev python3-dev
cd virtualenv -p python3 pgadmin4 cd pgadmin4 source bin/activate
pip3 install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.1/pip/pgadmin4-2.1-py2.py3-none-any.whl Configure Override default paths and set it to single-user mode in the local configuration file: nano lib/python2.7/site-packages/pgadmin4/config_local.py For Python3.x: nano lib/python3.x/site-packages/pgadmin4/config_local.py Write: import os DATA_DIR = os.path.realpath(os.path.expanduser(u'~/.pgadmin/')) LOG_FILE = os.path.join(DATA_DIR, 'pgadmin4.log') SQLITE_PATH = os.path.join(DATA_DIR, 'pgadmin4.db') SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions') STORAGE_DIR = os.path.join(DATA_DIR, 'storage') SERVER_MODE = False Run python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py For Python3.x: python3 lib/python3.x/site-packages/pgadmin4/pgAdmin4.py Access Access at http://localhost:5050 Exit Exit with Ctrl-C Run again cd ~/pgadmin4 source bin/activate python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py For Python3.x
- !/bin/bash
cd ~/pgadmin4 source bin/activate python3 lib/python3.x/site-packages/pgadmin4/pgAdmin4.py Make a shortcut touch ~/pgadmin4/pgadmin4 chmod +x ~/pgadmin4/pgadmin4 nano ~/pgadmin4/pgadmin4 Write:
- !/bin/bash
cd ~/pgadmin4 source bin/activate python lib/python2.7/site-packages/pgadmin4/pgAdmin4.py For Python3.x
- !/bin/bash
cd ~/pgadmin4 source bin/activate python3 lib/python3.x/site-packages/pgadmin4/pgAdmin4.py Now you can just run it with a simpler command: ~/pgadmin4/pgadmin4 Python3 users Replace [x] in Python3.x with your respective version. Conflict with pgAdmin 3 configuration pgAdmin 4 will not start in the environment where pgAdmin 3 was previously installed and used because of incompatible configuration in the .pgadmin directory. The simplest solution is to either clear that directory or tweak config_local.py to point to a clean new .pgadmin4directory.
2. REMOTE ACCESS (For CLOUD Install) PGAdmin4 Folder: ~/pgadmin4/lib/python3.X/site-packages/pgadmin4 (Replace 3.X with your Python Version) You need to add below config options, DEFAULT_SERVER = '0.0.0.0' in config_local.py (in "pgAdmin4" folder). If also want to change default port then also add DEFAULT_SERVER_PORT = 5050
3. RUN as a Service
Python file: ~/pgadmin4/lib/python3.x/site-packages/pgadmin4/pgAdmin4.py
PGAdmin4 Folder: ~/pgadmin4/lib/python3.X/site-packages/pgadmin4
(Replace 3.X with your Python Version)
Before we start let’s exit the virtual enviroment using the follwoing command:
- deactivate
– To make PgAdmin 4 we need to make some extra modification, Open the pgAdmin4.py file and insert the following line in the begin of the file:
- vi ~/pgadmin4/lib/python3.x/site-packages/pgadmin4/pgAdmin4.py
- !/usr/bin/env python3
[...] – Make it executable by doing:
- chmod +x ~/pgadmin4/lib/python3.x/site-packages/pgadmin4/pgAdmin4.py
– Now create a /etc/systemd/system/pgadmin4.service service file containing:
- vi /etc/systemd/system/pgadmin4.service
[Unit] Description=Pgadmin4 Service After=network.target
[Service] User=root Group=root
- Point to the virtual environment directory
WorkingDirectory=/root/pgadmin4
- Point to the bin folder of your virtual environment
- Environment="PATH=/home/qgis/Downloads/pgadmin4/bin"
Environment="PATH=/root/pgadmin4/bin"
- ExecStart=/home/qgis/Downloads/pgadmin4/bin/python /home/web/Downloads/pgadmin4/lib/python3.6/site-packages/pgadmin4/pgAdmin4.py
ExecStart="/root/pgadmin4/lib/python3.5/site-packages/pgadmin4/pgAdmin4.py" PrivateTmp=true
[Install] WantedBy=multi-user.target – Enable and start PgAdmin Service at system boot:
- sudo systemctl daemon-reload
- sudo systemctl enable pgadmin4
- sudo systemctl start pgadmin4
- sudo systemctl status pgadmin4
4. Access PGAdmin 4 – Open http://Server_ip:5050 and logon to the PgAdmin using your credentials.
5. Enable Postgresql Remote Access.
5.1. Permitir conexiones de clientes desde un determinado rango Llegamos a uno de los puntos importantes de la cuestión, el fichero pg_hba.conf. Su situación exacta dependerá de vuestra instalación, pero lo encontraréis en una de estas dos rutas: /var/lib/pgsql/data/pg_hba.conf (en mi instalación lo tengo ahí, utilizo Scientific Linux, una distribución derivada de Red Hat) /etc/postgresql/main/pg_hba.conf Dentro de este fichero, al final del mismo, veremos algo así: 1 2 3 4 5 6 7 8 # TYPE DATABASE USER CIDR-ADDRESS METHOD
- "local" is for Unix domain socket connections only
local all all ident
- IPv4 local connections:
host all all 127.0.0.1/32 ident
- IPv6 local connections:
host all all ::1/128 password ¿Qué significa esto? Veamos columna a columna: Tipo: básicamente conexión local o conexión remota (host). Base de datos: base de datos a las que afecta la regla. Si queremos todas, usamos el comodín all. Usuario: usuarios a los que afecta la regla, si queremos que afecte a todos, usamos también all. Nos paramos ahora en los dos apartados que más atención requieren. 5.2. Dirección En esta columna definimos, las direcciones IP (podemos también usar IPv6), desde las que podremos conectarnos a PostgreSQL. Usaremos la fórmula dirección/máscara: Una sola dirección: 150.100.100.100/32 O un rango (ampliemos el mismo de antes): 150.100.100.0/24 (256 direcciones) 5.3. Método Aunque hay multitud de métodos para utilizar (incluyendo conexiones LDAP, Kerberos o PAM), explico los tres más básicos: ident: utiliza el usuario del sistema desde el que se está intentado conectar. trust: deja todos los accesos sin necesidad de autenticarse (sólo recomendable para conexiones desde el equipo local). password: identificación con usuario/contraseña, es la más típica y es la recomendable para conexiones desde clientes como EMS PostgreSQL Manager. Una línea de ejemplo, para darle acceso a todos los usuarios, a todas las base de datos, desde el rango de IP explicado antes, usando autenticación con usuario y contraseña, sería la siguiente: 1 host all all 150.100.100.0/24 password 5.4. Habilitar conexiones al socket desde clientes que no sean el host local Al igual que en MySQL hay que configurar el bind-adress en my.conf, en PostgreSQL tenemos que hacer algo análogo. Para versiones 8.x en adelante el procedimiento es el siguiente. Buscamos el ficheropostgresql.conf en: /var/lib/pgsql/data/postgresql.conf /etc/postgresql/8.2/main/postgresql.conf Y buscar dentro del mismo la siguiente línea: 1 listen_addresses='localhost' Para sustituirla, por el comodín (para todas las IP, es una opción segura, tened en cuenta que tenemos también un filtro en el fichero pg_hba.conf. 1 listen_addresses='*' O definir algunas direcciones IP en concreto: 1 listen_addresses='150.100.100.100 150.100.100.101' 5.5. Reiniciar servicio Reiniciamos el servicio para que el servidor cargue los nuevos valores (como root): 1 $ service postgresql restart
