paramiko模块

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")

 参考:https://www.icode9.com/content-1-649396.html

posted @ 2021-03-15 21:53  半日闲1  阅读(70)  评论(0编辑  收藏  举报