python批量操作Linux服务器脚本,key登录(执行命令、上传、下载)(二)

#-*- coding: utf-8 -*-
#批量操作linux服务器(执行命令,上传,下载)
#!/usr/bin/python
import paramiko
import datetime
import os
import threading
def ssh2(ip,username,privatekeyfile,keypwd,cmd):
    try:
        paramiko.util.log_to_file('paramiko________.log')
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #privatekeyfile = "D:\\batch\\id_dsa_1024"
        mykey=paramiko.DSSKey.from_private_key_file(filename=privatekeyfile,password=keypwd)
        ssh.connect(hostname=ip,port=22,username=username , pkey=mykey,timeout=5)
        for m in cmd:
            stdin,stdout,stderr = ssh.exec_command(m)
            #stdin.write("Y")   #简单交互,输入 ‘Y’
            out = stdout.readlines()
            # outerr = stderr.readlines()
            #屏幕输出
            for o in out:
                print o,
            # for i in outerr:
            #     print i,
                print '%s\tOK\n'%(ip)
        ssh.close()
    except Exception,ex:
        print Exception,":",ex
        print '%s\tError\n'%(ip)
def download(ip,username,privatekeyfile,keypwd,local_dir, remote_dir):
   try:
        paramiko.util.log_to_file('paramiko_download.log')
        t = paramiko.Transport((ip,22))
        mykey=paramiko.DSSKey.from_private_key_file(filename=privatekeyfile,password=keypwd)
        t.connect(username = username, pkey=mykey)
        sftp = paramiko.SFTPClient.from_transport(t)
        files = sftp.listdir(remote_dir)
        for f in files:
            print ''
            print '############################'
            print 'Beginning to download file  from %s  %s ' % (ip, datetime.datetime.now())
            print 'Downloading file:', os.path.join(remote_dir, f)
            sftp.get(os.path.join(remote_dir, f), os.path.join(local_dir, f))#下载
            print 'Download file success %s ' % datetime.datetime.now()
            print ''
            print '############################'
        t.close()
   except Exception,ex:
        print Exception,":",ex
        print "connect error!"
        print ip, "fail!"


def upload(ip, username,privatekeyfile, keypwd, local_dir, remote_dir):
    try:
        paramiko.util.log_to_file('paramiko_upload.log')
        t = paramiko.Transport((ip, 22))
        mykey=paramiko.DSSKey.from_private_key_file(filename=privatekeyfile,password=keypwd)
        t.connect(username = username, pkey=mykey)
        sftp = paramiko.SFTPClient.from_transport(t)
        files = os.listdir(local_dir)
        for f in files:
            print ''
            print '############################'
            print 'Beginning to upload file  to %s  %s ' % (ip, datetime.datetime.now())
            print 'Uploading file:', os.path.join(local_dir, f)
            sftp.put(os.path.join(local_dir, f), os.path.join(remote_dir, f))#上传
            print 'Upload file success %s ' % datetime.datetime.now()
            print ''
            print '############################'
        t.close()
    except Exception,ex:
        print Exception,":",ex
        print "connect error!"
        print ip, "fail!"


if __name__=='__main__':
  #  cmd = ['ls -lh /export/servers/mysql/log/mysql.log']#你要执行的命令列表
    cmds=open("D:\\batch\\cmds.txt") #从文件读取命令
    cmd=cmds.readlines()
    cmds.close()
    username = "root"  #用户名
    privatekeyfile = "D:\\batch\\id_dsa_all"
    keypwd="123456"
    #passwd = "xxxx"    #单台服务器时启用----------------------
    #ip='192.168.12.19'  #单台服务器时启用----------------------
    local_dir = "D:\\batch\\tmp"  #本地服务器目录
    remote_dir = "/tmp/temp/" #远程服务器目录
    #threads = []   #多线程
    print "Begin......"
    hosts=open("D:\\batch\\ip.txt") #本地服务器列表
    host=hosts.readlines()
    hosts.close()
    for ip in host:
        ip=ip.strip()
        # b=threading.Thread(target=upload,args=(ip,username,privatekeyfile,keypwd,local_dir,remote_dir))
        # b.start()
        # c=threading.Thread(target=download,args=(ip,username,privatekeyfile,keypwd,local_dir,remote_dir))
        # c.start()
        a=threading.Thread(target=ssh2,args=(ip,username,privatekeyfile,keypwd,cmd))
        a.start()


#和Paramiko相关的网址
#http://docs.paramiko.org/en/1.13/api/keys.html   paramiko帮助
#https://github.com/paramiko/paramiko    paramiko源码
#http://nullege.com/codes/search/paramiko  paramiko实例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值