Check if Postgresql is listening

…衆ロ難τιáo~ 提交于 2020-01-12 18:54:29

问题


Given an IP Address and port number, is it possible to check if the machine with that IP address has Postgresql listening on the specified port? If so, how?

I just want to obtain a boolean value of whether Postgresql is listening on the specified port of the specified machine.


回答1:


I think you need to define what you're trying to achieve better. Do you just want to know if anything is listening on a certain point? If PostgreSQL is listening on a given port? If PostgreSQL is running and actually accepting connections? If you can connect to PostgreSQL, authenticate successfully and issue queries?

One option is to invoke psql to connect to it and check the result code. Do not attempt to parse the output text, since that's subject to translation into different languages.

Better, use the client library for the language of your choice - psycopg2 for Python, PgJDBC for Java, the Pg gem for Ruby, DBD::Pg for Perl, nPgSQL for C#, etc. This is the approach I'd recommend. The SQLSTATE or exception details from any connection error will tell you more about why the connection failed - you'll be able to tell the difference between the server not listening, authentication failure, etc this way. For example, in Python:

import psycopg2
try:
    conn = psycopg2.connect("host=localhost dbname=postgres")
    conn.close();
except psycopg2.OperationalError as ex:
    print("Connection failed: {0}".format(ex))

There are exception details in ex.pgcode (the SQLSTATE) to tell you more about errors that're generated server-side, like authentication failures; it'll be empty for client-side errors.

If you just want to see if something is listening on a given IP and TCP port, you can use netcat (*nix only), or a simple script in the language of your choice that creates a socket and does a connect() then closes the socket if it gets a successful response. For example, the following trivial Python script:

import socket                                                                                                                                                              
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect(('localhost',5432))
    s.close()
except socket.error as ex:
    print("Connection failed with errno {0}: {1}".format(ex.errno, ex.strerror))            

The same approach applies in any programming language, just the details of the socket library and error handling vary.

For some purposes it can also be useful to use the netstat tool to passively list which processes are listening on which network sockets. The built-in netstat on Windows is pretty brain-dead so you have to do more parsing of the output than with netstat for other platforms, but it'll still do the job. The presence of a socket in netstat doesn't mean that connecting to it will succeed, though; if the process has failed in some way that leaves it broken but still running (stuck in an infinite loop, blocked by a debugger, SIGSTOPed, etc) then it won't respond to an actual connection attempt.




回答2:


You can use, for example, nmap tool:

=$ sudo nmap -v -p 5930 127.0.0.1

Starting Nmap 6.00 ( http://nmap.org ) at 2013-06-25 19:28 CEST
Initiating SYN Stealth Scan at 19:28
Scanning localhost (127.0.0.1) [1 port]
Discovered open port 5930/tcp on 127.0.0.1
Completed SYN Stealth Scan at 19:28, 0.03s elapsed (1 total ports)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000045s latency).
PORT     STATE SERVICE
5930/tcp open  unknown

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.08 seconds
           Raw packets sent: 1 (44B) | Rcvd: 2 (88B)

Alternatively you can just "SELECT 1" with psql, and check output:

=$ psql -h 127.0.0.1 -p 5930 -c "select 1"
 ?column? 
----------
        1
(1 row)

=$ psql -h 127.0.0.1 -p 5940 -c "select 1"
psql: could not connect to server: Connection refused
        Is the server running on host "127.0.0.1" and accepting
        TCP/IP connections on port 5940?



回答3:


In brief

In details

Fastest way is to use netcat aka nc with timeout ability as shared here

Results as 0/1 means postgres working/not-working

echo 'QUIT' | nc -w SECONDS YOUR_HOST PORT; echo $?
# eg
echo 'QUIT' | nc -w 1       localhost 5432; echo $?

Another also-faster way that works for me is to use telnet as discussed here.

echo -e '\x1dclose\x0d' | telnet YOUR_HOST PORT
# eg
echo -e '\x1dclose\x0d' | telnet localhost 5432


来源:https://stackoverflow.com/questions/17303531/check-if-postgresql-is-listening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!