0


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

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

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

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

1、安装 Paramiko 模块

可以使用 pip 命令来安装:

  1. pip install paramiko

2、导入 Paramiko 模块

在 Python 脚本中导入 Paramiko 模块:

  1. import paramiko

3、连接到远程服务器

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

  1. # 创建 SSHClient 对象
  2. ssh_client = paramiko.SSHClient()
  3. # 添加远程服务器的主机密钥(如果首次连接,需要添加)
  4. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  5. # 连接到远程服务器
  6. ssh_client.connect(hostname='your_remote_server', port=22, username='your_username', password='your_password')

4、执行远程命令

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

  1. # 执行远程命令
  2. stdin, stdout, stderr = ssh_client.exec_command('ls -l')
  3. # 读取命令执行结果
  4. output = stdout.read().decode('utf-8')
  5. error = stderr.read().decode('utf-8')
  6. # 打印执行结果或错误信息
  7. print("Command Output:", output)
  8. print("Command Error:", error)

5、关闭 SSH 连接

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

  1. # 关闭 SSH 连接
  2. ssh_client.close()

6、示例

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

  1. import paramiko
  2. # 远程服务器的信息
  3. hostname = 'your-remote-server'
  4. port = 22
  5. username = 'your-username'
  6. password = 'your-password'
  7. # 创建 SSHClient 对象
  8. ssh_client = paramiko.SSHClient()
  9. try:
  10. # 添加远程服务器的主机密钥(如果首次连接,需要添加)
  11. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  12. # 连接到远程服务器
  13. ssh_client.connect(hostname, port, username, password)
  14. # 执行远程命令
  15. command = 'ls -l'
  16. stdin, stdout, stderr = ssh_client.exec_command(command)
  17. # 获取命令执行结果
  18. output = stdout.read().decode('utf-8')
  19. error = stderr.read().decode('utf-8')
  20. if output:
  21. print("命令执行结果:")
  22. print(output)
  23. else:
  24. print("错误信息:")
  25. print(error)
  26. finally:
  27. # 关闭 SSH 连接
  28. ssh_client.close()

二、使用 Paramiko 的 SFTP

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

1、导入 Paramiko 模块

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

  1. import paramiko

2、连接到远程服务器

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

  1. # 创建 SSHClient 对象
  2. ssh_client = paramiko.SSHClient()
  3. # 添加远程服务器的主机密钥(如果首次连接,需要添加)
  4. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  5. # 连接到远程服务器
  6. ssh_client.connect(hostname='your_remote_server', port=22, username='your_username', password='your_password')

3、创建 SFTP 客户端

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

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

4、执行 SFTP 操作

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

上传文件

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

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

下载文件

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

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

创建目录

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

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

删除文件

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

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

5、关闭 SFTP 连接

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

  1. # 关闭 SFTP 连接
  2. sftp_client.close()

6、关闭 SSH 连接

最后,关闭 SSH 连接:

  1. # 关闭 SSH 连接
  2. ssh_client.close()

7、示例

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

  1. import paramiko
  2. # 远程服务器的信息
  3. hostname = 'your-remote-server'
  4. port = 22
  5. username = 'your-username'
  6. password = 'your-password'
  7. # 远程文件和本地文件的路径
  8. remote_file_path = '/path/to/remote/file.txt'
  9. local_file_path = '/path/to/local/file.txt'
  10. # 创建 SSHClient 对象
  11. ssh_client = paramiko.SSHClient()
  12. try:
  13. # 添加远程服务器的主机密钥(如果首次连接,需要添加)
  14. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  15. # 连接到远程服务器
  16. ssh_client.connect(hostname, port, username, password)
  17. # 创建 SFTP 客户端
  18. sftp_client = ssh_client.open_sftp()
  19. # 上传文件到远程服务器
  20. sftp_client.put(local_file_path, remote_file_path)
  21. print("文件成功上传到远程服务器")
  22. # 下载文件到本地
  23. sftp_client.get(remote_file_path, local_file_path)
  24. print("文件成功从远程服务器下载到本地")
  25. finally:
  26. # 关闭 SFTP 连接
  27. sftp_client.close()
  28. # 关闭 SSH 连接
  29. ssh_client.close()

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

  1. # -*- coding: utf-8 -*-
  2. import paramiko
  3. import threading
  4. import logging as logger
  5. logger.basicConfig(level=logger.INFO)
  6. def remote_command(host_ip, host_port, username, password, command):
  7. """
  8. 远程执行Linux命令
  9. :param host_ip: 主机IP地址
  10. :type host_ip: str
  11. :param host_port: 主机SSH端口号
  12. :type host_port: int
  13. :param username: SSH用户名
  14. :type username: str
  15. :param password: SSH密码
  16. :type password: str
  17. :param command: 要执行的命令
  18. :type command: str
  19. """
  20. client = None
  21. try:
  22. # 创建SSH客户端
  23. client = paramiko.SSHClient()
  24. # 第一次SSH远程连接时会提示输入yes或者no
  25. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  26. client.connect(host_ip, host_port, username=username, password=password, timeout=10)
  27. logger.info(f"开始在远程服务器 {host_ip} 上执行命令: {command}")
  28. # 执行命令
  29. stdin, stdout, stderr = client.exec_command(command, get_pty=True)
  30. # 获取命令执行结果,返回的数据是一个字符串
  31. result = stdout.read().decode('utf-8')
  32. logger.info(f"{host_ip} 执行结果: {result}")
  33. error = stderr.read().decode('utf-8')
  34. if error != "":
  35. logger.info(f"{host_ip} 错误信息: {error}")
  36. else:
  37. pass
  38. except Exception as e:
  39. logger.error(e)
  40. finally:
  41. client.close()
  42. def batch_remote_command(host_list, host_port, username, password, command):
  43. """
  44. 批量远程执行Linux命令
  45. :param host_list: 主机IP地址列表
  46. :type host_list: list
  47. :param host_port: 主机SSH端口号
  48. :type host_port: int
  49. :param username: SSH用户名
  50. :type username: str
  51. :param password: SSH密码
  52. :type password: str
  53. :param command: 要执行的命令
  54. :type command: str
  55. """
  56. thread_list = []
  57. for ip in host_list:
  58. thread = threading.Thread(target=remote_command, args=(ip, host_port, username, password, command))
  59. # 将生成的线程添加到列表中
  60. thread_list.append(thread)
  61. for t in thread_list:
  62. # 开始执行线程
  63. t.start()
  64. for t in thread_list:
  65. # 挂起线程,等待所有线程结束
  66. t.join()
  67. def upload_file_to_remote_server(host, port, username, password, local_path, remote_path):
  68. """
  69. 上传文件从本地到远程服务器
  70. Args:
  71. host (str): 远程服务器的IP地址或主机名
  72. port (int): 远程服务器的端口
  73. username (str): 远程服务器的用户名
  74. password (str): 远程服务器的密码
  75. local_path (str): 本地文件路径,要上传的文件
  76. remote_path (str): 远程文件路径,上传的目标位置
  77. """
  78. # 连接远程服务器
  79. ssh = paramiko.SSHClient()
  80. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  81. ssh.connect(hostname=host, port=port, username=username, password=password)
  82. # 打开SFTP客户端
  83. sftp = ssh.open_sftp()
  84. # 上传本地文件至远程服务器
  85. sftp.put(local_path, remote_path)
  86. # 关闭SFTP客户端和SSH连接
  87. sftp.close()
  88. ssh.close()
  89. def download_file_from_remote_server(host, port, username, password, remote_path, local_path):
  90. """
  91. 从远程服务器下载文件到本地
  92. Args:
  93. host (str): 远程服务器的IP地址或主机名
  94. port (int): 远程服务器的端口
  95. username (str): 远程服务器的用户名
  96. password (str): 远程服务器的密码
  97. remote_path (str): 远程文件路径,要下载的文件
  98. local_path (str): 本地文件路径,下载的目标位置
  99. """
  100. # 连接远程服务器
  101. ssh = paramiko.SSHClient()
  102. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  103. ssh.connect(hostname=host, port=port, username=username, password=password)
  104. # 打开SFTP客户端
  105. sftp = ssh.open_sftp()
  106. # 下载远程服务器文件至本地
  107. sftp.get(remote_path, local_path)
  108. # 关闭SFTP客户端和SSH连接
  109. sftp.close()
  110. ssh.close()

四、使用

  1. ftplib 访问 FTP 服务
  1. ftplib

是 Python 标准库中的一个模块,用于实现 FTP(文件传输协议)客户端。通过

  1. ftplib

模块,你可以编写 Python 程序来连接到 FTP 服务器,上传文件、下载文件、列出目录等。

1、连接到 FTP 服务器

  1. 要连接到 FTP 服务器,首先需要导入
  1. ftplib

模块,然后使用

  1. FTP

类创建一个 FTP 对象,并通过

  1. connect(host, port)

方法连接到服务器。

  1. from ftplib import FTP
  2. ftp = FTP()
  3. ftp.connect('ftp.example.com', 21)

2、登录到 FTP 服务器

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

方法登录到服务器。

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

3、获取目录列表

可以使用

  1. nlst()

方法获取当前目录的文件列表。

  1. file_list = ftp.nlst()
  2. print(file_list)

4、切换目录

可以使用

  1. cwd(path)

方法切换到指定的目录。

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

5、下载文件

要从服务器下载文件,可以使用

  1. retrbinary(command, callback, blocksize, rest)

方法。

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

6、上传文件

要将文件上传到服务器,可以使用

  1. storbinary(command, file, blocksize, callback, rest)

方法。

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

7、删除文件

可以使用

  1. delete(filename)

方法从服务器上删除文件。

  1. ftp.delete('file_to_delete.txt')

8、断开连接

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

  1. ftp.quit()

9、示例

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

  1. from ftplib import FTP
  2. # FTP 服务器的地址和端口
  3. ftp_host = 'ftp.example.com'
  4. ftp_port = 21
  5. # FTP 服务器的用户名和密码
  6. ftp_username = 'your-username'
  7. ftp_password = 'your-password'
  8. # 连接到 FTP 服务器
  9. ftp = FTP()
  10. ftp.connect(ftp_host, ftp_port)
  11. # 登录到 FTP 服务器
  12. ftp.login(ftp_username, ftp_password)
  13. # 列出当前目录的文件列表
  14. file_list = ftp.nlst()
  15. print("当前目录的文件列表:", file_list)
  16. # 切换到指定目录
  17. ftp.cwd('/path/to/directory')
  18. # 上传文件到服务器
  19. local_filename = 'file_to_upload.txt'
  20. remote_filename = 'uploaded_file.txt'
  21. with open(local_filename, 'rb') as file:
  22. ftp.storbinary('STOR ' + remote_filename, file)
  23. print("文件成功上传到服务器")
  24. # 下载文件到本地
  25. local_filename = 'downloaded_file.txt'
  26. remote_filename = 'file_to_download.txt'
  27. with open(local_filename, 'wb') as file:
  28. ftp.retrbinary('RETR ' + remote_filename, file.write)
  29. print("文件成功从服务器下载到本地")
  30. # 删除服务器上的文件
  31. ftp.delete(remote_filename)
  32. print("文件成功从服务器删除")
  33. # 断开与 FTP 服务器的连接
  34. ftp.quit()
  35. print("FTP连接已断开")
  1. 以上是对
  1. ftplib

模块的介绍。使用这个模块,可以轻松地编写 Python 脚本来管理 FTP 服务器上的文件。请注意,在使用

  1. ftplib

模块时要小心处理敏感信息(如用户名和密码),以确保安全性。

标签: ssh 运维 python

本文转载自: https://blog.csdn.net/xiangxi1204/article/details/139237381
版权归原作者 寒秋丶 所有, 如有侵权,请联系我们删除。

“Python中的SSH、SFTP和FTP操作详解”的评论:

还没有评论