Python中paramiko模块的使用

paramiko支持SSH协议,可以与Linux或Windows(搭建了SSH服务)进行交互,包括远程执行命令或执行上传/下载文件等操作。

代码如下:

import os
import paramiko


def exec_command(ip, port, username, password, cmd):
    """远程执行命令
    """

    paramiko.util.log_to_file("paramiko.log")

    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip, port=int(
        port), username=username, password=password, timeout=5)
    stdin, stdout, stderr = ssh.exec_command('cmd.exe /C "%s"' % cmd)

    ssh.close()


def upload_file(ip, port, username, password, local_file_path, remote_file_path):
    """上传文件
    """

    paramiko.util.log_to_file("paramiko.log")

    trans = paramiko.Transport((ip, int(port)))
    trans.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(trans)
    sftp.put(local_file_path, remote_file_path)

    trans.close()


def download_file(ip, port, username, password, local_file_path, remote_file_path):
    """下载文件
    """

    paramiko.util.log_to_file("paramiko.log")

    trans = paramiko.Transport((ip, int(port)))
    trans.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(trans)
    sftp.get(remote_file_path, local_file_path)

    trans.close()


def upload_dir(ip, port, username, password, local_dir, remote_dir):
    """上传目录(从windows上传)
    """

    paramiko.util.log_to_file("paramiko.log")

    trans = paramiko.Transport((ip, int(port)))
    trans.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(trans)

    try:
        sftp.mkdir(remote_dir)
    except Exception, e:
        pass

    for root, dirs, files in os.walk(local_dir):

        for file_name in files:
            local_file_path = os.path.join(root, file_name)
            remote_file_path = os.path.join(
                remote_dir, local_file_path[3:])    # 切片:windows路径去掉盘符
            remote_file_path = remote_file_path.replace("\\", "/")

            try:
                sftp.put(local_file_path, remote_file_path)
            except Exception, e:
                sftp.mkdir(os.path.dirname(remote_file_path))
                sftp.put(local_file_path, remote_file_path)

        for dir_name in dirs:
            local_dir = os.path.join(root, dir_name)
            remote_path = os.path.join(remote_dir, local_dir[3:])
            remote_path = remote_path.replace("\\", "/")

            try:
                sftp.mkdir(os.path.dirname(remote_path))
                sftp.mkdir(remote_path)
            except Exception, e:
                pass

    trans.close()


你可能感兴趣的:(Python中paramiko模块的使用)