python3实现登录管理多台ssh|telnet客户端

python管理ssh客户端

#!/usr/bin/python3
import paramiko

# 交换机的IP地址列表
hosts = [
    "ip_address01",
    "ip_address02",
    ]

# SSH连接用户名和密码
username = "root"
password = "123456"
ssh_port = "22"

# 定义多个需要执行的命令列表,一行一个
commands = [
    'curl -sf myip.ipip.net', 
    'uptime',
]

# 遍历服务器列表
for host in hosts:
    try:
        # 创建 SSH 客户端对象
        ssh = paramiko.SSHClient()

        # 自动添加主机密钥
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接服务器
        ssh.connect(host, username=username, password=password, port=ssh_port)

        # 执行命令
        for command in commands:
            # 一次一个列表里的命令将会执行
            stdin, stdout, stderr = ssh.exec_command(command)

            # 打印输出结果
            print('Server:', host)
            print(stdout.read().decode())

        # 关闭连接
        ssh.close()
    except Exception as e:
        print('Error:', e)
        ssh.close()

python管理telnet客户端

#!/usr/bin/python3
import telnetlib

# 交换机的IP地址列表
hosts = [
    "ip_address01",
    "ip_address02",
    ]

# SSH连接用户名和密码
username = "root"
password = "123456"
telnet_port = "23"

# 定义多个需要执行的命令列表,一行一个
commands = [
    'curl -sf myip.ipip.net', 
    'uptime',
]

# 遍历服务器列表
for host in hosts:
    try:
        # 创建 Telnet 客户端对象
        tn = telnetlib.Telnet(host, telnet_port)

        # 登录服务器
        tn.read_until(b'login: ')
        tn.write(username.encode('utf-8') + b'\n')
        tn.read_until(b'Password: ')
        tn.write(password.encode('utf-8') + b'\n')

        # 执行命令
        for command in commands:
            tn.write(command.encode('utf-8') + b'\n')
            print('Server:', host)
            print(tn.read_until(b'\n').decode('utf-8'))

        # 关闭连接
        tn.write(b'exit\n')
        tn.close()
    except Exception as e:
        print('Error:', e)
声明:本文为原创,作者为 辣条①号,转载时请保留本声明及附带文章链接:https://boke.wsfnk.com/archives/1141.html
谢谢你请我吃辣条谢谢你请我吃辣条

如果文章对你有帮助,欢迎点击上方按钮打赏作者

最后编辑于:2023/5/14作者: 辣条①号

现在在做什么? 接下来打算做什么? 你的目标什么? 期限还有多少? 进度如何? 不负遇见,不谈亏欠!

暂无评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

arrow grin ! ? cool roll eek evil razz mrgreen smile oops lol mad twisted wink idea cry shock neutral sad ???

文章目录