Linuxでの関心のある特定のファイルが含まれている最新のフォルダを取得し、PythonでParamikoを使用してそのファイルをダウンロードするには?

アイラ:

私は、Python 3にParamikoを使用して、私のローカルマシンにリモートサーバから特定のファイルをSCPにしようとしています。

背景:ディレクトリがあるmydir名前で始まり、多くのタイムスタンプディレクトリが含まれている宛先マシン198.18.2.2には、2020...

宛先マシン: 198.18.2.2

ソースマシン: 198.18.1.1

これまでのところ、私は次のように実行するコマンドを構築するために管理しています -

cd "$(ls -1d /mydir/20* | tail -1)"; scp -o StrictHostKeyChecking=no email_summary.log [email protected]:/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

基本的に、ファイル「email_summary.log」が含まれ、最新のタイムスタンプフォルダからファイルをscpコマンド。缶誰かがこれで私を助けてください?

前もって感謝します。

マーティンPrikryl:

実行scpするために、リモートマシン上でコマンドを押して、ローカルマシンにファイルバックすることは行き過ぎです。そして、一般的には、シェルコマンドに依存することは非常に壊れやすいアプローチです。あなたはより良い最新のリモートファイルを識別し、する、唯一のネイティブ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 the next folder')

上記に基づいています。


サイドノート:DOは使用しませんAutoAddPolicyあなたはそうすることによって、セキュリティを失います。参照してくださいParamiko「不明サーバー」

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=7435&siteId=1