如何在Python中实现scp?

2024-04-23 19:00:19 发布

您现在位置:Python中文网/ 问答频道 /正文

用Python编写一个文件的最Python方法是什么?我知道的唯一途径是

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不是一个选项。

编辑: 这是How to copy a file to a remote server in Python using SCP or SSH?的副本。然而,这个问题并没有给出一个特定于scp的答案来处理Python中的键。我希望有一种运行代码的方法

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')

Tags: 模块orto方法clienthost密码remote
3条回答

您可能有兴趣尝试Pexpectsource code)。这将允许您处理输入密码的交互式提示。

以下是来自主网站的一个示例用法(用于ftp):

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

您还可以查看paramiko。目前还没有scp模块,但它完全支持sftp。

[编辑] 对不起,错过了你提到帕拉米科的那一行。 以下模块只是paramiko的scp协议的一个实现。 如果您不想使用paramiko或conch(我所知道的python的唯一ssh实现),您可以重新编写它,以便在使用管道的常规ssh会话中运行。

scp.py for paramiko

试试Python scp module for Paramiko。它很容易使用。请参见以下示例:

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操作。

SCPClient code

相关问题 更多 >