#-*- coding: utf-8 -*-
#批量操作linux服务器(执行命令,上传,下载)
#!/usr/bin/python
import paramiko
import datetime
import os
import threading
def ssh2(ip,username,passwd,cmd):
try:
paramiko.util.log_to_file('paramiko________.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,username,passwd,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 :
print '%s\tError\n'%(ip)
def download(ip, username, passwd, local_dir, remote_dir):
try:
paramiko.util.log_to_file('paramiko_download.log')
t = paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
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:
print "connect error!"
def upload(ip, username, passwd, local_dir, remote_dir):
try:
paramiko.util.log_to_file('paramiko_upload.log')
t = paramiko.Transport((ip, 22))
t.connect(username=username, password=passwd)
sftp = paramiko.SFTPClient.from_transport(t)
#files = sftp.listdir(remote_dir)
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:
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" #用户名
#passwd = "xxxx" #单台服务器时启用----------------------
#ip='192.168.12.19' #单台服务器时启用----------------------
local_dir = "D:\\batch\\tmp" #本地服务器目录
remote_dir = "/tmp/" #远程服务器目录
#threads = [] #多线程
print "Begin......"
hosts=open("D:\\batch\\list.txt") #本地服务器列表
host=hosts.readlines()
hosts.close()
for list in host:
line = list.split()
ip = line[0].strip()
pwd = line[1].strip()
# print ip,
# print pwd,
# b=threading.Thread(target=upload,args=(ip,username,pwd,local_dir,remote_dir))
# b.start()
a=threading.Thread(target=ssh2,args=(ip,username,pwd,cmd))
a.start()
python批量操作Linux服务器脚本,ssh密码登录(执行命令、上传、下载)(一)
最新推荐文章于 2023-08-02 13:50:50 发布