import paramiko
import os
class Linux(object):
# 經過IP, 用戶名,密碼,超時時間初始化一個遠程Linux主機
def __init__(self, ip, username, password, timeout=30):
self.ip = ip
self.username = username
self.password = password
self.timeout = timeout
# transport和chanel
self.t = ''
self.chan = ''
# 連接失敗的重試次數
self.try_times = 3app
# 調用該方法鏈接遠程主機
def connect(self):
passssh
# 斷開鏈接
def close(self):
passspa
# 發送要執行的命令
def send(self, cmd):
passorm
# get單個文件
def sftp_get(self, remotefile, localfile):
t = paramiko.Transport(sock=(self.ip, 22))
t.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(remotefile, localfile)
t.close()遞歸
# put單個文件
def sftp_put(self, localfile, remotefile):
t = paramiko.Transport(sock=(self.ip, 22))
t.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localfile, remotefile)
t.close()ip
# ------獲取本地指定目錄及其子目錄下的全部文件------
def __get_all_files_in_local_dir(self, local_dir):
# 保存全部文件的列表
all_files = list()
# 獲取當前指定目錄下的全部目錄及文件,包含屬性值
files = os.listdir(local_dir)
for x in files:
# local_dir目錄中每個文件或目錄的完整路徑
filename = os.path.join(local_dir, x)
# 若是是目錄,則遞歸處理該目錄
if os.path.isdir(x):
all_files.extend(self.__get_all_files_in_local_dir(filename))
else:
all_files.append(filename)
return all_filesrem
def sftp_put_dir(self, local_dir, remote_dir):
ssh = paramiko.SSHClient()get
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip, port=22, username=self.username, password=self.password)
stdin, stdout, stderr = ssh.exec_command("cd /home/zmm/SNWA_space/ad_world/media;mkdir {}".format("aaa/bbb"))
print stdout.readlines()
ssh.close()
t = paramiko.Transport(sock=(self.ip, 22))cmd
t.connect(username=self.username, password=self.password)
ssh = paramiko.SSHClient()it
sftp = paramiko.SFTPClient.from_transport(t)
# 去掉路徑字符穿最後的字符'/',若是有的話
if remote_dir[-1] == '/':
remote_dir = remote_dir[0:-1]
# 獲取本地指定目錄及其子目錄下的全部文件
all_files = self.__get_all_files_in_local_dir(local_dir)
# 依次put每個文件
for x in all_files:
filename = os.path.split(x)[-1]
remote_filename = remote_dir + '/' + filename
print u'Put文件%s傳輸中...' % filename
sftp.put(x, remote_filename)
if __name__ == '__main__':
remote_path = r'/home/zmm/SNWA_space/'
local_path = r'hitb-ams2018/data.yml'
host = Linux('192.168.1.201', 'zmm', 'zhangmiaomiao')
# 將遠端remote_path目錄中的全部文件get到本地local_path目錄 # host.sftp_get_dir(remote_path, local_path) # # 將本地local_path目錄中的全部文件put到遠端remote_path目錄 host.sftp_put_dir(remote_path, local_path)