Python處理ftp上傳以及操作linux
阿新 • • 發佈:2021-01-30
說明
用到的模組:
- tqdm 進度條
- paramiko 操作ssh和sftp
其他模組:
- logging
- os
解決問題
本地寫的文件需要上傳到伺服器,每次需要開啟工具進行上傳,耗時比較久,所以寫了這樣的一個工具來。
當然解決方案還有很多:比如使用git配合paramiko完成等,這裡介紹一個不需安裝任何軟體的方法。這樣省去了很多時間,寫完文件只需要點選下指令碼執行即可。
原始碼
class MySftp:
def __init__(self, host, server_path, local_path):
self. host = host
self.server_path = server_path
self.local_path = local_path
self.username = 'root'
self.password = 'password'
self.file_list = []
def clear(self):
"""
上傳前清空目標目錄的檔案資訊
:return:
"""
client = paramiko.SSHClient()
client.connect(hostname=self.host, port=22, username=self.username, password=self.password)
stdin, stdout, stderr = client.exec_command('rm -rf ' + self.server_path)
logging.info(">>> " + stdout.read().decode('utf-8'))
client.close( )
def put_file(self):
"""
將當前檔案的內容上傳到伺服器指定資料夾內
:return:
"""
self.get_file_path(self.local_path)
files_len = int(len(self.file_list))
logging.info(">>> 檔案數量:" + str(files_len))
transport = paramiko.Transport(sock=self.host)
transport.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(transport)
with tqdm(total=files_len, desc='上傳進度:', leave=True, ncols=100, unit='file', unit_scale=True) as pbar:
for item in self.file_list:
target_file = str(item).replace(self.local_path, self.server_path).replace('\\', '/')
# 建立目錄
try:
sftp.chdir(path=os.path.split(target_file)[0])
except IOError:
sftp.mkdir(path=os.path.split(target_file)[0])
sftp.put(item, target_file)
pbar.update(1)
logging.info(">>> 上傳完成...")
transport.close()
def get_file_path(self, root_path):
"""
獲取資料夾下的檔案列表
:param root_path:
:return:
"""
for dir_file in os.listdir(root_path):
dir_file_path = os.path.join(root_path, dir_file)
if os.path.isdir(dir_file_path):
self.get_file_path(dir_file_path)
else:
self.file_list.append(dir_file_path)
使用
if __name__ == '__main__':
sftp = MySftp('172.18.xx.xx', '/opt/test', 'D:\\Project\\open-docsify\\xxx')
logging.info(">>> 開始清空目標目錄...")
sftp.clear()
logging.info(">>> 開始上傳檔案...")
sftp.put_file()
執行效果