简单命令操作执行要是删除修改请慎重,使用请慎重个人脚本欢迎提供各种意见。


使用的时候需要一份包含主机名和密码的文件

./remote_cmd.py -e FILENAME就可以生成一个例子。

远程执行命令脚本(通过密码登陆)脚本_主机

2,配置号文件之后可以运行 ./remote_cmd.py -f FILENAME -c CMD

运行结果如下

远程执行命令脚本(通过密码登陆)脚本_python_02

#!/usr/bin/env python
#-*- coding:utf-8  -*-
'''
Author: Aileo
Date:2013-08-19
Version:1.0.0
'''
import re
import pexpect
from optparse import OptionParser
#import os
#print os.getcwd()
parser = OptionParser()
parser.add_option("-f","--file",dest="filename",help="read info from FILE",metavar="FILE")
parser.add_option("-c","--cmd",dest="cmd",help="enter your command",metavar="CMD")
parser.add_option("-e","--exam",dest="exam",help="create an example example.cfg",metavar="example.cfg")
(options,args) = parser.parse_args()
          
def ssh_cmd(ip, passwd, port, cmd):
    ret = -1
    ssh = pexpect.spawn('ssh -p %s root@%s %s' %(port, ip, cmd))
    try:
        i = ssh.expect(['Password:', 'continue connecting (yes/no)?'], timeout=5)
        if i == 0 :
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes\n')
            ssh.expect('Password: ')
            ssh.sendline(passwd)
        ssh.sendline(cmd)
        r = ssh.read()
        print r
        ret = 0
    except pexpect.EOF:
        print "EOF"
        ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
        print "TIMEOUT"
        ssh.close()
        ret = -2
    return ret
def exhostcfg(judge):
    examples = '''
#Hostname|IP    password    ssh_port|default{22}
Gentoo-128  xindong 22
Gentoo-214  xindong 1688'''
    f = file(judge,"w")
    f.write(examples)
    f.close
    print "Create a example %s" %judge
def main(cmd): 
    Hosts_file = open(options.filename,'r')
    for line in Hosts_file.readlines():
        reject = re.match(r"^#|^\s+",line)
        if reject:
            pass
        else:
            p = re.compile(r'\s+')
            Hostname = p.split(line)[0]
            Password = p.split(line)[1]
            Port = p.split(line)[2]
#           method = p.split(line)[3]
            print Hostname, ":_________________"
            ssh_cmd(Hostname, Password, Port, cmd)
if __name__ == '__main__':
    if options.cmd  and options.filename:
        main(options.cmd)
    elif options.exam :
        exhostcfg(options.exam)
    else:  
        print "argvs error,please use --help for more information"