python写的ssh简单批量管理工具

   这个脚本执行的前提是,得先做好基于密钥的认证,这样可以避免频繁输入密码,基于密钥的认证这里就不写了。

脚本很简单,使用subprocess模块的call()方法来执行shell命令。刚开始学,一步步来,哈哈。。。

后面再学习学习paramiko模块,多线程。。。


下面是我写的脚本simple_ssh.py,贴上来,自己留作记录:


#!/usr/bin/env python
# Filename: simple_ssh.py
# Author: zhangliang - [email protected]
# Last modified: 2014-02-26 11:36
# Description:
# -*- coding:UTF-8 -*-
import subprocess
import sys
machines = {
    'Centos6.4': ('10.21.178.239', 'root', '22',),
    'localhost': ('192.168.10.25', 'root', '22',),
}
def ssh_Command(cmd):
    try:
        for host in machines:
            print ('-'*30 + ' \033[32;1m%s\033[0m ' + '-'*30) % machines[host][0]
            subprocess.call('ssh -p %s %s@%s %s ' % \
                (machines[host][2], machines[host][1], machines[host][0], cmd), shell=True)
    except KeyboardInterrupt:
        sys.exit('\n')
if __name__ == '__main__':
    if len(sys.argv) != 2:
        print "\033[31;1mUsage: python %s 'commands'\033[0m" % sys.argv[0]
        sys.exit()
    cmd = sys.argv[1]
    #call ssh_Command
    ssh_Command(cmd)


简单演示下:

[root@VMtemp ssh]# python simple_ssh.py "pwd"
------------------------------ 10.21.178.239 ------------------------------
/root
------------------------------ 192.168.10.25 ------------------------------
/root
[root@VMtemp ssh]#
[root@VMtemp ssh]# python simple_ssh.py "df -h"
------------------------------ 10.21.178.239 ------------------------------
Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/vg--root-LogVol00   18G  7.2G  9.5G  44% /
tmpfs                          497M  224K  497M   1% /dev/shm
/dev/sda1                      194M   97M   88M  53% /boot
------------------------------ 192.168.10.25 ------------------------------
Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/vg--root-LogVol00   18G  7.2G  9.5G  44% /
tmpfs                          497M  224K  497M   1% /dev/shm
/dev/sda1                      194M   97M   88M  53% /boot
[root@VMtemp ssh]#


你可能感兴趣的:(python,ssh,批量管理)