pythonauthenticationsftp.netrc

re-load variables during script


I have a script which I am using to connect to a sftp server and download some files, the catch is I need to do this for multiple users (7 in total). I have got this working but I am basicly repeating myself 7 times to get this to work (I just put three in the example below). what I want to do is get the script to re-check the Hostname variable after each session is closed. is there a way to do that without overwritting it each time?

Here is what I have so far:

import pysftp
`
import netrc
`
"""
This imports from three different directories which are owned by different users.
it logs in as a user, downloads their files, closes the connection and then opens another with the other user.
it uses login details from the .netrc files to pull the usernames.
it is a bit clunky repeating all this code three times, there must be a better way but it works.
"""

#I am using netrc to conseal the login details from easy access
secrets = netrc.netrc()
Host = "ubuntu-test"

user = "user1"
username, account, password = secrets.authenticators(user)
sftp = pysftp.Connection(Host,username=username, password=password)
sftp.get_d("/foo", "/home/Documents", preserve_mtime=True)
sftp.close

user = "user2"
#If I take out the next line it still uses the user details from the previous section.
username, account, password = secrets.authenticators(user)
sftp = pysftp.Connection(Host, username=username, password=password)
sftp.get_d("/foo", "/home/Documents", preserve_mtime=True)
sftp.close()

user = "user3"
username, account, password = secrets.authenticators(user)
sftp = pysftp.Connection(Host, username=username, password=password)
sftp.get_d("/foo", "/home/Documents", preserve_mtime=True)
sftp.close()

*Edit1

Following suggestions I have reformated it as a function and that does exactly what i wanted, so now it is:

def download(login, file):
    username, account, password = secrets.authenticators(login)
    sftp = pysftp.Connection(server, username=username, password=password)
    sftp.get_d(file, destination, preserve_mtime=True)
    sftp.close()

download("<login>", "/foo")

Solution

  • Following suggestions I have reformated it as a function and that does exactly what i wanted, so now it is:

    def download(login, file):
        username, account, password = secrets.authenticators(login)
        sftp = pysftp.Connection(server, username=username, password=password)
        sftp.get_d(file, destination, preserve_mtime=True)
        sftp.close()
    
    download("<login1>", "/foo")
    download("<login2>", "/foo")
    download("<login3>", "/foo")