python实现ssh+scp文件上传下载,sudo免密执行命令脚本

import paramiko

from scp import SCPClient
import os

# scpclient只能上传/下载单文件 , 不能传文件目录
def scp_up(ip_list, username, password, filepath_list,cmd,root_pwd):
    """
    :param ip_list: ip地址
    :param username:用户名
    :param pwd:密码
    :param filepath_list:  文件列表   [[local_path,server_path],[]]
    :return:
    """

    for _ip in ip_list:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh_client.connect(hostname=_ip,port=22, username=username, password=password)

        #  通过scp上传或下载服务器文件
        scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
        try:
            #  上传文件
            for  path  in  filepath_list:
                #
                scpclient.put(path[0], path[1])
        except FileNotFoundError as e:
            print(e)
            print('系统找不到指定文件'+str(path[0]))
        else:
            print('scp  %s 到服务器 %s 成功' %(path[0],path[1]))
        # 上传完成后执行命令,sudo免密执行
        stdin, stdout, stderr = ssh_client.exec_command( 'echo "%s" | sudo  -S %s' %(root_pwd,cmd) )
        #读取执行命令后输出的内容
        out = stdout.readlines()
        for m in out:
            print(m)
        ssh_client.close()

if __name__ == '__main__':
    ip_list=['']
    username=''
    password=''
    root_pwd=''
    local_path='local/'
    server_path='/etc/supervisor/conf.d/'
    filepath_list=[[local_path+'sensor.conf',server_path],
                   [local_path+'shelf.conf',server_path],
                   [local_path+'shelf_sgun.conf',server_path],
                   [local_path+'scanner_alone.conf',server_path]]
    scp_up(ip_list,username,password,filepath_list,cmd,root_pwd)

你可能感兴趣的:(python脚本)