需求:
1、從postgresql數(shù)據(jù)庫(kù)中查出附件名稱
2、從遠(yuǎn)程服務(wù)器下載對(duì)應(yīng)的附件
用到的python模塊paramiko、psycopg2。
paramiko是用python寫的一個(gè)模塊,遵循SSH2協(xié)議,支持以加密和認(rèn)證的方式,進(jìn)行遠(yuǎn)程服務(wù)器的連接。利用該模塊,可以方便的進(jìn)行ssh連接和sftp協(xié)議進(jìn)行sftp文件傳輸以及遠(yuǎn)程命令執(zhí)行。
psycopg2是python的postgresql數(shù)據(jù)庫(kù)接口,可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作。
conndb.py文件代碼功能是連接數(shù)據(jù)庫(kù),查詢附件的名稱,用于拼接地址。
import psycopg2
def conn_db():
# database,user,password,host,port分別對(duì)應(yīng)要連接的PostgreSQL數(shù)據(jù)庫(kù)的數(shù)據(jù)庫(kù)名、數(shù)據(jù)庫(kù)用戶名、用戶密碼、主機(jī)、端口信息
conn = psycopg2.connect(database="h", user="oe", password="1234", host="10.18.xxx.xxx", port="5432")
cursor = conn.cursor()
# 執(zhí)行查詢命令
cursor.execute("select store_fname,datas_fname from contract_attachment where contract_interview_id in(select id from hr_re)")
result = cursor.fetchall()
print(result)
# cursor.close() #關(guān)閉游標(biāo)
conn.close() #關(guān)閉連接
return result
download.py進(jìn)行連接服務(wù)器和下載文件的操作
from conndb import conn_db
import os
import re
import logging
import paramiko
import base64
_logger = logging.getLogger(__name__)
PATH = '/hr/openerp8/openerp/'
LOCATION='file:///filestore'
dbname='h'
def full_path(path):
# location = 'file:filestore'
assert LOCATION.startswith('file:'), "Unhandled filestore location %s" % LOCATION
location = LOCATION[5:]
# sanitize location name and path
location = re.sub('[.]', '', location)
location = location.strip('/\\')
path = re.sub('[.]', '', path)
path = path.strip('/\\')
res_path =os.path.join(PATH, location, dbname, path)
return res_path.replace('\\','/')
def data_get(data):
result = []
bin_size = False
for attach in data:
# f_path = None
if LOCATION and attach[0]:
f_path = full_path(attach[0])
result.append(f_path)
# os.remove(f_path)
return result
def RemoteScp(host_ip, host_port, host_username, host_password, remote_file, local_file):
scp = paramiko.Transport((host_ip, host_port))
scp.connect(username=host_username, password=host_password)
sftp = paramiko.SFTPClient.from_transport(scp)
for file in remote_file:
file_path,filename =os.path.split(file)
sftp.get(file, local_file+'/'+filename)
scp.close()
return ("success")
if __name__ == '__main__':
ip="10.18.xxx.xxx"
user="root"
passwd="1234"
host_port = 22
data = conn_db() #取文件名集合
all_file = data_get(data)
local_path = 'F:/ProjectTrain/download_file/att'
RemoteScp(ip, host_port, user, passwd, all_file, local_path)
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
