批量远程执行linux服务器程序--基于paramiko

paramiko模块是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接

具体安装方法这里不写,网上一大把

#!/usr/bin/python
#coding:utf-8
import paramiko
import threading
import os,sys,time
import subprocess
from optparse import OptionParser
import logging usage='%prog [-h][-f file][-c CMDS][--version]' parser=OptionParser(usage=usage,version='HuZhiQiang 2.0_20150618')
parser.add_option('-f','--File',dest='server',default='ip.txt',help='The Server Info')
parser.add_option('-c','--CMDS',dest='cmd',default="uptime,top -n 1,df -Ph |awk 'NR == 1 || NR == 6{print $0}',ifconfig |awk 'NR==8'|sed 's/^\s*//g'",help='You wann to execute commands')
(options,args)=parser.parse_args()

#日志记录这里注释了,有需要的可以打开
'''
logging.basicConfig(Level=logging.INFO)
logger=logging.getLogger(__name__) handler=logging.FileHandler('rem.log')
handler.setLevel(logging.INFO)
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter) logger.addHandler(handler)
'''
#print options.server,options.cmd def ssh2(ip,pt,pw,us,comm):
try: ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#logging.INFO( "%s %s %s" % ('*'*50,ip,'*'*50) )
ssh.connect(ip,port=pt,username=us,password=pw)
f.write(('='*20 +'%s status' +'='*20 + '\n')% ip)
for COMM in comm:
#print COMM
stdin,stdout,stderr = ssh.exec_command(COMM)
print "%s The command %s result is:\n" % (time.strftime("%Y%m%d %H:%M:%S"),COMM)
read = stdout.read()
print read
print '-'*60
f.write(read)
ssh.close() # except SyntaxError:
# print "please checking"
# sys.exit()
except:
print "SSH Connection refused"
print "-" *60
sys.exit() if __name__ == '__main__':
if os.path.exists(options.server):
filename=options.server
pass
else:
print 'Please check %s and ip.txt is exits' % options.server
exit(-1) print "\033[1;31m ...... 请等待......\033[0m"
open_ip = open(options.server)
f = open('Allsystem.log','a')
paramiko.util.log_to_file('paramiko.log')
up='uptime'
df = "df -Ph |awk 'NR == 1 || NR == 6{print $0}'"
net="ifconfig |awk 'NR==8'|sed 's/^\s*//g'"
command = []
command=options.cmd.split(',')
print command
#command.append(options.cmd)
for line in open_ip.readlines():
#for line in subprocess.Popen('cat ip.txt',shell=True).communicate()[0]:
ip,user,passwd,port=line.strip().split()
cmm=['ping','-c','','-w','']
cmm.extend(ip.split())
#print cmm
a=subprocess.Popen(cmm,stdout=subprocess.PIPE)
a.wait()
b=a.returncode
if b==0:
print "%s is up" % ip
port=int(port)
aa = threading.Thread(target=ssh2,args=(ip,port,passwd,user,command))
aa.start()
aa.join()
else:print "%s id down" % ip
open_ip.close()
f.write('='*20 +'All done' +'='*20 + '\n')
f.flush()
f.close()

运行结果如下:

批量远程执行linux服务器程序--基于paramiko(多线程版)的更多相关文章

  1. 批量远程执行linux服务器程序--基于pxpect(多进程、记日志版)

    #!/usr/bin/python '''Created on 2015-06-09@author: Administrator''' import pexpect import os,sys fro ...

  2. java远程执行linux服务器上的shell脚本

    业务场景:需要从服务器A中新增的文件同步至本地服务器,服务器A中内存有限,需同步成功之后清除文件. Java调用远程shell脚本,需要和远程服务器建立ssh链接,再调用指定的shell脚本. 1.创 ...

  3. SecureCRT远程ssh linux服务器,利用X11本地图形化wireshark抓包,

    平时学习抓包,使用wireshark很方便,直接图形化界面抓包,近期项目中遇到了需要通过SecureCRT ssh到linux服务器上面,还要在抓包, 1.简单使用网络数据包截获分析工具tcpdump ...

  4. Linux服务器程序--大数据量高并发系统设计

         在Linux服务器程序中,让系统能够提供以更少的资源提供更多的并发和响应效率决定了程序设计价值!怎样去实现这个目标,它其实是这么多年以来一直追逐的东西.最开始写代码时候,省去一个条件语句.用 ...

  5. Linux 高性能服务器编程——Linux服务器程序规范

    问题聚焦:     除了网络通信外,服务器程序通常还必须考虑许多其他细节问题,这些细节问题涉及面逛且零碎,而且基本上是模板式的,所以称之为服务器程序规范.     工欲善其事,必先利其器,这篇主要来探 ...

  6. java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息

    1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...

  7. widows本地-xshell实现远程连接linux服务器图形界面

    本地环境远程连接linux图形界面,常用的实现工具有,VNC.Puty.Xshell等,这里我们用的xshell manager: Xmanager简介:Xmanager是一个运行于 Windows平 ...

  8. widows终端远程连接Linux服务器

    一.前言 为什么不是远程连接Linux服务器? 因为我不会,远程连接window我就用电脑自带的“远程桌面连接”. 以下所述都是在CentOS操作系统下的. 服务器刚换成Linux的时候很迷茫,感觉无 ...

  9. 利用java实现可远程执行linux命令的小工具

    在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令.为了解决这个问题,写了个小工具来解决这个问题. 后面的代码是利用java实现的可远程执行linux命令的小工具,代 ...

随机推荐

  1. 分享10个原生JavaScript技巧

    首先在这里要非常感谢无私分享作品的网友们,这些代码片段主要由网友们平时分享的作品代码里面和经常去逛网站然后查看源文件收集到的.把平时网站上常用的一些实用功能代码片段通通收集起来,方便网友们学习使用,利 ...

  2. 【转】nginx中proxy_set_header Host $host的作用

    nginx为了实现反向代理的需求而增加了一个ngx_http_proxy_module模块.其中proxy_set_header指令就是该模块需要读取的配置文件.在这里,所有设置的值的含义和http请 ...

  3. Learning to act by predicting the future

    Dosovitskiy, Alexey, and Vladlen Koltun. "Learning to act by predicting the future." arXiv ...

  4. bcm53344 gpio驱动分析

    /********************************************************************************* * 1.查看代码是在vim下,使用 ...

  5. new/delete 的使用要点

    运算符 new 使用起来要比函数 malloc 简单得多,例如: int *p1 = (int *)malloc(sizeof(int) * length); int *p2 = new int[le ...

  6. (转)platform_driver_register,什么时候调用PROBE函数 注册后如何找到驱动匹配的设备

     platform_driver_register,什么时候调用PROBE函数 注册后如何找到驱动匹配的设备 2011-10-24 19:47:07 分类: LINUX   kernel_init中d ...

  7. bootstrap -- css -- 文字、列表

    文字 <small></small>:呈现小号字体效果. <big></big>:程序大号字体效果 <abbr></abbr>: ...

  8. js+css+div的点击后显示或者隐藏

    <html ><head><meta charset=utf-8 /><title>JS Bin</title></head>  ...

  9. opencv实例三:播放AVI格式视频

    一.不带滚动条的视频读取播放. 1.原理介绍:视频的本质是一些静态的图像的集合,opencv可以不断读取视屏中的图片,显示,就可以实时的视频流进行处理了. 2.代码如下: /************* ...

  10. [转] web_reg_save_param得到的数组的处理

    方法一: 函数(sprintf,web_reg_save_param),其中红色字体是本文档最重要的#include "web_api.h" Action(){int i,iloo ...