一、安装paramiko
pip install paramiko
二、编写代码块
import os
import paramiko
class SSHConnection(object):
def __init__(self, host, port, username, pwd):
self.__transport = None
self.host = host
self.port = port
self.username = username
self.pwd = pwd
self.__k = None
def connect(self):
transport = paramiko.Transport((self.host, self.port))
transport.connect(username=self.username, password=self.pwd)
self.__transport = transport
def close(self):
self.__transport.close()
def upload(self, local_path, target_path):
sftp = paramiko.SFTPClient.from_transport(self.__transport)
sftp.put(local_path, target_path)
def download(self, remote_path, local_path):
sftp = paramiko.SFTPClient.from_transport(self.__transport)
sftp.get(remote_path, local_path)
def cmd(self, command):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
stdin, stdout, stderr = ssh.exec_command(command)
result = stdout.read()
print(str(result, encoding='utf-8'))
return result
if __name__ == '__main__':
ssh = SSHConnection(host='127.0.0.1', port=22, username='root', pwd='123')
ssh.connect()
third_model_data_path = r'C:\Users\dylan.wu\Desktop\spider_asin\2022-04-28\\'
cmd = r'/bison_mnt/AmzProductPage/2022-04-28/'
ssh.cmd('mkdir -p /bison_mnt/AmzProductPage/2022-04-28')
for filename in os.listdir(third_model_data_path):
print(filename)
ssh.upload(third_model_data_path + filename, cmd + filename)
ssh.close()