python 连接到给定SSH配置文件中的给定主机名(Invoke + Paramiko)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 连接到给定SSH配置文件中的给定主机名(Invoke + Paramiko)相关的知识,希望对你有一定的参考价值。

"""
Used with Invoke to automate tasks
Connect to a given hostname in a given SSH config file
Inpired by: https://gist.github.com/acdha/6064215
"""

from invoke import task, run
from paramiko import SSHConfig, SSHClient, SSHException, AutoAddPolicy

import logging


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('ParamikoInvoke')


def connect_to_server(server='some_hostname'):
    """ Returns a paramiko.SSHClient connected to specific server """
    # Open configuration file
    with open('config') as config_file:
        ssh_config = SSHConfig()
        ssh_config.parse(config_file)

    server_config = ssh_config.lookup(server)
    user, hostname, port, keys = (
        server_config.get('user'),
        server_config.get('hostname'),
        server_config.get('port'),
        server_config.get('identityfile')
    )

    if not user or not hostname or not port or not keys:
        logger.error('Server name not found inn config file')
        return exit()

    try:
        port = int(port)
    except ValueError as e:
        logger.critical('Invalid port')
        exit()

    ssh_client = SSHClient()
    # Auto add to unknown hosts
    ssh_client.set_missing_host_key_policy(AutoAddPolicy())

    try:
        ssh_client.connect(
            hostname, port,
            username=user, key_filename=keys
        )
    except SSHException as e:
        logger.critical('Could not connect to SSH Server')
        logger.error(e)
        exit()

    return ssh_client

以上是关于python 连接到给定SSH配置文件中的给定主机名(Invoke + Paramiko)的主要内容,如果未能解决你的问题,请参考以下文章

连接到 ssh 远程主机(在 *** 网络中)超时

如何使用堡垒主机通过 SSH 连接到 Redshift

Python 脚本 - 连接到 SSH 并运行命令

如何使用代理跳转(堡垒主机)通过 ssh 隧道连接到 mongodb 服务器

Git SSH 错误:“连接到主机:错误的文件号”

Ubuntu通过ssh公钥验证远程连接到Windows