首页 > 其他 > 详细

paramiko模块

时间:2021-03-15 22:57:48      阅读:25      评论:0      收藏:0      [点我收藏+]

ssh登录与证书登录实现

import paramiko
from paramiko.ssh_exception import AuthenticationException

def ssh_channel(connect_type=True):
    ssh_client = paramiko.SSHClient()   #创建连接对象
    # 允许连接不在know_hosts文件中的主机, 首次登陆其它机器时会用到
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    if connect_type:
        #  使用用户名密码连接主机
        try:
            ssh_client.connect(
                username="",
                password="123",
                port=22,
                hostname="",
            )
        except AuthenticationException as e:
            return "check login info "
    else:
        try:
            pkey = "/root/.ssh/id_rsa"
            key = paramiko.RSAKey.from_private_key_file(pkey)  # 基于秘钥连接
            # ssh.load_system_host_keys()
            ssh_client.connect(hostname="192.168.95.120", pkey=key)
        except Exception as e:
            return e

    channel = ssh_client.get_transport().open_session()  # 打开一个会话通道
    channel.get_pty()  # 获取终端
    channel.invoke_shell()  # 激活终端
    return True

# 明文密码是不安全也不符合编程规范的,为了更加安全我们可使用秘钥来进行登录

if __name__ == __main__:
    res = ssh_channel()
    if res == True:
        print("success")
    else:
        print("error")

 

paramiko模块

原文:https://www.cnblogs.com/yu121/p/14540217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!