|
想写一个 python 脚本,实现 ssh 命令的功能,可以使用 pexpect 模块、paramiko 模块或 public key 来实现远程登陆和执行命令(在参数中指定),并且可以在参数中直接指定密码来实现批处理。
目前做了一下用 pexpect 的方法,远程执行命令没有问题,但如果仅仅是要远程登陆就不行,总是超时退出,请问有什么办法没有?
- #!/usr/bin/python
- # -*- encoding: UTF-8 -*-
- import re
- import sys
- import time
- import pexpect
- import getopt
- class pyssh:
- def __init__(self, user='nobody', passwd='', host='localhost', method='pexpect', info=None):
- self.user = user
- self.host = host
- self.passwd = passwd
- self.method = method
- if info:
- try:
- self.user = info['user']
- self.host = info['host']
- self.passwd = info['passwd']
- self.method = info['method']
- except KeyError, (errno, strerror):
- print 'Not enough infomations.'
- sys.exit(1)
- def rexec(self, command='', timeout=60):
- if self.method == 'pexpect':
- if type(command) is not str:
- raise 'Not a command string.'
- if command:
- command = 'ssh %s@%s "%s"' % (self.user, self.host, command)
- else:
- command = 'ssh %s@%s' % (self.user, self.host)
- print command
- T = time.time()
- try:
- ssh = pexpect.spawn(command, timeout=timeout)
- idx = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
- if idx == 0: ssh.sendline(self.passwd)
- elif idx == 1: ssh.sendline('yes')
- except pexpect.EOF:
- ssh.close()
- print '%d seconds' % int(time.time() - T)
- return 1
- # except pexpect.TIMEOUT:
- print ssh.read()
- ssh.expect(pexpect.EOF)
- ssh.close()
- print '%d seconds' % int(time.time() - T)
- # class ssh_pexpect(pyssh):
- def usage():
- print 'usage'
- if __name__ == '__main__':
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'a:u:p:h:m:t:')
- except getopt.GetoptError, (errno, strerror):
- print 'getopt error: %d, %s' % (errno, strerror)
- usage()
- sys.exit(2)
- optmap = {'method' : 'pexpect'}
- timeout = 30
- for opt, value in opts:
- if opt == '-a':
- try:
- optmap['host'] = value.split('@')[1]
- uptmp = value.split('@')[0]
- optmap['user'] = uptmp.split(':')[0]
- optmap['passwd'] = uptmp.split(':')[1]
- except IndexError:
- print 'Lack of info'
- sys.exit(3)
- if opt == '-u': optmap['user'] = value
- if opt == '-h': optmap['host'] = value
- if opt == '-p': optmap['passwd'] = value
- if opt == '-m': optmap['method'] = value
- if opt == '-t': timeout = value
- if not args:
- ssh = pyssh(info=optmap)
- ssh.rexec(timeout=timeout)
- else:
- ssh = pyssh(info=optmap)
- command = args[0]
- ssh.rexec(command, timeout=timeout)
复制代码
谢谢 |
|