使ssh记住密码

前面介绍过Conemu , Msys2工具,提升了windows本地文件操作的效率,但使用ssh时候,总需要重新输入密码,不能像SercurityCRT等工具记住密码,使用时不是很爽快。

其实通过sshpass 工具和python脚本就可以实现ssh记住密码的功能。

首先,通过pacman -S sshpass 安装sshpass

然后再编写 python脚本 如下:

#!/usr/bin/python2
import io,os,pickle,getopt,sys

DataFile='/c/Users/zhoushuang/bin/h.dat'
Hosts=[]

def loadHosts():
    global Hosts
    if os.path.isfile(DataFile):
        with open(DataFile,'rb') as f:
            Hosts = pickle.load(f)
    else:
        with open(DataFile,'wb') as f:
            pickle.dump(Hosts,f)

def saveHosts():
    global Hosts
    with open(DataFile,'wb') as f:
        pickle.dump(Hosts, f)

def printHosts():
    global Hosts
    seq = 1
    nnu = 4
    s = io.BytesIO()
    for item in Hosts:
        s.write(str(seq)+')'+item[0]+'\t')
        if 0==seq%nnu:
            s.write('\n')
        seq += 1
    s.write('\n')
    print s.getvalue()

def exessh(args): 
    os.execlp('sshpass', 'sshpass', '-p',args[1],'ssh',args[0])


def select():
    global Hosts
    printHosts()
    si=input('Select:')
    if si>0:
        si-=1
        exessh(Hosts[si])
    elif si < 0 :
        si=abs(si)
        del Hosts[si-1]
        saveHosts()

def updateHosts(args):
    global Hosts
    flag=True
    for it in Hosts:
        if it[0]==args[0]:
            it[1]=args[1]
            flag=False
            break
    if flag:
        Hosts.append(args)
    saveHosts()

def usage():
    print ''' rssh is a python script, use sshpass to login ssh server, and save pwd.
        rssh [-s]  <user@host>  <pwd>  -- firt login to a host , must use-s 
        rssh                           -- list hosts then select certain host to login
        rssh -h                        -- print help info'''

# main process
loadHosts()
try:
    opts, args = getopt.getopt(sys.argv[1:], "sh", ["start","help"])
    if len(args) == 2 :
        updateHosts(args)
    for opt, arg in opts:
        if opt in ('-s','--start') and len(args) == 2 :
            os.execlp('ssh','ssh',args[0])
            break
        if opt in ('-h','--help'):
            usage()
            exit(0)
    if len(args)==2 :
        exessh(args)
    select()
except getopt.GetoptError:
    print "ERROR"
except KeyboardInterrupt:
    pass

python 脚本的作用就是记住密码,并写入文件中。

以后采用此python 脚本登录远程机器,就能记住密码了,下次登录时可以直接选择要登录的机器。 效果如下:

zhoushuang@zhoushuang02 MSYS /c/Users/zhoushuang/bin
$ rssh
1)mcbadm@192.168.127.140        2)mcbadm@192.168.127.141        3)mcbadm@192.168.127.136

Select:

 

posted @ 2018-03-02 11:54  周双  阅读(3858)  评论(0编辑  收藏  举报