EC2 Ubuntu服务器SSH连接间歇性失败(仅40%成功率)排查求助
EC2 Ubuntu服务器SSH连接间歇性失败(仅40%成功率)排查求助
我遇到了一个非常诡异的问题:用Python脚本通过os.system执行SSH命令连接EC2上的Ubuntu服务器时,只有40%左右的成功率,剩下的情况都会直接报错“Connection refused”。但我手动在终端执行相同的SSH命令时,从来没有出过问题,而且我确认自己的网络连接是稳定的。
当前使用的Python代码
我用来发起SSH连接的代码如下:
ssh_command = f'ssh -vvv -o StrictHostKeyChecking=no -i {private_key_file} ubuntu@{public_ip}' # 通过子shell执行SSH命令 os.system(ssh_command)
失败时的完整Debug日志
连接失败时,输出的详细Debug日志(敏感信息已用[...]替换):
OpenSSH_9.4p1, LibreSSL 3.3.6 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 21: include /etc/ssh/ssh_config.d/* matched no files debug1: /etc/ssh/ssh_config line 54: Applying options for * debug2: resolve_canonicalize: hostname [...] is address debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> '/Users/scott/.ssh/known_hosts' debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> '/Users/scott/.ssh/known_hosts2' debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling debug3: ssh_connect_direct: entering debug1: Connecting to [...] [[...]] port 22. debug3: set_sock_tos: set socket 3 IP_TOS 0x48 debug1: connect to address [...] port 22: Connection refused ssh: connect to host [...] port 22: Connection refused
环境信息
- 本地系统:MacOS 14.2.1
- 目标服务器:AWS EC2上的Ubuntu服务器
已确认的信息/疑惑
- 手动执行完全相同的SSH命令,100%能成功连接,说明服务器的22端口是正常开放的,密钥、主机地址都没有问题
- 查过很多类似问题,大多是完全能连或完全连不上的情况,这种间歇性成功的场景很少见
- 已经关闭了
StrictHostKeyChecking,排除了已知主机密钥的问题
有没有大佬能帮我分析下,为什么脚本执行会出现这种间歇性的连接被拒绝的情况?可能的排查方向是什么?
备注:内容来源于stack exchange,提问作者BigMistake
相关产品推荐
相关产品推荐

