在scrip期间重新加载变量

2021-06-13 13:43:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,我用它连接到一个sftp服务器和下载一些文件,关键是我需要为多个用户(共7个)这样做。我已经让这个工作,但我基本上重复自己7次,使这个工作(我只是把三个在下面的例子)。我要做的是让脚本在每个会话关闭后重新检查Hostname变量。有没有办法做到每次都不覆盖?你知道吗

到目前为止,我掌握的情况如下:

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()

*编辑1

根据以下建议,我将其重新格式化为一个函数,这正是我想要的,所以现在它是:

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")