示例#1
0
def _get_host_ip(
        host: str,
        ssh_config_path: str = "~/.ssh/config"
) -> Union[IPv4Address, IPv6Address]:
    """
    1. If host.name is a short alias,
       we assume there is a corresponding record in `~/.ssh/config`:
        1.1 If the corresponding `HOSTNAME` value is an IP address,
            return it as the result.
        1.2 If the corresponding `HOSTNAME` is a domain,
            return the IP of the domain,
            assuming the domain is accessible from the local machine.
    2. If host.name is a domain, return its IP,
       assuming the domain is accessible from the local machine.
    3. Else raise an ValueError.
    """
    posix_path: PosixPath = PosixPath(ssh_config_path)
    path_with_user_expanded: PosixPath = posix_path.expanduser()
    config: SSHConfig = SSHConfig.from_path(str(path_with_user_expanded))
    # If `host.name` does not exist in `~/.ssh/config`,
    # `config.lookup(host.name)['hostname']` returns `host.name` itself.
    hostname: str = config.lookup(host)["hostname"]
    ip: Union[IPv4Address, IPv6Address]
    try:
        ip = ip_address(hostname)
    except ValueError:
        return ip_address(socket.gethostbyname(hostname))
    else:
        return ip
示例#2
0
def __power_off_linux():
    cfg = SSHConfig.from_path(Path.home() / ".ssh" / "config")\
                    .lookup(SSH_INSTANCE)
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(
        **{
            "hostname": cfg.get("hostname"),
            "port": cfg.get("port") or 22,
            "username": cfg.get("user"),
            "password": cfg.get("password"),
            "key_filename": cfg.get("identityfile"),
        })
    ssh.exec_command("sudo poweroff")