Python ssh测试主机连通性

2 篇文章 0 订阅

1、安装相关库

pip install paramiko

2、代码示例

# coding=utf-8
import traceback

import paramiko
import logging
import socket

from paramiko import ssh_exception
from paramiko.ssh_exception import AuthenticationException


def verify(sip, sport, susername, spassword):
    conn = paramiko.SSHClient()
    conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        conn.connect(sip, port=sport, username=susername, password=spassword, timeout=15)
        connect_result = "Connect Server {0} {1} {2} {3} 主机连接成功!\n".format(
            sip, sport, susername, spassword)
        # 连接成功
        logging.info(connect_result)
        data = '{"code": "1000", "msg": "主机连接成功","result": true}'
    except AuthenticationException:
        connect_result = "Connect Server {0} {1} {2} {3} 用户名或密码错误!\n".format(
            sip, sport, susername, spassword)
        # 用户名或密码错误
        print(traceback.format_exc())
        logging.info(connect_result)
        data = '{"code": "5000", "msg": "用户名或密码错误","result": false}'
    except socket.timeout:
        connect_result = "Connect Server {0} {1} {2} {3} 主机连接异常!\n".format(
            sip, sport, susername, spassword)
        # 主机连接异常
        print(traceback.format_exc())
        logging.info(connect_result)
        data = '{"code": "6000", "msg": "主机连接异常","result": false}'
    except ssh_exception.SSHException:
        connect_result = "Connect Server {0} {1} {2} {3} 端口错误!\n".format(
            sip, sport, susername, spassword)
        # 端口错误
        print(traceback.format_exc())
        logging.info(connect_result)
        data = '{"code": "7000", "msg": "端口错误","result": false}'
    return data


if __name__ == '__main__':
    res = verify("10.1.10.31", 22, "root", "keepmesecret")
    print(res)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值