Python中的SSH、SFTP和FTP操作详解

        大家好,在网络编程中,安全地连接到远程服务器并执行操作是一项常见任务。Python 提供了多种库来实现这一目标,其中 Paramiko 是一个功能强大的工具,可以轻松地在 Python 中执行 SSH、SFTP 和 FTP 操作。本文将介绍如何使用 Paramiko 库来进行这些操作。

一、使用 Paramiko 执行 SSH 远程命令

        使用 Python 的 Paramiko 模块可以方便地执行 SSH 远程命令。Paramiko 是一个纯 Python 实现的 SSHv2 协议,它提供了一个简单而强大的 API,可以连接到远程服务器并执行命令,以及传输文件等。

1、安装 Paramiko 模块

可以使用 pip 命令来安装:

pip install paramiko

2、导入 Paramiko 模块

在 Python 脚本中导入 Paramiko 模块:

import paramiko

3、连接到远程服务器

创建一个 SSHClient 对象,并使用 connect() 方法连接到远程服务器:

# 创建 SSHClient 对象
ssh_client = paramiko.SSHClient()

# 添加远程服务器的主机密钥(如果首次连接,需要添加)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接到远程服务器
ssh_client.connect(hostname='your_remote_server', port=22, username='your_username', password='your_password')

4、执行远程命令

使用 exec_command() 方法执行远程命令:

# 执行远程命令
stdin, stdout, stderr = ssh_client.exec_command('ls -l')

# 读取命令执行结果
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')

# 打印执行结果或错误信息
print("Command Output:", output)
print("Command Error:", error)

5、关闭 SSH 连接

执行完远程命令后,记得关闭 SSH 连接:

# 关闭 SSH 连接
ssh_client.close()

6、示例

下面是一个完整的示例,演示了如何使用 Paramiko 执行 SSH 远程命令:

import paramiko

# 远程服务器的信息
hostname = 'your-remote-server'
port = 22
username = 'your-username'
password = 'your-password'

# 创建 SSHClient 对象
ssh_client = paramiko.SSHClient()

try:
    # 添加远程服务器的主机密钥(如果首次连接,需要添加)
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接到远程服务器
    ssh_client.connect(hostname, port, username, password)

    # 执行远程命令
    command = 'ls -l'
    stdin, stdout, stderr = ssh_client.exec_command(command)

    # 获取命令执行结果
    output = stdout.read().decode('utf-8')
    error = stderr.read().decode('utf-8')

    if output:
        print("命令执行结果:")
        print(output)
    else:
        print("错误信息:")
        print(error)

finally:
    # 关闭 SSH 连接
    ssh_client.close()

二、使用 Paramiko 的 SFTP

        Paramiko 的 SFTP(SSH 文件传输协议)功能使得在 Python 中进行安全文件传输变得非常简单。通过 SFTP,你可以连接到远程服务器,上传文件、下载文件、创建目录、删除文件等。

1、导入 Paramiko 模块

首先,在 Python 脚本中导入 Paramiko 模块:

import paramiko

2、连接到远程服务器

创建一个 SSHClient 对象,并使用 connect() 方法连接到远程服务器:

# 创建 SSHClient 对象
ssh_client = paramiko.SSHClient()

# 添加远程服务器的主机密钥(如果首次连接,需要添加)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接到远程服务器
ssh_client.connect(hostname='your_remote_server', port=22, username='your_username', password='your_password')

3、创建 SFTP 客户端

通过 SSHClient 的 open_sftp() 方法创建 SFTP 客户端:

# 创建 SFTP 客户端
sftp_client = ssh_client.open_sftp()

4、执行 SFTP 操作

现在,可以使用 SFTP 客户端执行各种操作,比如上传文件、下载文件、创建目录、删除文件等。以下是一些常见操作的示例:

上传文件

使用 put() 方法上传本地文件到远程服务器:

local_file = '/path/to/local/file.txt'
remote_file = '/path/to/remote/file.txt'
sftp_client.put(local_file, remote_file)

下载文件

使用 get() 方法从远程服务器下载文件到本地:

remote_file = '/path/to/remote/file.txt'
local_file = '/path/to/local/file.txt'
sftp_client.get(remote_file, local_file)

创建目录

使用 mkdir() 方法在远程服务器上创建目录:

remote_dir = '/path/to/remote/directory'
sftp_client.mkdir(remote_dir)

删除文件

使用 remove() 方法删除远程服务器上的文件:

remote_file = '/path/to/remote/file.txt'
sftp_client.remove(remote_file)

5、关闭 SFTP 连接

执行完 SFTP 操作后,记得关闭 SFTP 连接:

# 关闭 SFTP 连接
sftp_client.close()

 6、关闭 SSH 连接

最后,关闭 SSH 连接:

# 关闭 SSH 连接
ssh_client.close()

7、示例

以下是一个完整的示例,演示了如何使用 Paramiko 进行 SFTP 文件传输:

import paramiko

# 远程服务器的信息
hostname = 'your-remote-server'
port = 22
username = 'your-username'
password = 'your-password'

# 远程文件和本地文件的路径
remote_file_path = '/path/to/remote/file.txt'
local_file_path = '/path/to/local/file.txt'

# 创建 SSHClient 对象
ssh_client = paramiko.SSHClient()

try:
    # 添加远程服务器的主机密钥(如果首次连接,需要添加)
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接到远程服务器
    ssh_client.connect(hostname, port, username, password)

    # 创建 SFTP 客户端
    sftp_client = ssh_client.open_sftp()

    # 上传文件到远程服务器
    sftp_client.put(local_file_path, remote_file_path)
    print("文件成功上传到远程服务器")

    # 下载文件到本地
    sftp_client.get(remote_file_path, local_file_path)
    print("文件成功从远程服务器下载到本地")

finally:
    # 关闭 SFTP 连接
    sftp_client.close()

    # 关闭 SSH 连接
    ssh_client.close()

三、Paramiko 远程命令与文件的函数封装

# -*- coding: utf-8 -*-
import paramiko
import threading
import logging as logger

logger.basicConfig(level=logger.INFO)


def remote_command(host_ip, host_port, username, password, command):
    """
    远程执行Linux命令
    :param host_ip: 主机IP地址
    :type host_ip: str
    :param host_port: 主机SSH端口号
    :type host_port: int
    :param username: SSH用户名
    :type username: str
    :param password: SSH密码
    :type password: str
    :param command: 要执行的命令
    :type command: str
    """
    client = None
    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        # 第一次SSH远程连接时会提示输入yes或者no
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host_ip, host_port, username=username, password=password, timeout=10)
        logger.info(f"开始在远程服务器 {host_ip} 上执行命令: {command}")
        # 执行命令
        stdin, stdout, stderr = client.exec_command(command, get_pty=True)
        # 获取命令执行结果,返回的数据是一个字符串
        result = stdout.read().decode('utf-8')
        logger.info(f"{host_ip} 执行结果: {result}")

        error = stderr.read().decode('utf-8')
        if error != "":
            logger.info(f"{host_ip} 错误信息: {error}")
        else:
            pass
    except Exception as e:
        logger.error(e)
    finally:
        client.close()


def batch_remote_command(host_list, host_port, username, password, command):
    """
    批量远程执行Linux命令
    :param host_list: 主机IP地址列表
    :type host_list: list
    :param host_port: 主机SSH端口号
    :type host_port: int
    :param username: SSH用户名
    :type username: str
    :param password: SSH密码
    :type password: str
    :param command: 要执行的命令
    :type command: str
    """
    thread_list = []
    for ip in host_list:
        thread = threading.Thread(target=remote_command, args=(ip, host_port, username, password, command))
        # 将生成的线程添加到列表中
        thread_list.append(thread)
    for t in thread_list:
        # 开始执行线程
        t.start()
    for t in thread_list:
        # 挂起线程,等待所有线程结束
        t.join()

def upload_file_to_remote_server(host, port, username, password, local_path, remote_path):
    """
    上传文件从本地到远程服务器
    Args:
        host (str): 远程服务器的IP地址或主机名
        port (int): 远程服务器的端口
        username (str): 远程服务器的用户名
        password (str): 远程服务器的密码
        local_path (str): 本地文件路径,要上传的文件
        remote_path (str): 远程文件路径,上传的目标位置
    """
    # 连接远程服务器
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, port=port, username=username, password=password)
    # 打开SFTP客户端
    sftp = ssh.open_sftp()
    # 上传本地文件至远程服务器
    sftp.put(local_path, remote_path)
    # 关闭SFTP客户端和SSH连接
    sftp.close()
    ssh.close()

def download_file_from_remote_server(host, port, username, password, remote_path, local_path):
    """
    从远程服务器下载文件到本地
    Args:
        host (str): 远程服务器的IP地址或主机名
        port (int): 远程服务器的端口
        username (str): 远程服务器的用户名
        password (str): 远程服务器的密码
        remote_path (str): 远程文件路径,要下载的文件
        local_path (str): 本地文件路径,下载的目标位置
    """
    # 连接远程服务器
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, port=port, username=username, password=password)
    # 打开SFTP客户端
    sftp = ssh.open_sftp()
    # 下载远程服务器文件至本地
    sftp.get(remote_path, local_path)
    # 关闭SFTP客户端和SSH连接
    sftp.close()
    ssh.close()

四、使用 ftplib 访问 FTP 服务

    ftplib 是 Python 标准库中的一个模块,用于实现 FTP(文件传输协议)客户端。通过 ftplib 模块,你可以编写 Python 程序来连接到 FTP 服务器,上传文件、下载文件、列出目录等。

1、连接到 FTP 服务器

        要连接到 FTP 服务器,首先需要导入 ftplib 模块,然后使用 FTP 类创建一个 FTP 对象,并通过 connect(host, port) 方法连接到服务器。

from ftplib import FTP

ftp = FTP()
ftp.connect('ftp.example.com', 21)

2、登录到 FTP 服务器

        成功连接到 FTP 服务器后,需要登录以进行后续操作。可以使用 login(user, passwd) 方法登录到服务器。

ftp.login('username', 'password')

3、获取目录列表

可以使用 nlst() 方法获取当前目录的文件列表。

file_list = ftp.nlst()
print(file_list)

4、切换目录

可以使用 cwd(path) 方法切换到指定的目录。

ftp.cwd('/path/to/directory')

5、下载文件

要从服务器下载文件,可以使用 retrbinary(command, callback, blocksize, rest) 方法。

local_filename = 'file_to_download.txt'

with open(local_filename, 'wb') as file:
    ftp.retrbinary('RETR file_to_download.txt', file.write)

6、上传文件

要将文件上传到服务器,可以使用 storbinary(command, file, blocksize, callback, rest) 方法。

local_filename = 'file_to_upload.txt'

with open(local_filename, 'rb') as file:
    ftp.storbinary('STOR file_to_upload.txt', file)

7、删除文件

可以使用 delete(filename) 方法从服务器上删除文件。

ftp.delete('file_to_delete.txt')

8、断开连接

完成所有操作后,记得断开与服务器的连接。

ftp.quit()

9、示例

以下是一个完整的示例,演示了如何使用 Python 的 ftplib 模块访问 FTP 服务:

from ftplib import FTP

# FTP 服务器的地址和端口
ftp_host = 'ftp.example.com'
ftp_port = 21

# FTP 服务器的用户名和密码
ftp_username = 'your-username'
ftp_password = 'your-password'

# 连接到 FTP 服务器
ftp = FTP()
ftp.connect(ftp_host, ftp_port)

# 登录到 FTP 服务器
ftp.login(ftp_username, ftp_password)

# 列出当前目录的文件列表
file_list = ftp.nlst()
print("当前目录的文件列表:", file_list)

# 切换到指定目录
ftp.cwd('/path/to/directory')

# 上传文件到服务器
local_filename = 'file_to_upload.txt'
remote_filename = 'uploaded_file.txt'
with open(local_filename, 'rb') as file:
    ftp.storbinary('STOR ' + remote_filename, file)

print("文件成功上传到服务器")

# 下载文件到本地
local_filename = 'downloaded_file.txt'
remote_filename = 'file_to_download.txt'
with open(local_filename, 'wb') as file:
    ftp.retrbinary('RETR ' + remote_filename, file.write)

print("文件成功从服务器下载到本地")

# 删除服务器上的文件
ftp.delete(remote_filename)
print("文件成功从服务器删除")

# 断开与 FTP 服务器的连接
ftp.quit()
print("FTP连接已断开")

        以上是对 ftplib 模块的介绍。使用这个模块,可以轻松地编写 Python 脚本来管理 FTP 服务器上的文件。请注意,在使用 ftplib 模块时要小心处理敏感信息(如用户名和密码),以确保安全性。

  • 32
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒秋丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值