如何使用Python从REMOTE HOST目录列出文件?

时间:2018-11-09 22:55:36

标签: python operating-system

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

类似于远程主机上的os.listdir(),而不是运行Python代码的本地计算机中的os.lisdir()

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

2 个答案:

答案 0 :(得分:2)

在远程计算机上运行命令的最佳选择是使用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()

答案 1 :(得分:-1)

使用os库,并且:

myfilelist = os.listdir()

或者您可以如下循环浏览文件列表:

for file in os.listdir():
    //do things here