1. paramiko set_keepalive源码
def set_keepalive(self, interval):
"""
Turn on/off keepalive packets (default is off). If this is set, after
``interval`` seconds without sending any data over the connection, a
"keepalive" packet will be sent (and ignored by the remote host). This
can be useful to keep connections alive over a NAT, for example.
:param int interval:
seconds to wait before sending a keepalive packet (or
0 to disable keepalives).
"""
def _request(x=weakref.proxy(self)):
return x.global_request("keepalive@lag.net", wait=False)
self.packetizer.set_keepalive(interval, _request)
def global_request(self, kind, data=None, wait=True):
"""
Make a global request to the remote host. These are normally
extensions to the SSH2 protocol.
:param str kind: name of the request.
:param tuple data:
an optional tuple containing additional data to attach to the
request.
:param bool wait:
``True`` if this method should not return until a response is
received; ``False`` otherwise.
:return:
a `.Message` containing possible additional data if the request was
successful (or an empty `.Message` if ``wait`` was ``False``);
``None`` if the request was denied.
"""
if wait:
self.completion_event = threading.Event()
m = Message()
m.add_byte(cMSG_GLOBAL_REQUEST)
m.add_string(kind)
m.add_boolean(wait)
if data is not None:
m.add(*data)
self._log(DEBUG, 'Sending global request "{}"'.format(kind))
self._send_user_message(m)
if not wait:
return None
while True:
self.completion_event.wait(0.1)
if not self.active:
return None
if self.completion_event.is_set():
break
return self.global_response
2. 使用
使用paramiko连接服务器,上传/下载等相关操作
服务器的会话超时设置为5分钟,当sftp一段时间没有交互之后,会出现会话超时,此时在put/get/stat等一切操作时,就会处于等待状态,并不会抛出任何异常。
为了解决这个问题,我认为激活keep alive将是最好的选择,所以我在传输上使用"set_keepalive"将其设置为60秒:
transport = paramiko.Transport((host, port))
transport.connect(username=user, password=pwd)
transport.set_keepalive(60)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_path, remote_path)