如何通过python从远程服务器获取最新的三个文件?

2024-04-20 06:52:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我用shell脚本touch.sh在服务器test2上创建了十个文件:

root@test2:/sites/buildglasses-qa.walmart.com/ftp/walmart# cat touch.sh 
for i in {1..10}
do 
    touch WMI_Order_Req_409313_$i.xml
    sleep 1
done

root@test2:/sites/buildglasses-qa.walmart.com/ftp/walmart# ls 
touch.sh                     WMI_Order_Req_409313_2.xml  WMI_Order_Req_409313_5.xml  WMI_Order_Req_409313_8.xml
WMI_Order_Req_409313_10.xml  WMI_Order_Req_409313_3.xml  WMI_Order_Req_409313_6.xml  WMI_Order_Req_409313_9.xml
WMI_Order_Req_409313_1.xml   WMI_Order_Req_409313_4.xml  WMI_Order_Req_409313_7.xml

服务器test可以通过ssh连接到远程服务器test2,无需密码提示。
我想在测试时从远程服务器test2获取最新的三个文件。

使用Farbic:
下面是我对farbic的处理。我遇到了一个问题。
谁能用farbicsubprocess或更好的方法给我解题?谢谢。你知道吗

root@test:~# cat fabfile.py 
#!/usr/bin/env python
#-*- coding:utf8 -*-

from fabric.api import *
from fabric.contrib.project import rsync_project

env.user = 'root'
env.host_string =  "test2"


def getremote():
    code_dir = '/sites/buildglasses-qa.walmart.com/ftp/walmart'
    with cd(code_dir):
        cmd = '''ls -lt WMI_Order_Req* |sed -n '1,3p' |awk '{print $9}' |tr "\n" " ";echo'''
        output = run(cmd)
        print output
        get(output,'/tmp')

getremote()

enter image description here

使用Python:

root@test:~# cat get.py
#!/usr/bin/env python
#-*- coding:utf8 -*-
# Power by will yu2016-09-06 10:49:06

import subprocess
import os

cmd="ls -t /sites/buildglasses-qa.walmart.com/ftp/walmart/WMI_Order_Req_*|head -2"
ssh = subprocess.Popen(["ssh", "test2", cmd], shell=False,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
print result

enter image description here 我很难过。我不知道下一步该怎么办。你知道吗


Tags: 服务器comftporderrootxmlwmiqa