ssh.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:kafka-utils 作者: Yelp 项目源码 文件源码
def ssh(host, forward_agent=False, sudoable=False, max_attempts=1, max_timeout=5):
    """Manages a SSH connection to the desired host.
       Will leverage your ssh config at ~/.ssh/config if available

    :param host: the server to connect to
    :type host: str
    :param forward_agent: forward the local agents
    :type forward_agent: bool
    :param sudoable: allow sudo commands
    :type sudoable: bool
    :param max_attempts: the maximum attempts to connect to the desired host
    :type max_attempts: int
    :param max_timeout: the maximum timeout in seconds to sleep between attempts
    :type max_timeout: int
    :returns a SSH connection to the desired host
    :rtype: Connection

    :raises MaxConnectionAttemptsError: Exceeded the maximum attempts
    to establish the SSH connection.
    """
    with closing(SSHClient()) as client:
        client.set_missing_host_key_policy(AutoAddPolicy())

        cfg = {
            "hostname": host,
            "timeout": max_timeout,
        }

        ssh_config = SSHConfig()
        user_config_file = os.path.expanduser("~/.ssh/config")
        if os.path.exists(user_config_file):
            with open(user_config_file) as f:
                ssh_config.parse(f)
                host_config = ssh_config.lookup(host)
                if "user" in host_config:
                    cfg["username"] = host_config["user"]

                if "proxycommand" in host_config:
                    cfg["sock"] = ProxyCommand(host_config["proxycommand"])

                if "identityfile" in host_config:
                    cfg['key_filename'] = host_config['identityfile']

                if "port" in host_config:
                    cfg["port"] = int(host_config["port"])

        attempts = 0
        while attempts < max_attempts:
            try:
                attempts += 1
                client.connect(**cfg)
                break
            except socket.error:
                if attempts < max_attempts:
                    time.sleep(max_timeout)
        else:
            raise MaxConnectionAttemptsError(
                "Exceeded max attempts to connect to host: {0}".format(max_attempts)
            )

        yield Connection(client, forward_agent, sudoable)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号