您的位置:首页 > 其它

远程执行命令通用脚本

2016-05-03 00:00 323 查看
摘要: 远程执行命令通用脚本 ssh_cmd

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time
import argparse
import datetime
import paramiko

reload(sys)
sys.setdefaultencoding("utf-8")

username = 'root'
password = ''

#change return color
def G(s):
return "%s[32;2m%s%s[0m"%(chr(27), s, chr(27))
def R(s):
return "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))

def cmd_exc(ip, username, password):
conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
conn.connect(hostname = ip, username = username, password = password, timeout = 10)
stdin, stdout, stderr = conn.exec_command(cmd)
result = stdout.readlines()
except:
print R("无法连接")
conn.close()
try:
return G(result)
except UnboundLocalError:
pass

if __name__ == "__main__":
parser=argparse.ArgumentParser(description='ssh_cmd', usage='%(prog)s [options]')
parser.add_argument('-H','--host', nargs='?', dest='listhost', help='主机/多个主机用","分割')
parser.add_argument('-f','--file', nargs='?', dest='filehost', help='主机列表文件')
parser.add_argument('-m','--command', nargs='?', dest='command', help='执行命令')
if len(sys.argv)==1:
parser.print_help()
else:
args=parser.parse_args()
cmd = args.command
if args.listhost is not None and args.filehost is None and args.command is not None:
for ip in args.listhost.split(','):
print G(ip)
print G('-'*80)
print cmd_exc(ip, username, password)
print
elif args.listhost is None and args.filehost is not None and args.command is not None:
try:
with open(args.filehost) as f:
for ips in f.readlines():
ip = ips.replace('\n', '')
print G(ip)
print G('-'*80)
print cmd_exc(ip, username, password)
print
except IOError:
print R('主机列表文件不存在')
else:
print R('主机或命令不能为空')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息