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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM