在下面的函数中,我正在创建 ssh 客户端并尝试将其保存到 django 会话对象。
def create_ssh_client(host, user, password):
client = SSHClient()
client.load_system_host_keys()
client.connect(host,
username=user,
password=password,
timeout=5000,
)
return client
def save_to_session(request):
ssh_client = create_ssh_client(host, user, password)
request.session['ssh_client'] = ssh_client
** 在尝试保存到会话时,出现类型错误 -**
TypeError: Object of type SSHClient is not JSON serializable
任何建议或意见表示赞赏。
在 django 中使用SSHClient
create_ssh_client
函数返回包含有关 SSH 客户端的必要信息的字典:import json
from paramiko import SSHClient
def create_ssh_client(host, user, password):
client = SSHClient()
client.load_system_host_keys()
client.connect(
host,
username=user,
password=password,
timeout=5000,
)
return {
'host': host,
'user': user,
'password': password,
'client': client,
}
def save_to_session(request):
ssh_data = create_ssh_client(host, user, password)
request.session['ssh_client'] = json.dumps(ssh_data)
def use_ssh_client(request):
ssh_data = json.loads(request.session.get('ssh_client', '{}'))
host = ssh_data.get('host')
user = ssh_data.get('user')
password = ssh_data.get('password')
if host and user and password:
client = SSHClient()
client.load_system_host_keys()
client.connect(
host,
username=user,
password=password,
timeout=5000,
)
# Now you can use the 'client' object for your SSH operations.
else:
# Handle the case when SSH client data is not available in the session.