我正在开发一个简单的工具,它将文件传输到硬编码的位置,密码也是硬编码的。我是一个python新手,但多亏了ftplib,很容易:

import ftplib

info= ('someuser', 'password')    #hard-coded

def putfile(file, site, dir, user=(), verbose=True):
    """
    upload a file by ftp to a site/directory
    login hard-coded, binary transfer
    """
    if verbose: print 'Uploading', file
    local = open(file, 'rb')    
    remote = ftplib.FTP(site)   
    remote.login(*user)         
    remote.cwd(dir)
    remote.storbinary('STOR ' + file, local, 1024)
    remote.quit()
    local.close()
    if verbose: print 'Upload done.'

if __name__ == '__main__':
    site = 'somewhere.com'            #hard-coded
    dir = './uploads/'                #hard-coded
    import sys, getpass
    putfile(sys.argv[1], site, dir, user=info)

问题是我找不到任何支持sFTP的库。安全地做这样的事情的正常方法是什么?

编辑:感谢这里的答案,我已经让它与Paramiko合作,这就是语法。

import paramiko

host = "THEHOST.com"                    #hard-coded
port = 22
transport = paramiko.Transport((host, port))

password = "THEPASSWORD"                #hard-coded
username = "THEUSERNAME"                #hard-coded
transport.connect(username = username, password = password)

sftp = paramiko.SFTPClient.from_transport(transport)

import sys
path = './THETARGETDIRECTORY/' + sys.argv[1]    #hard-coded
localpath = sys.argv[1]
sftp.put(localpath, path)

sftp.close()
transport.close()
print 'Upload done.'

再次感谢!

有帮助吗?

解决方案

Paramiko 支持SFTP。我用过它,而且我用过Twisted。两者都有它们的位置,但你可能会发现从Paramiko开始更容易。

其他提示

你应该查看pysftp https://pypi.python.org/pypi/pysftp 它取决于paramiko,但将最常见的用例包含在几行代码中。

import pysftp
import sys

path = './THETARGETDIRECTORY/' + sys.argv[1]    #hard-coded
localpath = sys.argv[1]

host = "THEHOST.com"                    #hard-coded
password = "THEPASSWORD"                #hard-coded
username = "THEUSERNAME"                #hard-coded

with pysftp.Connection(host, username=username, password=password) as sftp:
    sftp.put(localpath, path)

print 'Upload done.'

如果您想要简单易用,您可能还需要查看 Fabric 。它是一个自动化的部署工具,如Ruby的Capistrano,但更简单,当然也适用于Python。它建立在Paramiko之上。

你可能不想做'自动部署',但Fabric完全适合你的用例。为了向您展示Fabric的简单性:您的脚本的fab文件和命令将如下所示(未经过测试,但99%确定它可以正常工作):

fab_putfile.py:

from fabric.api import *

env.hosts = ['THEHOST.com']
env.user = 'THEUSER'
env.password = 'THEPASSWORD'

def put_file(file):
    put(file, './THETARGETDIRECTORY/') # it's copied into the target directory

然后使用fab命令运行该文件:

fab -f fab_putfile.py put_file:file=./path/to/my/file

你已经完成了! :)

以下是使用pysftp和私钥的示例。

import pysftp

def upload_file(file_path):

    private_key = "~/.ssh/your-key.pem"  # can use password keyword in Connection instead
    srv = pysftp.Connection(host="your-host", username="user-name", private_key=private_key)
    srv.chdir('/var/web/public_files/media/uploads')  # change directory on remote server
    srv.put(file_path)  # To download a file, replace put with get
    srv.close()  # Close connection

pysftp是一个易于使用的sftp模块,它使用paramiko和pycrypto。它提供了一个简单的sftp接口。你可以用pysftp做的其他事情非常有用:

data = srv.listdir()  # Get the directory and file listing in a list
srv.get(file_path)  # Download a file from remote server
srv.execute('pwd') # Execute a command on the server

更多命令和关于PySFTP 此处

Twisted 可以帮助您完成工作,查看他们的文档,有很多示例。它也是一个成熟的产品,背后有一个庞大的开发者/用户社区。

您可以使用 pexpect模块

这是一个很好的介绍帖子

child = pexpect.spawn ('/usr/bin/sftp ' + user@ftp.site.com )
child.expect ('.* password:')
child.sendline (your_password)
child.expect ('sftp> ')
child.sendline ('dir')
child.expect ('sftp> ')
file_list = child.before
child.sendline ('bye')

我没有对此进行测试,但它应该可以正常工作

帕拉米科太慢了。使用subprocess和shell,这是一个例子:

remote_file_name = "filename"
remotedir = "/remote/dir"
localpath = "/local/file/dir"
    ftp_cmd_p = """
    #!/bin/sh
    lftp -u username,password sftp://ip:port <<EOF
    cd {remotedir}
    lcd {localpath}
    get {filename}
    EOF
    """
subprocess.call(ftp_cmd_p.format(remotedir=remotedir,
                                 localpath=localpath,
                                 filename=remote_file_name 
                                 ), 
                shell=True, stdout=sys.stdout, stderr=sys.stderr)

使用RSA密钥,然后参考此处

段:

import pysftp
import paramiko
from base64 import decodebytes

keydata = b"""L+WsiL5VL51ecJi3LVjmblkAdUTU+xbmXmUArIU5+8N6ua76jO/+T""" 
key = paramiko.RSAKey(data=decodebytes(keydata)) 
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add(host, 'ssh-rsa', key)


with pysftp.Connection(host=host, username=username, password=password, cnopts=cnopts) as sftp:   
  with sftp.cd(directory):
    sftp.put(file_to_sent_to_ftp)

有很多答案提到pysftp,所以如果你想要一个围绕pysftp的上下文管理器包装器,这里有一个解决方案甚至更少的代码,在使用时最终看起来如下

path = "sftp://user:p@ssw0rd@test.com/path/to/file.txt"

# Read a file
with open_sftp(path) as f:
    s = f.read() 
print s

# Write to a file
with open_sftp(path, mode='w') as f:
    f.write("Some content.") 

(更全面的)示例: http:/ /www.prschmid.com/2016/09/simple-opensftp-context-manager-for.html

如果你第一次无法连接,这个上下文管理器碰巧有自动重试逻辑(这种情况比你在生产环境中预期的更频繁发生......)

open_sftp 的上下文管理器要点: https://gist.github的.com / prschmid / 80a19c22012e42d4d6e791c1e4eb8515

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top