唐伯虎 发表于 2021-6-24 09:51:16

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

本文为通过密码或密钥实现python批量自动化运维脚本案例分享,是老男孩linux培训 python课程教学案例内容,后续会分享多线程并发执行这个脚本的更高级的功能(http://oldboy.blog.51cto.com/2561410/1221605),敬请关注!
#!/usr/bin/env pythonthis script comes from beijing oldboy trainning.e_mail:70271111@qq.comfunction: remote multi exec cmd by ssh.version:1.1
oldboy trainning info.QQ 80042789 70271111site:http://www.etiantian.orgblog:http://oldboy.blog.51cto.comoldboy trainning QQ group: 208160987 45039636

import paramiko
import socket
import sys,os
host = sys.argv
user = sys.argv
port = int(sys.argv)
auth_method = sys.argv
if auth_method == 'PASSWORD':
password = sys.argv
cmd = sys.argv
else:
cmd = sys.argv
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执行命令:
python batch_ssh.py 10.0.0.8 oldboy 22 SSH_KEYdf
python batch_ssh.py 10.0.0.9 root   33 PASSWORD 123456 df

页: [1]
查看完整版本: 利用python实现批量自动化运维脚本案例