【问题标题】:How I can list files from REMOTE HOST directory using Python? [closed]如何使用 Python 列出远程主机目录中的文件? [关闭]
【发布时间】:2019-04-13 12:42:13
【问题描述】:

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

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

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

【问题讨论】:

  • 听起来像你想要的os.listdir()
  • 类似于os.listdir(),但在主机中,而不是在运行代码的本地机器中
  • 如果我的回答有帮助,请标记为已接受,以便其他人知道他们可以使用此信息。谢谢

标签: python operating-system


【解决方案1】:

在远程机器上运行命令的最佳选择是通过带有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()

【讨论】:

  • 谢谢。这对我有用。只需要更改 rsa 密钥。我最终使用client.load_system_host_keys() 使用本地已知主机,因为在我的情况下它更容易,因为我将它们加载到我的环境中。
  • 很高兴为您提供帮助,欢迎反馈。
  • 这个查找程序是否也搜索子目录?如何返回在父/path/data 目录中而不是data 子目录中的文件的结果?
  • print(stdout) 是否在等待输出?我执行了,似乎没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 2011-03-09
相关资源
最近更新 更多