【发布时间】:2020-04-28 14:36:12
【问题描述】:
各位,
我在重新启动后尝试重新连接到服务器时遇到了问题。我看到了其他关于类似问题的文章,但我尝试的所有操作都出现了相同的错误。
目标
重启后自动重新连接服务器
脚本
ssh_client = SSHClient()
ssh_client.set_missing_host_key_policy(AutoAddPolicy())
ssh_client.connect(hostname=host,port=port, username=user, password=psw)
s = ssh_client.get_transport().open_session()
agent.AgentRequestHandler(s)
try:
stdin, stdout, stderr = ssh_client.exec_command(command, get_pty= True)
get_output(stdout)
channel = stdout.channel
stdin.close()
channel.shutdown_write()
stdout_chunks = []
stdout_chunks.append(channel.recv(len(channel.in_buffer)))
while not channel.closed or channel.recv_ready() or channel.recv_stderr_ready():
got_chunk = False
readq, _, _ = select.select([stdout.channel], [], [])
for c in readq:
if c.recv_ready():
stdout_chunks.append(channel.recv(len(c.in_buffer)))
got_chunk = True
if c.recv_stderr_ready():
stderr.channel.recv_stderr(len(c.in_stderr_buffer))
got_chunk = True
if not got_chunk \
and channel.exit_status_ready() \
and not channel.recv_stderr_ready() \
and not channel.recv_ready():
channel.shutdown_read()
channel.close()
break
stdout.close()
stderr.close()
except (ConnectionResetError, SSHException):
print('Connection died')
错误被try catch块缓存:
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
Connection died
我在远程服务器上运行的脚本以重启命令结束:
/sbin/shutdown -r now
【问题讨论】:
-
您的代码 sn-p 缺少尝试。它在哪里?尝试将其放在
ssh_client.connect()之外,以确保您从头开始重新建立连接。 -
只是复制粘贴错误。将编辑我的帖子。如您所见,它在@Hannu 之外
-
重启后,通常需要启动httpd服务和mysql服务才能使web服务器正常运行。检查是否是您的情况。
-
这两个服务在每次重启后都会自动启动。我也通过 SSH 连接,据我所知服务器不应该运行 httpd 或 mysqld 以便重新连接。如果我错了,请纠正我:) @Kosem
-
我不明白为什么这两行没有帮助 s=ssh.get_transport().open_session() #get 'ssh' 传输并打开分配给 's' 变量 paramiko.agent.AgentRequestHandler 的会话(s) #call in 's' 到当前 ssh 会话的转发代理