首页 > 解决方案 > 如何使用 Python 列出远程主机目录中的文件?

问题描述

我需要从远程主机目录中获取文件列表,在我的本地机器上运行代码。

类似于os.listdir()远程主机上,而不是os.lisdir()在运行 python 代码的本地机器上。

在 bash 中,此命令有效 ssh user@host "find /remote/path/ -name "pattern*" -mmin -15" > /local/path/last_files.txt

标签: pythonoperating-system

解决方案


在远程机器上运行命令的最佳选择是通过带有paramiko的 ssh 。

关于如何使用库并向远程系统发出命令的几个示例:

import base64
import paramiko

# Let's assign an RSA SSH key to the 'key' variable
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))

# And create a client instance.
client = paramiko.SSHClient()

# Create an object to store our key  
host_keys = client.get_host_keys()
# Add our key to 'host_keys'
host_keys.add('ssh.example.com', 'ssh-rsa', key)

# Connect to our client; you will need 
# to know/use for the remote account:
#
#   IP/Hostname of target
#   A username 
#   A password
client.connect('IP_HOSTNAME', username='THE_USER', password='THE_PASSWORD')

# Assign our input, output and error variables to
# to a command we will be issuing to the remote 
# system 
stdin, stdout, stderr = client.exec_command(
    'find /path/data/ -name "pattern*" -mmin -15'
)

# We iterate over stdout
for line in stdout:
    print('... ' + line.strip('\n'))

# And finally we close the connection to our client
client.close()

正如 OP 所指出的,如果我们在本地已经有一个已知的 hosts 文件,我们可以做一些稍微不同的事情:

import base64
import paramiko

# And create a client instance.
client = paramiko.SSHClient()

# Create a 'host_keys' object and load
# our local known hosts  
host_keys = client.load_system_host_keys()

# Connect to our client; you will need 
# to know/use for the remote account:
#
#   IP/Hostname of target
#   A username 
#   A password
client.connect('IP_HOSTNAME', username='THE_USER', password='THE_PASSWORD')

# Assign our input, output and error variables to
# to a command we will be issuing to the remote 
# system 
stdin, stdout, stderr = client.exec_command(
    'find /path/data/ -name "pattern*" -mmin -15'
)

# We iterate over stdout
for line in stdout:
    print('... ' + line.strip('\n'))

# And finally we close the connection to our client
client.close()

推荐阅读