批量执行shell命令

简介:

 虽然目前都实现了自动化如puppet saltstack在环境中的应用,但工作中不可避免的要自己写一些简单的批量执行shell命令的脚本。


python paramiko模块是目前使用得较为顺手的模块,执行命令时基本无需要转换,直接将shell命令扔进去执行就OK


简单示例,10个线程同时执行ssh或scp动作,未设置timeout时间,如执行长时间无反应会导致脚本执行问题:


#!/usr/bin/python

# _*_ coding: utf-8 _*_


import paramiko

import sys

import logging

from multiprocessing.dummy import Pool as ThreadPool

import re

import os


try:

    fun_name = sys.argv[1]

    file = open(sys.argv[2])

except Exception,e:

    print """use like:

    #copy dir or file

    shell_exec_map.py scp ip_file source_file des_file

    #do cmd in host

    exec_map.py ssh ip_file 'yum install -y zabbix'

    """

    exit()


logging.basicConfig(level=logging.DEBUG ,

                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

                datefmt='%a, %d %b %Y %H:%M:%S',

                filename='exec_map.log',

                filemode='a+')


#ssh key文件位置

privatekeyfile  = os.path.expanduser('/root/.ssh/id_rsa')

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)

#############################

#对ssh key设置密码方式

#privatekeyfile  = os.path.expanduser('/root/.ssh/id_rsa')

#mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='password')

#############################


def getCmdInfo(host_ip,cmd):

    print host_ip

    try:

        c = paramiko.SSHClient()

        c.set_missing_host_key_policy(paramiko.AutoAddPolicy())

##################

#密码登录方式

        #c.connect(host_ip,22,'root',password)

##################

        c.connect(host_ip,22,'root',pkey=mykey)

        stdin,stdout,stderr = c.exec_command(cmd)

        info = stdout.read()

        c.close()

        return info

    except Exception as e:

            logging.error( 'getCmdInfo ip %s  %s error: %s' % (host_ip,cmd,e))


def postFileToRemote(host_ip,localpath,remotepath):

    print host_ip

    try:

        t = paramiko.Transport((host_ip,22))

        ##################

#密码登录方式

        #t.connect(username='root',password='')

##################

        t.connect(username='root',pkey=mykey)

        sftp = paramiko.SFTPClient.from_transport(t)

        sftp.put(localpath,remotepath)

        sftp.close()

        t.close()

    except Exception,e:

        logging.error( 'scp_cmd ip %s soure:%s des: %s error: %s' % (host_ip,localpath,remotepath,e))


#10个并发同时进行

pool = ThreadPool(10)

line_list = []

for line in file.readlines():

  line_list.append(line.strip())

  

if fun_name == 'scp':

    try:

        pool.map(scpFile,line_list)

        logging.debug('scpFile ip file %s source %s dec %s' % (sys.argv[2],sys.argv[3],sys.argv[4]))

    except Exception as e:

            logging.error( 'scpFile map error: %s ' % e)

elif fun_name == 'ssh':

    try:

        if pattern_cmd.findall(sys.argv[3]):

            print "can't use rm command!"

            logging.debug('sshCmd ip file %s cmd %s' % (sys.argv[2],sys.argv[3]))

        else:

            pool.map(sshCmd,line_list)

            logging.debug('sshCmd ip file %s cmd %s' % (sys.argv[2],sys.argv[3]))

    except Exception as e:

            logging.error( 'sshCmd map error: %s ' % e)

pool.close()

pool.join()



ansible基于paramiko模块做的批量执行脚本,远端执行

1、安装ansible软件,配置了epel源,或者线上下载ansible-1.7.2

2、配置节点,IP(主机名需要主机能正常解析)

vi /etc/ansible/hosts

[other]
zabbix-127023.xxx.com
haproxy-127021.xxx .com
controller-127022.xxx .com
haproxy-127021.xxx.com

3、执行Ping命令测试(带上环境变量. ~/.bash_profile

ansible -m shell -a '. ~/.bash_profile &&ping -c 2 10.197.128.1' other

controller-129022.xxx.com | success | rc=0 >>
PING 10.197.128.1 (10.198.127.1) 56(84) bytes of data.
64 bytes from 10.198.127.1: icmp_seq=1 ttl=254 time=0.466 ms
64 bytes from 10.198.127.1: icmp_seq=2 ttl=254 time=0.409 ms

--- 10.198.127.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.409/0.437/0.466/0.035 ms

pinsh-127024.xxx.com | FAILED => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue


ansible方法有个不方便的地方第一次执行时,需要手动确认下。python脚本不需要手动确认



本文转自 qwjhq 51CTO博客,原文链接:http://blog.51cto.com/bingdian/1710444

相关文章
|
5月前
|
存储 Unix Shell
Shell 输出命令完全指南:echo 与 printf 的深度剖析
本文深入解析了 Shell 编程中 `echo` 和 `printf` 两个核心输出命令的用法与区别。`echo` 简单易用,适合基础输出;`printf` 功能强大,支持复杂格式化。文章从语法、转义序列、高级技巧到实际应用场景(如日志记录、进度显示)逐一讲解,并对比两者的性能与适用场景,帮助开发者根据需求灵活选择。最后通过进阶技巧和常见问题解答,进一步提升对两者的掌握程度。
256 1
|
6月前
|
网络协议 Shell 网络安全
面试官想听的不仅是命令——如何结构化回答“容器无Shell时如何测试外网”?
“说说看,如果一个Pod的容器没有Shell,如何测试它能否访问外网?”
面试官想听的不仅是命令——如何结构化回答“容器无Shell时如何测试外网”?
|
8月前
|
运维 Shell 数据库
Python执行Shell命令并获取结果:深入解析与实战
通过以上内容,开发者可以在实际项目中灵活应用Python执行Shell命令,实现各种自动化任务,提高开发和运维效率。
225 20
|
8月前
|
安全 Shell 数据处理
使用Python执行Shell命令并获取结果
在实际应用中,可以根据需要选择适当的参数和方法来执行Shell命令,并处理可能出现的各种情况。无论是系统管理、自动化任务还是数据处理,掌握这些技巧都将极大地提高工作效率。
273 12
|
10月前
|
人工智能 Shell iOS开发
AI Shell:在命令行里“对话” AI ,微软推出将 AI 助手引入命令行的 CLI 工具,打造对话式交互命令行
AI Shell 是一款强大的 CLI 工具,将人工智能直接集成到命令行中,帮助用户提高生产力。AI Shell 支持多种 AI 模型和助手,通过多代理框架提供丰富的功能和灵活的使用模式。
1181 7
|
11月前
|
Web App开发 网络协议 Linux
linux命令总结(centos):shell常用命令汇总,平时用不到,用到就懵逼忘了,于是专门写了这篇论文,【便持续更新】
这篇文章是关于Linux命令的总结,涵盖了从基础操作到网络配置等多个方面的命令及其使用方法。
221 1
linux命令总结(centos):shell常用命令汇总,平时用不到,用到就懵逼忘了,于是专门写了这篇论文,【便持续更新】
|
10月前
|
Java Shell Windows
java Runtime.exec()执行shell/cmd命令:常见的几种陷阱与一种完善实现
java Runtime.exec()执行shell/cmd命令:常见的几种陷阱与一种完善实现
187 1
|
11月前
|
Unix Shell Linux
常见的shell命令
shell常用命令
250 11
|
11月前
|
Shell 知识图谱
Shell printf 命令
10月更文挑战第3天
91 1
|
12月前
|
Shell Linux
Linux shell编程学习笔记82:w命令——一览无余
Linux shell编程学习笔记82:w命令——一览无余