快速连接服务器脚本 可从多个服务中选择并连接

使用 python 做一个可选择服务器登录连接的脚本

前置条件

  1. 需要有python 环境
  2. python --version 显示版本号即可
  3. 检查 python 是否有 paramiko 包
  4. 没有的话 python install paramiko
  5. 创建一个python 文件,内容如下
# -*- coding: utf-8 -*-

"""
Authors: huxiaohua
Date:    2023/8/17
Time:    2:41 PM
"""
import pexpect

def connect_to_server(hostname, username, password):
    try:
        ssh_cmd = f"ssh {username}@{hostname}"
        child = pexpect.spawn(ssh_cmd)
        child.expect('password:')
        child.sendline(password)

        # 等待终端输出,保持会话
        child.interact()

    except pexpect.ExceptionPexpect as e:
        print("发生错误:", str(e))

def main():
    servers = {
        'Server 1': {
            'hostname': 'xxxx',
            'username': 'root',
            'password': 'xxxx'
        },
        # 添加更多的服务器...
    }

    print("可用服务器列表:")
    for index, server_name in enumerate(servers, start=1):
        print(f"{index}. {server_name}")

    selection = input("请选择要连接的服务器编号:")
    selection = int(selection)

    server_names = list(servers.keys())
    selected_server_name = server_names[selection - 1]
    selected_server_info = servers[selected_server_name]

    connect_to_server(selected_server_info['hostname'], selected_server_info['username'], selected_server_info['password'])

if __name__ == '__main__':
    main()


你可能感兴趣的:(服务器,服务器连接,python)