python - 如何使用 Python 列出远程主机目录中的文件?
问题描述
我需要从远程主机目录中获取文件列表,在我的本地机器上运行代码。
类似于os.listdir()
在远程主机上,而不是os.lisdir()
在运行 python 代码的本地机器上。
在 bash 中,此命令有效
ssh user@host "find /remote/path/ -name "pattern*" -mmin -15" > /local/path/last_files.txt
解决方案
在远程机器上运行命令的最佳选择是通过带有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()
推荐阅读
- tortoisegit - 如何使用 TortoiseGit 从远程 git 存储库中获取笔记?
- c# - 无效的密钥哈希。我通过facebook登录游戏时出错
- javascript - Vue.js @click 只注册了一半的时间
- python - 尝试将 tkinter 中的图像正确显示到类的方法中
- go - go rpc 内存泄漏还是不了解?
- ruby - 更新 Ruby Mac OS 10.6.8 Snow Leopard
- javascript - (Javascript) 需要帮助将对象转换为数组
- amazon-web-services - Kinesis 到 S3 自定义分区
- r - 在列表中包含列表
- angularjs - Jasmine - 如何为具有命名属性和对象的数组编写测试