码迷,mamicode.com
首页 > 其他好文 > 详细

SSH 配置

时间:2017-02-08 23:34:19      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:ssh openssh

#!/usr/bin/env python
#-*- encoding:utf8 -*-
#---------------------------------------------------------------------------------------
#           FILE:    sshd.py
#          USAGE:    sshd.py
#    DESCRIPTION:    Copy python style guide and coding standard .
#                    The default copy example is the current text .
#                    Dont.t find text on other directories .
#        OPTIONS:    see fuction ‘usage‘ below 
#           BUGS:    ---
#         AUTHOR:    Dr.-Vision. Simple(sp)
#        VERSION:    1.0
#        CREATED:    08.18.2014 - 10:15:30
#       REVISION:    12.02.2014
#        PROJECT:    XXX
#      COPYRITHT:    Copyright(c)2002-2014 Python, All Rights Reserved
#---------------------------------------------------------------------------------------

# import python module

#---------------------------------------------------------------------------------------
#   define python import modules .
#---------------------------------------------------------------------------------------
import os
import sys
sys.path.append(‘../module‘)
from zgtz import idsTempDic,showServerStart,showServerEnd
import socket
import time
import pexpect
import paramiko
import getpass

#   Python Function comments

#======== Function  ====================================================================
#          NAME:        
#   DESCRIPTION:    Display usage information for this script.
#  PARAMETER  1:    ---
#=======================================================================================
class SSH(object):
    user = "用户名"
    port = "端口"
    passwd = "明文密码"
    cmd = "命令行"
    local_path = "本地路径"
    remote_path = "远程路径"
    known_host = "host文件"
    public_rsa_file = "RSA公钥文件"
    private_rsa_file = "RSA私钥文件"
    public_dsa_file = "DSA公钥文件"
    private_dsa_file = "DSA私钥文件"
    auth_key_file = "authorized_keys"
    rsa_cmd = "RSA keygen" 
    dsa_cmd = "DSA keygen"
    record_log = ‘ssh日志文件‘
    t1 = "函数启动时间"
    t2 = "函数结束时间"
    def __init__(self):
        self.user = "root" 
        self.port = 22
        self.passwd = ""
        self.cmd = "ls ./tmp"
        self.local_path = os.environ[‘HOME‘]+‘/.ssh/‘ 
        self.remote_path = os.environ[‘HOME‘]+‘/.ssh/‘ 
        self.known_host = "known_hosts"
        self.public_dsa_file = "id_dsa.pub"
        self.private_dsa_file = "id_dsa"
        self.public_rsa_file = "id_rsa.pub"
        self.private_rsa_file = "id_rsa"
        self.auth_key_file = "authorized_keys"
        self.rsa_cmd = "/usr/bin/ssh-keygen -t rsa "
        self.dsa_cmd = "/usr/bin/ssh-keygen -t dsa "
        self.record_log = "./tmp/paramiko.log"
        self.t1 = time.time()
    def key_rw(self,host):
        self.host = host
        if os.path.exists(self.local_path+self.auth_key_file) and os.path.getsize(self.local_path+self.auth_key_file) != 0 :
            print "%sFileName ===%10s\tCVM_Address === %s\t[ CVM 跳板机 Is Exists ! ]  %s" %(rx,self.auth_key_file,self.host,ry)
            all = []
            os.chdir(self.local_path)
            Fname= open(self.auth_key_file,‘r‘)
            for line in Fname:
                #print line
                all.append(line)
            return all
            Fname.close() 
        else:
            try:
                all = []
                ls = os.linesep
                rdsa=[‘rsa‘, ‘dsa‘]
                #print self.local_path
                os.chdir(self.local_path)
                try:
                    for i in rdsa:
                        FName = open(‘id_%s.pub‘%(str(i)))
                        for line in FName:
                            #print line.rstrip(‘\n‘),
                            all.append(line)
                    F_KEY = open(self.local_path+self.auth_key_file,‘w‘)
                    F_KEY.writelines([‘%s%s‘% (x,ls)for x in all])
                    print "%sFileName ===%10s\tCVM_Address === %s\t[ CVM 跳板机 NoKey OK ] %s" %(rx,self.auth_key_file,self.host,ry)
                    return all
                    FName.close()
                    F_KEY.close()
                except IOError ,e:
                    print "*** file open failed:",e
            except:
                print "Open %s file failed !" %(self.auth_key_file)
                raise

    def rsync_ssh(self,host):
        self.host = host
        try:    
            scp = paramiko.Transport((self.host,self.port))
            scp.connect(username=self.user,password=self.passwd)
            sftp = paramiko.SFTPClient.from_transport(scp)
        except Exception,e:
            print e
            scp.close()
        else:
            try:
                sftp.mkdir(self.remote_path)
            except IOError:
                #print(‘(assuming ~/.ssh already exists)‘)
                with sftp.open(self.remote_path+self.auth_key_file,‘a+‘) as f:
                    f.write("#Create SSH Address == %s\n"%(self.host))
                with open(self.local_path+self.public_rsa_file,‘r‘) as f: 
                    data = f.read()
                sftp.open(self.remote_path+self.auth_key_file,‘a+‘).write(data)
                sftp.open(self.remote_path+self.auth_key_file,‘a‘).write(‘\n‘)
                print ‘%sFileName ===%s\tCVM_Address === %s\t[ Finish NoKey OK ]%s‘ %(rx,self.auth_key_file,self.host,ry)
            else:
                with sftp.open(self.remote_path+self.auth_key_file, ‘w‘) as f:
                    f.write("#This Is NoKey Record .\n")
                with open(self.local_path+self.public_rsa_file,‘r‘) as f:
                    data = f.read()
                sftp.open(self.remote_path+self.auth_key_file,‘w‘).write(data)
                print ‘%sFileName ===%s\tCVM_Address === %s\t[ Finish NoKey OK ]%s‘ %(rx,self.auth_key_file,self.host,ry)
if __name__ == ‘__main__‘:
    #格式化打印
    star="\033[1;33;40m=\033[0m"
    rx="\033[1;33;40m"
    ry="\033[0m"
    showStart = showServerStart()
    temp_data = idsTempDic()
    ids_sorted = sorted(temp_data.items(),key=lambda d:int(d[0]))
    for k,v in ids_sorted:
        print ‘\t‘.join(v)
    showEnd = showServerEnd()
    while True:
        ids = []
        errids = []
        try:
            inputs=str(raw_input(‘%s请输入CVM_ID[多个请用空格隔开,全部(all),反选("-"开头),返回(b)]:%s‘%(rx,ry)).strip().lower())
            print inputs
            #inputs=raw_input(‘请输入CVM_ID[多个请用空格隔开,全部(all),反选("-"开头),返回(b)]:‘).strip().lower()
            if inputs == "b":
                print ‘%s您没有选择,返回主界面! %s‘%(rx,ry)
                raw_input()
                continue
            elif inputs == "all":
                ids = temp_data.keys() # 此处返回字典key,类型为list类型
                #print ids
                break
            elif inputs.startswith(‘-‘):
                ex = inputs[1:].split()
                #print ‘‘.join(ex)
                all = temp_data.keys()
                ids = [x for x in all if x not in ex] #反选后的CVM_ID
                exids = [x for x in ex if x not in all] #反选CVM_ID
                break
            else:
                ids = inputs.split()
                ids=sorted(set(ids),key=ids.index)
                for id in ids:
                    running = temp_data.has_key(id)
                    if running == False:
                        ids.remove(id)
                        errids.append(id)
                        print ids
                    elif running == True:
                        print "%s输入正确的CVM_ID:%s %s"%(rx,id,ry)
                    else:
                        raise ValueError
            break   
        except (NameError,KeyboardInterrupt):
            print "\n"
            sys.exit()
        except (ValueError,KeyError):
            print "%s 无此CVM_ID,输入错误,请重新输入! %s"%(rx,ry)  
            raw_input()
            
    if not ids:
        print "%s你输入的CVM_ID有误%s"%(rx,ry)
    if inputs == "all":
        print "%s选择所有服务器 %s"%(rx,ry)
    elif inputs.startswith(‘-‘):
        #print exids
        print "\033[1;33;40m去除的id为:%s\033[0m "%",".join(ex)
        print "\033[1;33;40m反选后id为:\033[0m",
        for gid in ids:
            name = temp_data[gid][0]
            if name:
                print name+‘ ‘,
        print ‘\t‘        
            
    else:
        print "\033[1;33;40m去除的id为:%s\033[0m "%",".join(ids)
        print "对应的游戏服为:",
        for gid in ids:
            name = temp_data[gid][0]
            if name:
                print name+‘ ‘,
    if errids:
        print "%s你输入的id部分有误,已经排除:%s"%(rx,ry)
        print ‘\t‘.join(errids)
    try:
        if raw_input("\n确认?(y/n)") == "y":
            print "%s更新的CVM_ID为%s:"%(rx,ry)+‘ ‘.join(ids)
            sshdir ="~/.ssh"
            if os.path.exists(sshdir):
                pass
            else:
                for gid in ids:
                    Host_Wan = temp_data[gid][3]
                    Host_Lan = temp_data[gid][4]
                    print Host_Wan,Host_Lan 
                    if Host_Lan  == "10.1.1.1":
                        SSH2 = SSH()
                        #SSH2.key_rw(Host_Wan)
                        #SSH2.rsync_ssh(Host_Lan)
                        print "%s跳过运维跳板机%s"
                    else:
                        try:
                            SSH2 = SSH()
                            SSH2.rsync_ssh(Host_Lan)
                            SSH2.known_hosts(Host_Lan)
                            SSH2.known_hosts(Host_Wan)
                        except Exception as e:
                            print e
                print "%s所选CVM_ID %s已经更新完成! %s"%(rx,ids,ry)        
        else:
            sys.exit() 
    except (KeyboardInterrupt,EOFError):
        print "\n"
        sys.exit()


本文出自 “关注后台设计” 博客,转载请与作者联系!

SSH 配置

标签:ssh openssh

原文地址:http://xleft.blog.51cto.com/955567/1896097

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!