我正在尝试使用 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 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b3924243f0b7a7273657a73657a657a" rel="noreferrer noopener nofollow">[email protected]</a>:/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
总是给我最新的时间戳文件夹。但是,如果该文件夹中不存在 email_summary.log
文件,我想查看包含文件 email_summary.log
的下一个最新时间戳文件夹。
本质上,scp 包含文件“email_summary.log”的最新时间戳文件夹中的文件。有人可以帮我解决这个问题吗?
提前致谢。
最佳答案
在远程计算机上执行 scp
命令将文件推送回本地计算机是一种矫枉过正的做法。一般来说,依赖 shell 命令是非常脆弱的方法。您最好仅使用 native 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')
以上内容基于:
- How to download only the latest file from SFTP server with Paramiko?
- Paramiko get sorted directory listing
附注:请勿使用 AutoAddPolicy
。这样做你就会失去安全感。请参阅Paramiko "Unknown Server" 。
关于python - 如何在 Linux 中获取包含感兴趣的特定文件的最新文件夹并在 Python 中使用 Paramiko 下载该文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218092/