Django 接口触发 SSH 脚本卡住问题排查及解决方法
这段代码中的问题可能是由于'client.exec_command(script_command)'执行的命令没有正常结束,导致终端卡住了。可能的原因包括:
- 'script_command'中的脚本命令没有正确执行完毕,导致没有返回结果。
- 'script_command'中的脚本命令执行时间过长,导致终端一直等待返回结果。
- 'script_command'中的脚本命令在执行过程中出现了错误,没有返回结果。
为了调试这个问题,你可以尝试以下方法:
- 检查'script_command'中的脚本命令是否正确,是否可以在终端中手动执行并返回结果。
- 尝试将'script_command'中的脚本命令修改为简单的命令,例如'ls',看是否可以正常返回结果。
- 检查'script_command'中的脚本命令是否需要输入额外的参数或环境变量,以确保命令可以正确执行。
- 尝试增加超时参数来限制命令执行的时间,例如'client.exec_command(script_command, timeout=10)',如果命令执行时间超过10秒则自动结束。
- 检查'script_command'中的脚本命令是否有输出重定向或后台执行等特殊操作,这些操作可能导致命令没有返回结果。
如果以上方法都没有解决问题,你可以尝试使用'invoke_shell()'方法来执行命令并实时获取输出,以便更好地调试和定位问题。以下是一个示例:
def start_script_via_ssh(hostname=settings.AUTODL_INSTANCE_HOSTNAME,
port=settings.AUTODL_INSTANCE_PORT,
username=settings.AUTODL_INSTANCE_USERNAME,
password=settings.AUTODL_INSTANCE_PASSWORD,
script_command='bash /root/init/start.sh; exit'):
# 创建 SSH 客户端对象
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接 SSH 服务器
client.connect(hostname=hostname, port=int(port),
username=username, password=password)
print('client', client)
try:
# 打开一个新的 Channel
channel = client.invoke_shell()
# 执行启动脚本命令
channel.send(script_command + '\n')
# 逐行读取输出
while True:
if channel.recv_ready():
output = channel.recv(1024).decode()
print(output, end='')
if channel.exit_status_ready():
break
finally:
# 关闭 SSH 连接
client.close()
通过使用'invoke_shell()'方法和循环读取输出,可以实时获取命令的输出,并在命令执行完毕后退出循环,以避免终端卡住。
原文地址: https://www.cveoy.top/t/topic/lXfW 著作权归作者所有。请勿转载和采集!