我正在研究一种简单的工具,它将文件传输到硬编码的位置,密码也是硬编码的.我是一个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 .