Search code examples
pythonregexsshparamikolistdir

Python Paramiko listdir in multi-hopped SSH


How can I listdir in multi-hopped ssh situation? Or there's other way to get my target file?

def file_lookup():
    for file in os.listdir('/var/log/rsyslog/firewall-a/'):
        if fnmatch.fnmatch(file, 'syslog-'+date+'-\d{10}\.gz'):
            global log_file
            log_file = file

def copy_from_log_server_to_bastion():
    ssh_client = paramiko.SSHClient()
    ssh_client.load_host_keys('/home/vagrant/.ssh/known_hosts/')
    ssh_client.connect(bastion_ip, bastion_port, username, password)
    stdin, stdout, stderr = ssh_client.exec_command('scp ' + username + '@' + log_server_ip + ':' + logs_directory + log_file + ' ./')
    stdin.write(password)

def copy_from_bastion_to_local():
    # some codes here

I want my script to copy a file from remote server -> bastion host -> local, but I'm having problem with this multi-hopped ssh.

Here's the network-mapping: (https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2017/11/15/NM_diagram_061316_a1.png)

Sorry that I have not enough reputation to append image in post.


Solution

  • I'd modified my second function code into this, third function is unnecessary, and now it works:

    def copy_from_log_server_to_local(log_client):
        os.mkdir('/vagrant/Logs/' + datetime.today().strftime('%m%d'))    
        scp_client = SCPClient(log_client.get_transport())
        scp_client.get('/var/log/rsyslog/firewall-a/'+log_file, '/vagrant/Logs/' + datetime.today().strftime('%m%d') + '/')
        scp_client.close()
    

    log_client has channel opened with my bastion host