基于Python實作的ssh兼sftp用戶端
by:授客 QQ:1033553122
otherTools.py
#!/usr/bin/env/ python
#
-*- coding:utf-8 -*-
__author__
=
'laifuyu'
import
os
subprocess
class
OtherTools:
def
__init__(self):
self.filepath_list
= []
#
批量建立目錄
mkdirs_once_many(self,
path):
path
= os.path.normpath(path) #
去掉路徑最右側的 \\
、/
= path.replace('\\',
'/')
# 将所有的\\轉為/,避免出現轉義字元串
head,
tail = os.path.split(path)
new_dir_path
'' #
反轉後的目錄路徑
root
'' #根目錄
if
not
os.path.isdir(path)
and
os.path.isfile(path): #
如果path指向的是檔案,則繼續分解檔案所在目錄
head,
tail = os.path.split(head)
tail ==
'':
return
while
tail:
new_dir_path
= new_dir_path + tail +
'/'
root
= head
else:
= root + new_dir_path
#
= os.path.normpath(new_dir_path)
tail = os.path.split(new_dir_path)
temp
''
while
temp
= temp +
'/'
+ tail
dir_path
= root + temp
if
os.path.isdir(dir_path):
os.mkdir(dir_path)
head,
# 測試
ssh_client
= MySSHClient()
ssh_client.connect(hostname='192.168.1.102',
port=22,
username='root',password='huozhe')
ssh_client.exec_command('ls
-l')
ssh_client.download_file('/root/dirForDownload/file',
'./test1.txt')
'.\test2.txt')
'd:\\test3.txt')
'd:\test4.txt')
'd:\mytest4.txt')
'd:/test5.txt')
'd:\dir1\dir2\test6.txt')
ssh_client.upload_file('./test1.txt','/root/test1.txt'
)
ssh_client.upload_file('d:\mytest4.txt','/root/mytestfile.txt'
ssh_client.upload_file('d:\dir1\dir2\test6.txt','./test6.txt'
ssh_client.close()
運作結果:

注意事項
# 1. 下載下傳檔案
1) 不支援目錄級的下載下傳,即隻能下載下傳指定的單個非目錄檔案
2) 本地目标檔案路徑隻支援檔案路徑,不支援目錄(比如 localpath='d:\\'),目标檔案所在的上級路徑可以不存在(但路徑必須位于分區下)
比如欲下載下傳到本地路徑:d:\dir1\dir2\test.txt, d:\dir1\dir2\可以不存在
3) 本地目标檔案支援相對路徑,比如./text.txt,遠端目标檔案僅支援絕對路徑
2. 上傳檔案
1) 不支援目錄級的上傳,隻能上傳指定的單個檔案
2) 遠端目标檔案所在的上級路徑必須存在,比如remotepath='/root/dir1/tarfile' ,其中/root/dir1必須存在
3) 遠端目标檔案、本地檔案路徑都支援相對路徑,比如./text.txt
3. 重複下載下傳檔案、上傳檔案,會自動覆寫已經下載下傳的檔案、已上傳的檔案
參考文檔:
http://docs.paramiko.org/en/2.4/api/channel.html
http://docs.paramiko.org/en/2.4/api/sftp.html#paramiko.sftp_client.SFTPClient
作者:授客
QQ:1033553122
全國軟體測試QQ交流群:7156436
Git位址:https://gitee.com/ishouke
友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額随意,您的支援将是我繼續創作的源動力,打賞後如有任何疑問,請聯系我!!!
微信打賞
支付寶打賞 全國軟體測試交流QQ群