【Python】模块学习之使用paramiko连接Linux,远程执行命令,上传下载、文件

本文主要介绍paramiko远程执行linux命令,及在服务器上进行文件的上传、下载

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。

由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等都可以支持

远程执行命令

def ssh_connect(host, username, passwd, *commands):
    """远程连接执行命令"""
    import paramiko
    try:
        # flag = True
        ssh = paramiko.SSHClient()  # 建立一个ssh client对象
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 使用自动保存服务器的主机名和密钥信息的策略
        ssh.load_system_host_keys()  # 每次连线时都会检查host key 与纪录的 host key 是否相同
        ssh.connect(hostname=host,
                    username=username,
                    password=passwd,
                    timeout=300)

        result = {}
        for command in commands:
            stdin, stdout, stderr = ssh.exec_command(command)
            result[command] = stdout.read(), stderr.read()   # 获取标准输出和标准错误输出的值
            err_list = stderr.readlines()
            if err_list:
                print("ERROR: ",err_list[0])
                exit(1)
                break
        ssh.close()
        return result
    except Exception as e:
        print( 'ssh %s@%s: %s' % (username, host, e))

从服务器下载文件

def ssh_get_file(host, username, passwd, remotepath, localpath):
    import paramiko
    try:
        ssh = paramiko.Transport(host)  # 建立一个连接对象
        ssh.connect(username=username,
                    password=passwd
                    )

        sftp = paramiko.SFTPClient.from_transport(ssh)
        sftp.get(remotepath, localpath)
        sftp.close()
    except Exception as e:
        print('Get data from %s@%s:%s, %s' % (username, host, remotepath, e))

上传文件到服务器

def ssh_upload_file(host, username, passwd, localpath, remotepath):
    import paramiko
    try:
        ssh = paramiko.Transport(host)  # 建立一个连接对象
        ssh.connect(username=username,
                    password=passwd
                    )

        sftp = paramiko.SFTPClient.from_transport(ssh)
        sftp.put(localpath, remotepath)
        sftp.close()
    except Exception as e:
        print('Get data from %s@%s:%s, %s' % (username, host, localpath, e))

 

posted @ 2018-01-02 10:34  Bingo-he  阅读(871)  评论(0编辑  收藏  举报