如何在Python中进行scp?

发布于 2021-02-02 23:13:12

在Python中scp文件的最pythonic方式是什么?我知道的唯一路线是

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

这是一种骇客,并且在类似Linux的系统之外不起作用,并且需要Pexpect模块的帮助来避免出现密码提示,除非你已经为远程主机设置了无密码的SSH。

我知道Twisted的conch,但是我希望避免通过低级ssh模块自己实现scp。

我知道paramiko,一个支持SSH和SFTP的Python模块;但它不支持SCP。

背景:我正在连接到不支持SFTP但确实支持SSH / SCP的路由器,因此不能选择SFTP。

编辑:这是如何使用SCP或SSH将文件复制到远程服务器中的副本?。 但是,该问题并未给出处理来自Python内部键的特定于scp的答案。我希望找到一种运行类似代码的方法

import scp

client = scp.Client(host=host, user=user, keyfile=keyfile)
# or
client = scp.Client(host=host, user=user)
client.use_system_keys()
# or
client = scp.Client(host=host, user=user, password=password)

# and then
client.transfer('/etc/local/filename', '/etc/remote/filename')
关注者
0
被浏览
99
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    尝试使用ParamikoPython scp模块。它很容易使用。请参见以下示例:

    import paramiko
    from scp import SCPClient
    
    def createSSHClient(server, port, user, password):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(server, port, user, password)
        return client
    
    ssh = createSSHClient(server, port, user, password)
    scp = SCPClient(ssh.get_transport())
    

    然后致电scp.get()scp.put()进行SCP操作。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看