Skip to content

Instantly share code, notes, and snippets.

@lichengwu
Last active December 31, 2015 08:28
Show Gist options
  • Save lichengwu/7960277 to your computer and use it in GitHub Desktop.
Save lichengwu/7960277 to your computer and use it in GitHub Desktop.
run shell on local/remote target
#!/usr/bin/python
#encoding=gbk
__author__ = 'lichengwu'
import pexpect
import sys
import getopt
import time
import os
def run_command(ip, user, password, cmd, tmo=600):
print 'try connect [%s] using %s' % (ip, user)
patterns = [user, '.*[Pp]assword:', 'Are you sure you want to continue connecting (yes/no)?',
'.*[Pp]ermission denied.*',
pexpect.EOF]
p = pexpect.spawn(cmd, timeout=tmo)
p.logfile = sys.stdout
try:
try_times = 0
i = p.expect(patterns)
while i < len(patterns):
if try_times > 100:
print "尝试100次失败,推出!"
sys.exit(1)
# first time connect
if i == 2:
p.sendline('yes')
# Permission denied
elif i == (len(patterns) - 2):
print '帐户%s没有%s的sudo权限' % (user, ip)
sys.exit(1)
elif i == (len(patterns) - 1):
break
else:
p.sendline(password)
# go on try connect
i = p.expect(patterns)
try_times += 1
p.flush()
p.close()
print '命令[%s]执行完成!' % cmd
except pexpect.TIMEOUT:
print '超时,请确认机器[%s]ssh可用,并加大超时时间,当前时间%ss' % (ip, tmo)
sys.exit(1)
except pexpect.EOF, e:
print 'EOF', e
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment