psycopg2连接PostgreSQL并操作

import psycopg2.extras
import time
from sshtunnel import SSHTunnelForwarder

start_time = 1615707560
end_time = 1615707562
ip = ['10.67.201.42', '192.168.138.16']
#
#
# a = time.localtime(start_time)
# dt = time.strftime("%Y-%m-%d %H:%M:%S", a)
# print(dt)


with SSHTunnelForwarder(
        ("10.67.200.82", 22),
        ssh_username="admin",
        ssh_password="Test_1234sangfornetwork",
        remote_bind_address=('0.0.0.0', 5550)
) as server:
    conn = psycopg2.connect(database='sip',
                            user='sipadmin',
                            password='3VrZ6J4S]RXIyMlt',
                            host='127.0.0.1',
                            port=server.local_bind_port)

    print(conn)

    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

    sql = "SELECT * FROM alerts WHERE " 
          "(ATTACK_IP IN {0} OR SUFFER_IP IN {0}) " 
          "AND " 
          "(LAST_TIME BETWEEN {1} AND {2});".format(tuple(ip), start_time, end_time)

    print(sql)

    # sql = "SELECT * FROM alerts WHERE " 
    #       "ATTACK_IP IN {0} OR SUFFER_IP IN {0};".format(ip)

    # sql = "SELECT * FROM alerts WHERE " 
    #       "ATTACK_IP IN {0};".format(ip)
    # sql = "SELECT * FROM alerts where LAST_TIME BETWEEN 1615707560 AND 1615707562;"

    cursor.execute(sql)

    rows = cursor.fetchall()
    for i in rows:
        print(i)
        print(i.get("attack_ip"))
        print(i.get("suffer_ip"))
        print(i.get("last_time"))

    conn.commit()

    cursor.close()

    conn.close()
抟扶摇而上者九万里
原文地址:https://www.cnblogs.com/fengting0913/p/15392644.html