Python尝试循环连接服务器,如果连接成功则退出,如果超过3次连接失败则退出

下面是一个使用Python实现的程序,可以实现你描述的功能:通过SSH连接服务器并重启服务器,然后循环尝试连接服务器,如果连接成功则退出,如果超过3次连接失败则退出。

首先,请确保你已经安装了`paramiko`库,它是一个用于SSH连接的Python库。你可以使用`pip install paramiko`命令进行安装。

python 复制代码
import time
import paramiko

def connect_ssh(hostname, port, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        client.connect(hostname=hostname, port=port, username=username, password=password)
        print("SSH连接成功!")
        return client
    except Exception as e:
        print(f"SSH连接失败:{e}")
        return None

def reboot_server(client):
    try:
        _, stdout, _ = client.exec_command("reboot")
        stdout.channel.recv_exit_status()
        print("服务器重启中...")
    except Exception as e:
        print(f"重启服务器失败:{e}")

def check_server_status(hostname):
    max_retries = 3  # 最大重试次数
    retries = 0
    connected = False

    while retries < max_retries:
        try:
            # 尝试连接服务器
            ssh = connect_ssh(hostname, 22, "your_username", "your_password")
            if ssh is not None:
                ssh.close()
                print("成功连接到服务器!")
                connected = True
                break  # 连接成功,跳出循环
            else:
                retries += 1
                time.sleep(10)  # 连接失败,等待10秒后重试
        except Exception as e:
            print(f"连接服务器失败:{e}")
            retries += 1
            time.sleep(10)  # 连接失败,等待10秒后重试

    if not connected:
        print(f"连接服务器失败超过 {max_retries} 次,程序退出。")

# 服务器信息
server_hostname = "your_server_hostname_or_ip"

# SSH连接和重启服务器
print("正在连接服务器...")
ssh_client = connect_ssh(server_hostname, 22, "your_username", "your_password")
if ssh_client is not None:
    print("成功连接到服务器!")
    print("正在重启服务器...")
    reboot_server(ssh_client)
    ssh_client.close()

# 循环尝试连接服务器
print("正在尝试连接服务器...")
check_server_status(server_hostname)

请注意替换以下参数:

  • `your_server_hostname_or_ip`:目标服务器的主机名或IP地址。

  • `your_username`:SSH连接使用的用户名。

  • `your_password`:SSH连接使用的密码。

在这个示例中,我们首先通过SSH连接服务器并重启服务器,然后循环尝试连接服务器。如果连接成功,则打印成功消息并退出。如果超过3次连接失败,则打印失败消息并退出。

相关推荐
vyuvyucd10 分钟前
Qwen-1.8B-Chat昇腾Atlas800TA2部署实战
python
轻竹办公PPT15 分钟前
2026 年工作计划 PPT 内容拆解,对比不同 AI 生成思路
人工智能·python·powerpoint
癫狂的兔子28 分钟前
【Python】【Flask】抽奖功能
开发语言·python·flask
linuxxx1101 小时前
python变量引用的小案例
python
2501_936146041 小时前
烟草叶片病害检测_YOLO11-C3k2-MSBlock模型详解
python
Data_agent1 小时前
Python 编程实战:函数与模块化编程及内置模块探索
开发语言·python
十铭忘1 小时前
windows系统python开源项目环境配置1
人工智能·python
Generalzy2 小时前
langchain deepagent框架
人工智能·python·langchain
栈与堆2 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
万行2 小时前
机器学习&第二章线性回归
人工智能·python·机器学习·线性回归