用于将文件从一台服务器获取到另一台服务器并将它们存储在不同目录中

用于将文件从一台服务器获取到另一台服务器并将它们存储在不同目录中

本文介绍了用于将文件从一台服务器获取到另一台服务器并将它们存储在不同目录中的 Python 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on server 1. I need to write a Python script where I need to connect to a server 2 and get certain files (files whose name begins with the letters 'HM') from a directory and put them into another directory, which needs to be created at the run time (because for each run of the program, a new directory has to be created and the files must be dumped in there), on server 1.

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

I need to do this in Python and I'm relatively new to this language. I have no idea where to start with the code. Is there a solution that doesn't involve 'tarring' the files? I have looked through Paramiko but that just transfers one file at a time to my knowledge. I have even looked at glob but I cannot figure out how to use it.

推荐答案

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

to transfer the files you might wanna check out 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 你可以这样做:

I you wanna use glob you can do this:

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()

otherwise an easier alternative is to use os.listdir()

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

这能回答你的问题吗?如果没有留下评论

does that answer your question? if not leave comments

这篇关于用于将文件从一台服务器获取到另一台服务器并将它们存储在不同目录中的 Python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:59