【python操作ssh上传和下载文件】
python操作ssh上传和下载文件
1.笔者环境
os:macos
python:3.7.5
2.项目地址
3.依赖来安装包
pip install paramiko
pip install scp
4.项目结构
├── download_file.py # 下载文件
├── main.py # 程序入口
├── settings.py # 配置
└── upload_file.py # 上传文件
5.代码示例:
# upload_file.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import paramiko
from scp import SCPClient
from settings import HOST
from settings import PORT
from settings import USERNAME
from settings import PASSWORD
from settings import UPLOAD_SERVER_REMOTE_PATH
from settings import UPLOAD_LOCAL_FILE_PATG
def upload_file():
"""
上传文件
:return:
"""
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(HOST, PORT, USERNAME, PASSWORD)
scp_client = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
try:
scp_client.put(UPLOAD_LOCAL_FILE_PATG, UPLOAD_SERVER_REMOTE_PATH)
except FileNotFoundError as e:
print(e)
print("系统找不到指定文件" + UPLOAD_LOCAL_FILE_PATG)
else:
print("文件上传成功")
ssh_client.close()
# download_file.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import paramiko
from scp import SCPClient
from settings import HOST
from settings import PORT
from settings import USERNAME
from settings import PASSWORD
from settings import DOWNLOAD_LOCAL_FILE_PATH
from settings import DOWNLOAD_SERVER_REMOTE_PATH
def download_file():
"""
下载文件
:return:
"""
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(HOST, PORT, USERNAME, PASSWORD)
scp_client = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
try:
scp_client.get(DOWNLOAD_SERVER_REMOTE_PATH, DOWNLOAD_LOCAL_FILE_PATH)
except FileNotFoundError as e:
print(e)
print("系统找不到指定文件" + DOWNLOAD_SERVER_REMOTE_PATH)
else:
print("文件下载成功")
ssh_client.close()
# settings.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 公共配置
HOST = "xx.xx.xx.xx" # 服务器ip地址
PORT = 22 # 端口号
USERNAME = "xxxxxx" # 用户名
PASSWORD = "xxxxxxx" # 密码
# 上传文件的配置
UPLOAD_SERVER_REMOTE_PATH = "/opt" # 要上传的目标路径
UPLOAD_LOCAL_FILE_PATG = "/Users/xxx/2.txt" # 本地文件的路径
# 下载文件的配置
DOWNLOAD_SERVER_REMOTE_PATH = "/opt/3.txt" # 要下载的服务器上文件的位置
DOWNLOAD_LOCAL_FILE_PATH = "/Users/xxx" # 本地路径
# main.py
from download_file import download_file
from upload_file import upload_file
def main():
print("upload_file...")
upload_file()
print("download_file...")
download_file()
if __name__ == '__main__':
main()