使用ready paramiko连接

时间:2014-12-30 10:37:41

标签: python ssh paramiko

想象一下当两台服务器可用时的情况。其中一个是不断地sshing到另一个并执行一些命令。由于每次都必须建立ssh连接,因此每个会话的过程大约需要5-10秒。

问题:是否可以建立一个现成的ssh连接,以减少在远程服务器上执行命令的时间?

2 个答案:

答案 0 :(得分:1)

以下是您的示例。它可以作为ssh客户端。无需每次都重新创建会话。

#!/usr/bin/env python
#-*- coding:utf-8 -*-


import os,sys  
import paramiko    
import threading    
import platform  

curr_ssh = None   
curr_prompt = ">>"  

#how to use it    
def printUsage():  
    print "    !ls                     :list sessions."  
    print "    !session id             :connect session."  
    print "    !conn host user password:connect host with user."  
    print "    !exit                   :exit."  

#connect using paramiko   
def conn(ip,username,passwd):  
    try:  
        ssh = paramiko.SSHClient()    
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    
        ssh.connect(ip,22,username,passwd,timeout=5)    
        print "Connect to ",ip," with ",username  
        global curr_prompt  
        curr_prompt=username+"@"+ip+">>"  
        return ssh  
    except:  
        return None  

#get former session
sessions=[]  
def loadSessions():  
    global sessions  
    try:  
        f = open("sessions")  
        sessions = f.readlines()  
        f.close()  
    except:  
        pass  

#main function   
def exe_cmd_local(cmd):  
    if(cmd == "!ls"):  
        loadSessions()  
        global sessions  
        i=0  
        print "Sessions:"  
        for s in sessions:  
            print"[%d] %s" %(i,s)  
            i+=1  
    else:  
        vals = cmd.split(' ')  
        if(vals[0]=="!session"):  
            id = (int)(vals[1])  
            if(id<len(sessions)):  
                os_name = platform.system()  

                new_console_cmd = ""  
                if(os_name == "Linux"):  
                    new_console_cmd="gnome-terminal -e \"./ssh.py " + sessions[id]+"\""  
                elif(os_name == "Windows"):  
                    new_console_cmd="start ssh.py " + sessions[id]  
                os.system(new_console_cmd)  
            else:  
                print "Didn't hava sessoin ",vals[1]  
        elif(vals[0]=="!conn"):  
            global curr_ssh  
            curr_ssh = conn(vals[1],vals[2],vals[3])  
            f = open("sessions","a")  
            line = vals[1]+" "+vals[2]+" "+vals[3]+"\n"  
            f.write(line)  
            f.close()  

#execute command remotely    
def exe_cmd_ssh(ssh,cmd):  
    if(ssh == None):  
        print "Didn't connect to a server. Use '!conn' to connect please."  
        return  
    stdin, stdout, stderr = ssh.exec_command(cmd)    
    print stdout.read()  
    print stderr.read()  

if __name__=='__main__':  
    loadSessions()  
    if(len(sys.argv)==4):  
        curr_ssh = conn(sys.argv[1],sys.argv[2],sys.argv[3])  
    else:  
        printUsage()  
    while True:  
        cmd = raw_input(curr_prompt)  
        if(len(cmd)==0):  
            continue  

        if(cmd == "!exit"):  
            if(curr_ssh != None):  
                curr_ssh.close();  
            break  
        else:  
            if(cmd[0] == '!'):  
                exe_cmd_local(cmd)  
            else:  
                exe_cmd_ssh(curr_ssh,cmd)  

希望它有所帮助。 :)

答案 1 :(得分:1)

可以使用现有的ssh连接,通过配置ssh来重用已经建立的连接。请参阅man ssh_config:

 ControlMaster
         Enables the sharing of multiple sessions over a single network connection.  When set to “yes”, ssh(1) will ...

所以你的〜/ .ssh / config可以包含:

Host firstServer
    ControlMaster auto
    ControlPath  ~/.ssh/tmp/controlPath_%h_%p_%r

这将创建一个套接字作为由&#39; ControlPath&#39;命名的文件。下一个ssh连接将通过同一个套接字,并且会快速闪电。

享受