Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

linux - How I open remote server folder using python?

How to Open the remote server folder > inside the folder only images store we read all the images.

Server is Linux server

import paramiko
import sys
import os

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<server-Ip-address>', username='******', password='******')

ftp = ssh.open_sftp()
#filea = ftp.get('/var/www/folder_image/', '#')
#Here coded how we open the dir and read one by one all images property(name,size,path,etc.)
ftp.close()

I used this code

So please kindly reply

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To download all files from a remote folder over ssh, you could use ftp.listdir() to list the files followed by ftp.get() for each file:

#!/usr/bin/env python
import os
import sys
from contextlib import closing

from paramiko import SSHConfig, SSHClient

# specify hostname to connect to and the remote/local paths
hostname, remote_dirname, destdir = sys.argv[1:]

# load parameters to setup ssh connection
config = SSHConfig()
with open(os.path.expanduser('~/.ssh/config')) as config_file:
    config.parse(config_file)
d = config.lookup(hostname)

# connect
with closing(SSHClient()) as ssh:
    ssh.load_system_host_keys() #NOTE: no AutoAddPolicy() 
    ssh.connect(d['hostname'], username=d.get('user'))
    with closing(ssh.open_sftp()) as sftp:
        # cd into remote directory
        sftp.chdir(remote_dirname)
        # cd to local destination directory
        os.chdir(destdir)
        # download all files in it to destdir directory
        for filename in sftp.listdir():
            sftp.get(filename, filename)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...