Skip to content

Instantly share code, notes, and snippets.

@fitzyyf
Last active November 30, 2017 13:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fitzyyf/5276821 to your computer and use it in GitHub Desktop.
Save fitzyyf/5276821 to your computer and use it in GitHub Desktop.
Python 通过SSH执行远程命令
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# See http://www.cnblogs.com/ma6174/archive/2012/05/25/2508378.html
import pexpect
import paramiko
import threading
import yaml
def ssh_exec(ip, passwd, command):
"""
采用pexpect来执行SSH命令登录
"""
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, command))
try:
i = ssh.expect(['passwod:','continue connecting (yes/no)?'], timeout=5)
if i == 0:
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('passwod:')
ssh.sendline(command)
r = ssh.read()
print r
ret = 0
except pexpect.EOF:
print "TIMEOUT"
ssh.close()
ret = -2
return ret
def ssh_save_exec(ip, username,passwd,command):
"""
采用paramiko的方式来执行,并利用多线程同时执行多个命令
"""
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,username,passwd,timeout=5)
for m in command:
stdin, stdout ,stderr = ssh.exec_command(m)
stdin.write("Y")
out = stdout.readlines()
for o in out:
print o
print '%s\t OK \n' % (ip)
ssh.close()
except :
print '%s\t Error \n' % (ip)
if __name__ == '__main__':
# 解析配置文件信息
f = open("config.yaml")
config = yaml.load(f)
# 需要执行的命令
cmd = config['execs']
# 登录用户名称
username = config['username']
# 登录密码
passwd = config['passwd']
threads = []
# 登录IP列表
ips = config['ips']
print "Beging Exec:%s on server ip: %s..." % (cmd,ips)
for ip in ips:
a = threading.Thread(target=ssh_save_exec ,args=(ip,username,passwd,cmd))
a.start()
print "Done!"
---
# SSH登录用户名称
username: root
# SSH登录用户密码
passwd: '1111'
# SSH需要登录的IP地址列表
ips:
- 192.168.1.102
- 192.168.1.103
- 192.168.1.104
# SSH登录后需要执行的命令
execs:
- service hadoop-0.20-namenode stop
- service hadoop-0.20-datanode stop
- service hadoop-0.20-secondarynamenode stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment