![](/img/trans.png)
[英]How to get the latest created file name and not the folder name using python?
[英]How to get the latest folder that contains a specific file of interest in Linux and download that file using Paramiko in Python?
我正在嘗試在 Python 3 中使用 Paramiko 將特定文件從遠程服務器 scp 到我的本地計算機。
背景:目標機器198.18.2.2上有一個目錄mydir
,里面有很多以2020...
目標機器: 198.18.2.2
源機器: 198.18.1.1
到目前為止,我已經設法構建要執行的命令,如下所示 -
cd "$(ls -1d /mydir/20* | tail -1)"; scp -o StrictHostKeyChecking=no email_summary.log root@198.18.1.1:/mydir/work/logs/email_summary_198.18.2.2.log
代碼:
def remote_execute(dest_ip, cmd):
"""API to execute command on remote machine"""
result = []
sys.stderr = open('/dev/null')
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh_client.connect(dest_ip, username='root')
stdin, stdout, stderr = ssh_client.exec_command(cmd)
for line in stdout.readlines():
result.append(line.strip())
ssh_client.close()
return result
except paramiko.AuthenticationException:
print("Authentication with the remote machine failed")
return
except paramiko.SSHException:
print("Connection to remote machine failed")
return
except paramiko.BadHostKeyException:
print("Bad host key exception for remote machine")
return
調用: remote_execute('198.18.1.1', cmd)
問題是ls -1d /mydir/20* | tail -1
ls -1d /mydir/20* | tail -1
總是給我最新的時間戳文件夾。 但是,如果該文件夾中不存在email_summary.log
文件,我想查看下一個包含文件email_summary.log
的最新時間戳文件夾。
本質上,scp 來自包含文件“email_summary.log”的最新時間戳文件夾中的文件。 有人可以幫我嗎?
提前致謝。
在遠程機器上執行scp
命令將文件推送回本地機器是一種矯枉過正的做法。 並且通常依賴 shell 命令是非常脆弱的方法。 您最好只使用本機 Python 代碼,以識別最新的遠程文件並將其拉到本地機器。 您的代碼將更加健壯和可讀。
sftp = ssh.open_sftp()
sftp.chdir('/mydir')
files = sftp.listdir_attr()
dirs = [f for f in files if S_ISDIR(f.st_mode)]
dirs.sort(key = lambda d: d.st_mtime, reverse = True)
filename = 'email_summary.log'
for d in dirs:
print('Checking ' + d.filename)
try:
path = d.filename + '/' + filename
sftp.stat(path)
print('File exists, downloading...')
sftp.get(path, filename)
break
except IOError:
print('File does not exist, will try the next folder')
以上是基於:
附注:不要使用AutoAddPolicy
。 這樣做會失去安全感。 請參閱Paramiko“未知服務器” 。
使用find
文件(而不是目錄)怎么樣?
find /mydir/20* -name email_summary.log | sort | tail -1
這將為您提供要復制的最新文件的路徑。
因此,您的命令將如下所示:
scp -o StrictHostKeyChecking=no "$(find /mydir/20* -name email_summary.log | sort | tail -1)" root@198.18.1.1:/mydir/work/logs/email_summary_198.18.2.2.log
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.