一、问题
在工作过程中,经常会遇见需要登录服务器,并且因为安全的原因,需要使用交互的方式登录,而且shell、python在工作中也经常用到,并且可以提供交互的功能。都是利用了expect、spawn、send、interact等命令。
二、实现
1、shell方式
#!/usr/bin/expect -f
set timeout 1
spawn ssh -A iwill@192.168.0.101
expect "Password:"
send "123456\r"
interact
2、python方式
#! /usr/bin/python
import sys
import pexpect
def servers_name():
servers = ['sample_app_one','sample_app_two']
return servers
def sample_app_one_ips():
tcs_ips = ['192.168.0.101','192.168.0.102']
return tcs_ips
def sample_app_two_ips():
bsn_ips = ['192.168.0.101','192.168.0.102']
return bsn_ips
def connect_server(ip):
cmd="ssh root@{}".format(ip)
child = pexpect.spawn(cmd)
child.expect ('password:')
child.sendline('123456')
child.interact()
def main():
print "server list show below : "
servers=servers_name()
index = 0
for server in servers:
index = index + 1
print '%d : %s'%(index,server)
show_msg='please select server(1...%d) : '%index
server_index = input(show_msg)
server_name=servers[server_index-1]
print 'the %s ips are below : '%server_name
server_ips_cmd= 'ips=%s_ips()'%server_name
exec(server_ips_cmd)
#print server_ips_cmd
#ips=tcs_dubbo_ips()
index = 0
for ip in ips :
index = index +1
print '%d : %s'%(index,ip)
show_msg='please select ip(i...%d) : '%index
ip_index = input(show_msg)
ip=ips[ip_index-1]
connect_server(ip)
if __name__=="__main__":
main()
三、扩展
写这些脚本,可以锻炼自己的脚本能力。