遠程執行命令腳本(通過密碼登陸)腳本

簡單命令操作執行要是刪除修改請慎重,使用請慎重個人腳本歡迎提供各種意見。


使用的時候需要一份包含主機名和密碼的文件

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

2,配置號文件之後可以運行 ./remote_cmd.py -f FILENAME -c CMD

運行結果如下

#!/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"
             


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章