因为项目中服务器太多,ip、username 都记不住,所以写了下面脚本,用于连接服务器。
1、python+expect版本
#!/usr/bin/env python #-*- coding: utf-8 -*- import pexpect if __name__=='__main__': try: servers = [ ['kfj', 'username', '192.168.1.1', 'password'], ['csj', 'username', '192.168.1.2', 'password'], ['lcx', 'username', '192.168.1.3', 'password'], ['fbj', 'username', '192.168.1.4', 'password'] ] print "choice server :" for i in range(0,len(servers)): print "\t %d : %s " % (i,servers[i][0]) sid = int(raw_input("input id:")) if sid >= 0 and sid < len(servers): ssh = pexpect.spawn('ssh %s@%s ' % (servers[sid][1], servers[sid][2])) try: i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline(servers[sid][3]) elif i == 1: ssh.sendline('yes\n') ssh.expect('password: ') ssh.sendline(servers[sid][3]) ssh.interact() ssh.close() except pexpect.EOF: print "EOF" ssh.close() except pexpect.TIMEOUT: print "TIMEOUT" ssh.close() except Exception, e: print "error"
但是这个版本有两个问题,一是登陆上去后可用屏幕宽度好像有限制,另一个是CRT实用rz命令接受文件会有问题。时间关系没有深究,后来就改成下面shell版本了,不过这个版本需要手动输入密码,有待改进。
2、纯Shell版本
#!/bin/bash step=4 i=0 servers=("kfj" "username" "192.168.1.1" "password" "csj" "username" "192.168.1.2" "password" "lcx" "username" "192.168.1.3" "password" "fbj" "username" "192.168.1.4" "password") echo "choice the server:" while [ $i -lt ${#servers[@]} ] do echo -e "\t" $((i/step)) ":" ${servers[$i]} let i=i+step done read -p "enter the number:" choice if [[ $choice -ge 0 && $choice -lt $i/$step ]] then let choice=choice*step ssh ${servers[$choice+1]}"@"${servers[$choice+2]} else read -p "enter the number:" choice if [[ $choice -ge 0 && $choice -lt $i/$step ]] then let choice=choice*step echo ${servers[$choice+1]}"@"${servers[$choice+2]} else echo "input error!" fi fi转载标明出处:https://blog.evanxia.com/2016/06/772