天天看點

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]#