第一种:
import paramiko # 用于调用scp命令
from scp import SCPClient
# 将指定目录的图片文件上传到服务器指定目录
# remote_path远程服务器目录
# file_path本地文件夹路径
# img_name是file_path本地文件夹路径下面的文件名称
def upload_img(img_name, remote_path="/var/www/html/public/thinkfont/competitor/data/font/oppo/preview_pic", file_path="D:\PythonProject\img"):
# img_name示例:07670ff76fc14ab496b0dd411a33ac95-6.webp
host = "***.***.***.***" #服务器ip地址
port = 22 # 端口号
username = "duanyuanjin" # ssh 用户名
password = "duanVlife" # 密码
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(host, port, username, password)
scpclient = SCPClient(ssh_client.get_transport(),socket_timeout=15.0)
local_path = file_path + "\\" + img_name
try:
scpclient.put(local_path, remote_path)
except FileNotFoundError as e:
print(e)
print("系统找不到指定文件" + local_path)
else:
print("文件上传成功")
ssh_client.close()
参考:https://blog.csdn.net/huangxin388/article/details/88294597
第二种:
import pexpect
class Transfer(object):
"""
python-scp
"""
def __init__(self):
self.passwd_key = 'Cqbd~!201401'
print("Transfer Working")
def upload(self, ip, user, dst_path, filename):
# 上传
cmdline = 'scp -r %s %s@%s:%s' % (filename, user, ip, dst_path)
try:
child = pexpect.spawn(cmdline)
child.expect(self.passwd_key)
child.sendline()
child.expect(pexpect.EOF)
print("file upload Finish!")
except Exception as e:
print("upload failed:", e)
def download(self, ip, user, dst_path, filename):
# 下载
cmdline = 'scp -r %s@%s:%s %s' % (user, ip, dst_path, filename)
try:
child = pexpect.spawn(cmdline)
child.expect(self.passwd_key)
child.sendline()
child.expect(pexpect.EOF)
print("file download Finish!")
except Exception as e:
print("download failed:", e)
triger = Transfer()
triger.upload(host, username, remote_dir, local)
参考:https://blog.csdn.net/u012965373/article/details/72822461