#! /usr/bin/env python3
# coding:utf-8
import paramiko
import re
from os import path
import time
import logging
import logging.handlers
# hostname = '132.33.35.23'
# username = 'ftstp'
# password = 'testZz$nN01h'
# port = 22
# local_dir = '/tmp/local_dir'
# remote_dir = '/tmp/remote_dir'
# log_file_path = '.'
# log_file_name = 'file_get_put.log'
hostname = '192.168.40.11'
username = 'root'
password = '1qaz!QAZ'
port = 22
local_dir = '/root/cly_test/test_file_get_put'
remote_dir = '/root/clytest/test_file_get_put'
log_file_path = '.'
log_file_name = 'file_get_put.log'
def init_logger(log_file_path,log_file_name):
FORMAT_STR = '[%(asctime)s][%(thread)d][%(filename)s][line: %(lineno)d][%(levelname)s] ## %(message)s'
log_format = logging.Formatter(FORMAT_STR)
file_handle = logging.handlers.RotatingFileHandler(
filename=path.join(log_file_path, log_file_name),
maxBytes=1024 * 1024,
backupCount=10)
file_handle.setFormatter(log_format)
logger = logging.getLogger('log')
logger.addHandler(file_handle)
logger.setLevel(logging.DEBUG)
logger.info('init logger success')
try:
init_logger(log_file_path,log_file_name)
logger = logging.getLogger('log')
t = paramiko.Transport((hostname, port))
logger.info('connect obj {}'.format(t))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
files = sftp.listdir(remote_dir)
now = time.strftime('%Y%m%d', time.localtime())
'匹配规则,按当前日期匹配'
pattern = re.compile(r'^{}.*?REQ$'.format(now))
logger.info('pattern{}'.format(pattern))
# 如果有多层嵌套的目录处理下即可
for f in files:
if re.match(pattern, f):
logger.info('match file {}'.format(f))
sftp.get(path.join(remote_dir, f), path.join(local_dir, f))
t.close()
except Exception as err:
logging.error(err)
python远程连接
最新推荐文章于 2024-07-18 02:22:28 发布