利用Paramiko 实现批量服务器执行命令,文件上传

1、本地文件为Windows服务器文件,远程为linux服务器

2、可批量操作多台服务器,多个文件

#-*- coding:utf-8 -*-

import paramiko
import os
import traceback

class SSH(object):
    def __init__(self, ip, passwordlist, username):
        self.ip = ip
        self.username = username
        self.passwordlist = passwordlist

    def connect_ssh(self):
        for passwd in self.passwordlist:
            try:
                self.ssh = paramiko.SSHClient()
                self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.ssh.connect(hostname=self.ip, port=22, username=self.username, password=passwd)
                break
            except Exception as e:
                print (self.ip, e)

    def execute_cmd(self, cmd): #多条命令之间以逗号隔开
        stdin, stdout, stderr = self.ssh.exec_command(cmd)
        res, err = stdout.read(), stderr.read()
        result = res if res else err
        return result.decode()

    def ssh_close(self):
        self.ssh.close()

    def sftp_connect(self):
        for passwd in self.passwordlist:
            try:
                self.t = paramiko.Transport((ip, 22))
                self.t.connect(username=username, password=passwd)
                self.sftp = paramiko.SFTPClient.from_transport(self.t)
            except Exception as e:
                print (self.ip, e)

    def sftp_close(self):
        self.t.close()

    def get_localfile(self, local_dir):
        allfiles = list()
        for filepath, dirs, files in os.walk(local_dir, topdown=True):
            for file in files:
                filename = os.path.join(filepath, file)
                allfiles.append(filename)
        return allfiles

    def sfpt_putfile(self, local_dir, remote_dir):
        try:
            if remote_dir[-1] != '/':
                remote_dir = remote_dir + "/"
            all_files = self.get_localfile(local_dir)
            for file in all_files:
                file1 = os.path.basename(file)
                remote_filename = os.path.join(remote_dir, file1)
                print (remote_filename)
                try:
                    self.sftp.stat(remote_path)
                except:
                    print ("远程服务器无文件夹,请先创建...")
                self.sftp.put(file, remote_filename)
        except:
            print(traceback.format_exc())



if __name__ == '__main__':
    hostipfile = "xxx" (Linux服务器IP文件)
    username = "xxx" (登陆服务器用户名)
    passwordlist = ["XXX", "XXX"] (登陆服务器密码列表)
    local_dir = "XXX" (本地Windows服务器文件夹名)
    remote_dir = "XXX" (远程Linux服务器文件夹名)
    with open (hostipfile) as f:
        for ips in f:
            ip = ips.replace('\n', '').strip()
            ssh = SSH(ip, passwordlist, username)
            ssh.connect_ssh()
            print (ip, ssh.execute_cmd('ls /opt'))
            ssh.sftp_connect()
            ssh.sfpt_putfile(local_dir, remote_dir)
        ssh.ssh_close()
        ssh.sftp_close()

 

posted @ 2020-03-12 17:09  三旌  阅读(472)  评论(0编辑  收藏  举报