python 在ssh_config上定义的远程主机上使用paramiko运行命令

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在ssh_config上定义的远程主机上使用paramiko运行命令相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

import os
import paramiko
import argparse
import socket
import logging


def create_ssh_client(hostname):
    """Create a paramiko ssh_client object for a 'hostname' defined on
    the ~/.ssh/config file and public ssh key authentication used"""
    config = paramiko.config.SSHConfig()
    config.parse(open(os.path.expanduser('~/.ssh/config')))
    host = config.lookup(hostname)
    params = {}
    params["timeout"] = 5
    for key in host.keys():
        if key == "hostname":
            params[key] = host[key]
        elif key == "user":
            params["username"] = host[key]
        elif key == "port":
            params[key] = int(host[key])
        elif key == "identityfile":
            params["key_filename"] = host[key][0]
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.RejectPolicy())
    try:
        client.connect(**params)
    except socket.timeout:
        logging.error("Connection timed out for host '{0}'"
                      .format(hostname))
        return None
    except socket.gaierror:
        logging.exception("Connection error: if [Errno -2] the host '{0}'"
                          "is not found in ssh_config\n".format(hostname))
        return None
    except paramiko.SSHException as e:
        logging.exception("Connection error on '{0}': {1}".format(hostname, e))
        return None
    return client


if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='This script will run a command in a remote host with \
            ssh access (login information to host must be defined in \
            ~/.ssh/config file and pubkey authentication setup)')
    parser.add_argument('host', type=str, help='remote host with ssh access')
    parser.add_argument('command', type=str, help='command to run')
    args = parser.parse_args()

    host = args.host
    command = args.command

    ssh = create_ssh_client(host)

    stdin, stdout, stderr = ssh.exec_command(command)
    err = stderr.readlines()
    out = stdout.readlines()
    if(len(err) > 0):
        for line in err:
            print(line.strip())
    else:
        for line in out:
            print(line.strip())

    ssh.close()

以上是关于python 在ssh_config上定义的远程主机上使用paramiko运行命令的主要内容,如果未能解决你的问题,请参考以下文章

获取VS代码Python扩展以连接到远程AWS EMR主节点上运行的Jupyter。

ssh配置文件ssh_config和sshd_config区别

在远程X server上显示图形的设置方法

ssh设置别名

在 Paramiko 中使用 ssh_config 文件

配置ssh远程登录