我有一些Python代码使用Paramiko从远程服务器获取构建文件:
def setup_sftp_session(self, host='server.com', port=22, username='puppy'):
self.transport = paramiko.Transport((host, port))
privatekeyfile = os.path.expanduser('~/.ssh/id_dsa')
try:
ssh_key = paramiko.DSSKey.from_private_key_file(privatekeyfile)
except IOError, e:
self.logger.error('Unable to find SSH keyfile: %s' % str(e))
sys.exit(1)
try:
self.transport.connect(username = username, pkey = ssh_key)
except paramiko.AuthenticationException, e:
self.logger.error("Unable to logon - are you sure you've added the pubkey to the server?: %s" % str(e))
sys.exit(1)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
self.sftp.chdir('/some/location/buildfiles')
def get_file(self, remote_filename):
try:
self.sftp.get(remote_filename, 'I just want to save it in the local cwd')
except IOError, e:
self.logger.error('Unable to find copy remote file %s' % str(e))
def close_sftp_session(self):
self.sftp.close()
self.transport.close()
我想检索每个文件,并将其存放在当前的本地工作目录中。
然而,Paramiko似乎没有这个选项 - 您需要指定完整的本地目的地。您甚至无法指定目录(例如“./”,甚至“/ home / victorhooi / files”) - 您需要包含文件名的完整路径。
这有什么办法吗?如果我们必须指定本地文件名,而不是仅仅复制远程文件名,那将会很烦人。
另外 - 我在setup_sftp_session中使用exit(1)处理异常的方式是一种很好的做法,还是有更好的方法?
干杯, 维克多
答案 0 :(得分:1)
你必须插入
os.path.join(os.getcwd(), remote_filename)
在函数中调用exit()不是一个好主意。也许您想重用代码并在发生异常时采取一些措施。如果您保持exit()调用,则会丢失。 我建议修改这个函数,以便在成功的情况下返回True,否则返回False。然后呼叫者可以决定做什么。
另一种方法是不捕捉异常。因此调用者必须处理它们,并且调用者获取有关失败情况的完整信息(包括堆栈跟踪)。