共计 2909 个字符,预计需要花费 8 分钟才能阅读完成。
摘要 :在主控主机上实现命令的批量分发。
环境 :python2.7.12 ecdsa paramiko。
1、ssh 模块安装
Windows 下安装包:
pycrypto 直接下载 exe 安装程序安装
ecdsa 使用源码安装,安装版本需要 >=0.11
paramiko 使用源码安装,python setup.py install
Linux 下安装:
pip install paramiko
2、ssh 模块封装
文件名为:class_ssh.py
# -*- coding:utf-8 -*-
import paramiko
import os
import traceback
import sys
class class_remote_ssh:
def __init__(self,remoteip,username,password,port=22):
self.ssh = paramiko.SSHClient()
self.remoteip = remoteip
self.username = username
self.password = password
#self.command = command
self.port = port
def ssh_connect(self):
try:
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.remoteip, self.port, self.username, self.password)
except Exception,e:
traceback.print_exc()
def ssh_exec_command(self,command):
try:
stdin, stdout, stderr = self.ssh.exec_command(command)
c = stdout.readlines()
if(c):
return c
else:
return stderr.readlines()
except Exception,e:
traceback.print_exc()
def ssh_close(self):
try:
self.ssh.close()
except:
pass
def function_remote_ssh(remoteip,username,password,command,port=22):
class_ssh = class_remote_ssh(remoteip,username,password,port)
class_ssh.ssh_connect()
c = class_ssh.ssh_exec_command(command)
class_ssh.ssh_close()
#print c
return c
3、远程分发 ssh 命令模块
文件名为:RemoteSSH.py
# _*_ coding:utf-8 _*
#!/usr/bin/env python
import class_ssh
import os
import json,sys
import logging
logfile = 'debug.log'
print logfile
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
# 创建一个 handler,用于写入日志文件
fh = logging.FileHandler(logfile)
# 定义 handler 的输出格式 formatter
formatter = logging.Formatter('%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s','%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
logger.addHandler(fh)
#iplist = ['172.20.46.143']
print os.getcwd()
json_obj = {}
try:
with open("config.json","r") as fd:
json_obj = json.load(fd)
except ValueError:
logger.debug('json loads failure')
sys.exit(-1)
iplist = json_obj["ServerIP"]
cmd = json_obj["Command"]
username = json_obj["UserName"]
passwd = json_obj["Password"]
port = json_obj["Port"]
for ip in iplist:
for c in cmd:
logger.debug("Connect to [%s] and exec command [%s]" % (ip, c))
result = class_ssh.function_remote_ssh(ip, username, passwd, c, port)
if result:
logger.debug("command exec result [%s]" % result)
4、配置文件 config.json
文件名为:config.json
{ "ServerIP":["192.168.1.2","192.168.1.3"],
"UserName":"root",
"Password":"123456",
"Port":22,
"Command":["ls","pwd"]
}
字段说明:
ServerIP :服务器 IP 列表,可支持多个
UserName:服务器 ssh 登录用户名
Password : 服务器材 ssh 登录密码
Port : SSH 端口
Command : 需要执行的命令,可有多个
5、运行
配置好各参数后,直接运行以下命令即可:
python RemoteSSH.py
正文完
扫码赞助
