2014-05-16 33 views
0

它的缺点是,我需要一个程序,通过sftp将本地目录中的所有txt文件上传到特定的远程目录。如果我从sftp命令行运行mput * .txt,而im已经在正确的本地目录中,那么这就是我正在拍摄的内容。Python代码,子进程使用glob吗?

这里是代码即时尝试。没有错误,当我运行它,但没有结果要么当我sftp到服务器和ls的上传目录,它的空。我可能会一起吠叫错误的树。我看到其他的解决方案,比如在bash中使用mget的lftp ...但我真的希望这可以与python一起使用。无论如何,我还有很多东西需要学习。这是几天后读到关于一些stackoverflow用户的建议,几个图书馆可能会有所帮助。即时通讯不知道我可以用“子进程”来做“所有文件中的我:”。

import os 
import glob 
import subprocess 

os.chdir('/home/submitid/Local/Upload') #change pwd so i can use mget *.txt and glob similarly 

pwd = '/Home/submitid/Upload' #remote directory to upload all txt files to 

allfiles = glob.glob('*.txt') #get a list of txt files in lpwd 

target="[email protected]" 


sp = subprocess.Popen(['sftp', target], shell=False, stdin=subprocess.PIPE) 


sp.stdin.write("chdir %s\n" % pwd) #change directory to pwd 

for i in allfiles: 
    sp.stdin.write("put %s\n" % allfiles) #for each file in allfiles, do a put %filename to pwd 

sp.stdin.write("bye\n")  


sp.stdin.close() 

回答

0

当你遍历allfiles,你是不是传递迭代变量sp.stdin.write,但allfiles本身。它应该是

for i in allfiles: 
    sp.stdin.write("put %s\n" % i) #for each file in allfiles, do a put %filename to pwd 

在发出命令之前,您可能还需要等待sftp进行身份验证。你可以从这个过程读取标准输出,或者只是在你的代码中加入一些延迟。

但是,为什么不只是使用scp并构建完整的命令行,然后检查它是否成功执行?喜欢的东西:

result = os.system('scp %s %s:%s' % (' '.join(allfiles), target, pwd)) 
if result != 0: 
    print 'error!' 
+0

DANG工作!现在,如果我只能摆脱密码提示。我将不得不阅读时间。睡觉...谢谢你! – Dogbyte

+0

@Dogbyte您可能会更好使用SSH公钥身份验证来绕过密码。请参阅http://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication –

+0

关于SSH公钥认证,我不知道我有这种级别的访问远程服务器,这是向医疗保健提供者发送EDI交易。他们只允许基本的sftp命令。 – Dogbyte

0

你不需要遍历allfiles

sp.stdin.write("put *.txt\n") 

就足够了。您指示sftp将所有文件一次放入,而不是逐个放入。