6

我正在努力server 1。我需要编写一个 Python 脚本,我需要在其中连接到 aserver 2并从一个目录中获取某些文件(名称以字母“HM”开头的文件)并将它们放入另一个目录中,该目录需要在运行时创建(因为对于程序的每次运行,都必须创建一个新目录,并且必须将文件转储到那里),在server 1.

我需要在 Python 中执行此操作,而且我对这种语言比较陌生。我不知道从哪里开始编写代码。是否有不涉及“压缩”文件的解决方案?我已经查看了 Paramiko,但据我所知,它一次只传输一个文件。我什至看过 glob,但我不知道如何使用它。

4

4 回答 4

4

传输您可能想要查看 paramiko 的文件

import os
import paramiko

localpath = '~/pathNameForToday/'
os.system('mkdir ' + localpath)
ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.get(remotepath, localpath)
sftp.close()
ssh.close() 

我你想使用 glob 你可以这样做:

import os
import re
import glob

filesiwant = re.compile('^HM.+') #if your files follow a more specific pattern and you don't know regular expressions you can give me a sample name and i'll give you the regex4it
path = '/server2/filedir/'
for infile in glob.glob( os.path.join(path, '*') ):
    if filesiwant.match(infile):
         print "current file is: " + infile

否则一个更简单的选择是使用 os.listdir()

import os
for infile in os.listdir('/server2/filedir/'):
    ...`

这是否回答你的问题?如果没有发表评论

于 2012-10-11T05:31:57.990 回答
1

Python 不会是我执行此任务的首选,但您可以使用对系统的调用并运行 mkdir 和 rsync。特别是你可以做

import os
os.system("mkdir DIRECTORY")
os.system("rsync -cav user@server2:/path/to/files/HM* DIRECTORY/")
于 2012-10-11T04:11:38.920 回答
0

你可以使用fabric. fabfile.py在 server1 上创建:

import os
from fabric.api import get, hosts

@hosts('server2')
def download(localdir):
    os.makedirs(localdir)  # create dir or raise an error if it already exists 
    return get('/remote/dir/HM*', localdir)  # download HM files to localdir

并运行:fab download:/to/dir从 shell 中的同一目录(fabfile.pyis to fabas Makefileis to make)。

于 2012-10-11T04:11:48.367 回答
0

只需使用 ssh 和 tar。无需涉及 Python

$ ssh server2 tar cf - HM* | tar xf -

远程 tar 可以通过管道直接进入本地 tar

于 2012-10-11T05:00:54.697 回答