如何使用python 3.2使用scp发送文件? [英] How to send a file using scp using python 3.2?
问题描述
我正尝试通过no-ack的libssh2的python byndings将一组文件发送到远程服务器,但是由于缺少文档,我对库的使用完全迷失了.
I'm trying to send a group of files to a remote server through no-ack's python byndings for libssh2, but I am totally lost regarding the library usage due to the lack of documentation.
我尝试将C文档用于libssh2失败.
I've tried using the C docs for libssh2 unsuccesfully.
由于我使用的是python 3.2,因此paramiko和pexpect都不是问题. 有人可以帮忙吗?
Since I'm using python 3.2, paramiko and pexpect are out of the question. Anyone can help?
我刚刚在no-Ack的博客评论中找到了一些代码.
I just found some code in no-Ack's blog comments to his post.
import libssh2, socket, os
SERVER = 'someserver'
username = 'someuser'
password = 'secret!'
sourceFilePath = 'source/file/path'
destinationFilePath = 'dest/file/path'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER, 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password(username, password)
sourceFile = open(sourceFilePath, 'rb')
channel = session.scp_send(destinationFilePath, 0o644, os.stat(sourceFilePath).st_size)
while True:
data = sourceFile.read(4096)
if not data:
break
channel.write(data)
exitStatus = channel.exit_status()
channel.close()
似乎可以正常工作.
推荐答案
以下是在Python 3.2中使用libssh2 获取文件的方法. no-Ack向我展示了这一点,这是他的主要荣誉.您需要libssh2的Python3绑定 https://github.com/wallunit/ssh4py
And here's how to get files with libssh2 in Python 3.2. Major kudos to no-Ack for showing me this. You'll need the Python3 bindings for libssh2 https://github.com/wallunit/ssh4py
import libssh2, socket, os
SERVER = 'someserver'
username = 'someuser'
password = 'secret!'
sourceFilePath = 'source/file/path'
destinationFilePath = 'dest/file/path'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER, 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password(username, password)
(channel, (st_size, _, _, _)) = session.scp_recv(sourceFilePath, True)
destination = open(destinationFilePath, 'wb')
got = 0
while got < st_size:
data = channel.read(min(st_size - got, 1024))
got += len(data)
destination.write(data)
exitStatus = channel.get_exit_status()
channel.close()
这篇关于如何使用python 3.2使用scp发送文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!