我有一个脚本,我用来连接到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()
* EDIT1
根据建议,我已将其重新格式化为功能,这完全符合我的要求,现在它是:
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")
答案 0 :(得分:0)
根据建议,我已将其重新格式化为功能,这完全符合我的要求,现在它是:
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")