对“使用Python拷贝远端服务器文件”的代码分析

参考资料:
用Python拷贝(scp)远端服务器上的文件(或文件夹)
Client — Paramiko documentation
Welcome to Paramiko!
Unicodedata – Unicode Database in Python

第一个参考文件中的作者的代码如下:

import os
import paramiko
import unicodedata
from scp import SCPClient
 
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('服务器IP地址', 服务器SSH端口, '服务器登录账号', '服务器登录密码')
scp = SCPClient(client.get_transport())
 
# 拿到服务器上所有文件夹
stdin, stdout, stderr = client.exec_command(
    'find 服务器上的文件路径 -type l'
)
 
# 遍历远端服务器上的所有文件夹,若在本地服务器不存在,则scp过来
for line in stdout:
    dir = line.strip("\n")
    
    # 文件名截取出来
    file_name = dir.split('/')[第几位]
    if os.path.exists('待拷贝进入的本机路径' + file_name):
        print('sub dir %s  already exists. skip it' % file_name)
    else:
        print('start to copy %s...' % file_name)
        scp.get(os.path.join(dir), '待拷贝进入的本机路径', recursive=True)
 
scp.close()
client.close()

现在开始对其代码分析:

1.什么是Paramiko:
Paramiko是一个纯粹的执行SSHv2协议的Python库,并提供了客户端和服务器端功能。它提供了高水平的SSH库Fabric,这是我们建议您在运行远程shell命令或传输文件等常见客户端用例中使用的。

2.什么是unicodedata:
该模块允许使用Unicode Character Database(Unicode字符数据库)的服务,并且使用和Unicode Character Database(Unicode字符数据库)所定义的同样的字符和名称。
Unicode Character Database (UCD) 是由 Unicode Standard Annex所定义的。

3.client = paramiko.SSHClient()
创建一个新的ssh客户端,并起名为client

4.load_system_host_keys(filename=None):
Load host keys from a system (read-only) file.Host keys read with this method will not be saved back by save_host_keys.If filename is left as None, an attempt will be made to read keys from the user’s local “known hosts” file, as used by OpenSSH, and no exception will be raised if the file can’t be read.
如果提供了文件名却读不了的话就会报一个IOError

5.set_missing_host_key_policy(policy):
负责在连接没有已知主机密钥的服务器时设定使用的连接策略。

6.get_transport():
返回此SSH连接的底层Transport对象。这可以用于执行较低级别的任务,例如打开特定类型的通道。

你可能感兴趣的:(科研笔记,python,远程连接,文件拷贝)