美文网首页Python进阶
Python模块·Paramiko远程连接

Python模块·Paramiko远程连接

作者: 技术老男孩 | 来源:发表于2023-01-07 09:28 被阅读0次

一、paramiko模块应用功能

  • 实现对 SSH 的相关功能,例如:要对服务器进行远程管理的操作,就需要使用此模块

二、安装(可以参照pip安装文章)

# 使用pip,安装paramiko模块
[root@localhost xxx]# pip3 install paramiko  

三、实现ssh远程连接服务器

import paramiko
import re
# ssh连接并执行脚本函数
# hosts:ssh的主机地址
# username:ssh登录的用户名
# password:用户名的登录密码
def ssh_exec_com(hosts, username, password, command):
    # 创建ssh连接对象
    ssh = paramiko.SSHClient()
    # 校验指纹信息,模拟输入yes的过程
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    try:
        # 连接服务器
        ssh.connect(hosts, username=username, password=password)
        cms = re.split(";", command)
        for cm in cms:
            # 远程执行命令
            ssh_result = ssh.exec_command(cm)
            # ssh_result[0]存储输入的数据
            # ssh_result[1]存储命令执行成功的输出信息
            # ssh_result[2]存储命令执行失败的错误信息
            # read()返回的是字节串,可以通过decode()转换成字符串
            success_log = ssh_result[1].read().decode()
            err_log = ssh_result[2].read().decode()
            # 打印执行命令
            print("command:", cm)
            # 打印成功日志
            print("success_log:", success_log, end="") if len(success_log) != 0 else None
            # 打印失败日志
            print("err_log:", err_log, end="") if len(err_log) != 0 else None
    except Exception as e:
        # 打印异常信息
        print(e)
    finally:
        # 关闭资源
        ssh.close()

if __name__ == '__main__':
    # 调用函数(输入参数可以使用input)
    ssh_exec_com("127.0.0.1", "root", "123", "id root;asdid bob;id hhh")

相关文章

网友评论

    本文标题:Python模块·Paramiko远程连接

    本文链接:https://www.haomeiwen.com/subject/jzlnqdtx.html