Using scp to transfer a single file into a remote folder that doesn't exist
I'm working on a python script that monitors a directory and uploads files that have been created or modified using scp. That's fine, except I want this to be done recursively, and I'm having a problem if a user creates a directory in the watch directory, and then modifies a file inside that new directory.
I can detect the directory creation and file nested file creation/modification just fine. But if I try to upload that file to the remote server, it won't work since the directory on the remote site won't exist. Is there a simple way to do this WITHOUT recursively copying the created directory? I want to avoid this because I don't want to delete the remote folder if it exists.
开发者_JS百科Also, please don't suggest rsync
. It has to only use ssh and scp.
Since you have ssh, can't you just create the directory first? For example, given a file with absolute path /some/path/file.txt, issue a mkdir -p /home/path
before uploading file.txt
.
UPDATE: If you're looking to lower the number of transactions, a better method might be to make a tar file locally, transfer that, and untar it.
While I imagine your specific application will have its own quirks (as does mine), this may put you on the right path. Below is a short snippet from a script I use to put files onto a remote EC2 instance using Fabric built on paramiko. Also note I where I put the sudo commands as Fabric has its own "sudo" class. This is one of those quirks I was referring to. Hope this helps someone.
from fabric.api import env, run, put, settings, cd
from fabric.contrib.files import exists
'''
sudo apt-get install fabric
Initially setup for interaction with an AWS EC2 instance
At the terminal prompt run:
fab ec2 makeRemoteDirectory changePermissions putScript
'''
TARGETPATH = '/your/path/here'
def ec2():
env.hosts = ['your EC2 Instance or remote address']
env.user = 'user_name'
env.key_filename = '/path/to/your/private_key.pem'
def makeRemoteDirectory():
if not exists('%s'%TARGETPATH):
run('sudo mkdir %s'%TARGETPATH)
def changePermissions():
run('sudo chown -R %(user)s:%(user)s %(path)s'%{'user': env.user, 'path': TARGETPATH})
def putScript():
fileName = '/path/to/local/file'
dirName = TARGETPATH
put(fileName, dirName)
It's not exactly scp, but sftp can take the -b
parameter with a batch file. You can send a mkdir and a put.
精彩评论