利用python实现批量自动化运维脚本案例

编程语言 jikk345 1188℃ 0评论

1、编写脚本

#!/usr/bin/env python
# this is script by qinglin.
# mail:qinglin@qinglin.net
################################################
# QQ 7796755
# blog:http://www.qinglin.net
################################################
import paramiko
import socket
import sys,os
host = sys.argv[1]
user = sys.argv[2]
port = int(sys.argv[3])
auth_method = sys.argv[4]
if auth_method == 'PASSWORD':
    password = sys.argv[5]
    cmd = sys.argv[6]
else:
    cmd = sys.argv[5]
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#pkey_file = '/home/alex/.ssh/id_rsa'
#key = paramiko.RSAKey.from_private_key_file(pkey_file)
#s.connect(host,port,username,pkey=key,timeout=5)
try:
if auth_method == 'SSH_KEY':
    pkey_file = '/home/alex/.ssh/id_rsa'
    key = paramiko.RSAKey.from_private_key_file(pkey_file)
    s.connect(host,port,user,pkey=key,timeout=5)
elif auth_method == 'PASSWORD':
    s.connect(host,port,user,password,timeout=5)
    stdin,stdout,stderr = s.exec_command(cmd)
    cmd_result = stdout.read(),stderr.read()
print "--------Result from? %s -------" % host
for line in cmd_result:
    print line,
s.close()
except paramiko.AuthenticationException:
    print "\033[31;1m%s Authentication Error!\033[0m" % host
except socket.error:
    print "\033[31;1m%s Connection Refused!\033[0m" % host

2、执行命令:

python batch_ssh.py 10.0.0.8 qinglin 22 SSH_KEY  df
python batch_ssh.py 10.0.0.9 root   33 PASSWORD 123456 df

转载请注明:清麟博客 » 利用python实现批量自动化运维脚本案例

喜欢 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址